aboutsummaryrefslogtreecommitdiffstats
path: root/icebram/icebram.cc
blob: edebb9f03d3240ea577e60164444f5d48906f442 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//
//  Copyright (C) 2016  Clifford Wolf <clifford@clifford.at>
//  Copyright (C) 2023  Sylvain Munaut <tnt@246tNt.com>
//
//  Permission to use, copy, modify, and/or distribute this software for any
//  purpose with or without fee is hereby granted, provided that the above
//  copyright notice and this permission notice appear in all copies.
//
//  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
//  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
//  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
//  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
//  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
//  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
//  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//


#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <sys/time.h>

#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <valarray>
#include <vector>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif



struct app_opts {
	char    *prog;

	int      extra_argc;
	char   **extra_argv;

	bool     generate;
	bool     verbose;
	uint32_t seed_nr;
	bool     seed;
};

static void help(const char *cmd);


// ---------------------------------------------------------------------------
// Update mode
// ---------------------------------------------------------------------------


// Hex Data File
// -------------

class HexFile
{
private:
	std::vector<std::vector<bool>> m_data;
	size_t m_word_size;

	std::vector<bool> parse_digits(std::vector<int> &digits) const;
	bool              parse_line(std::string &line);
public:
	HexFile(const char *filename, bool pad_words);
	virtual ~HexFile() { };

	void pad_words_to(size_t size);
	void pad_to(size_t size);

	size_t size()      const { return this->m_data.size(); };
	size_t word_size() const { return this->m_word_size;   };

	std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> generate_pattern(HexFile &to) const;
};

HexFile::HexFile(const char *filename, bool pad_words=false)
{
	std::ifstream stream(filename);

	if (!stream.is_open()) {
		fprintf(stderr, "Failed to open file %s\n", filename);
		exit(1);
	}

	// Parse file
	std::string line;
	for (int i=1; std::getline(stream, line); i++)
		if (!this->parse_line(line)) {
			fprintf(stderr, "Can't parse line %d of %s: %s\n", i, filename, line.c_str());
			exit(1);
		}

	// Check word size
	this->m_word_size = this->m_data.at(0).size();

	for (auto &w : this->m_data)
	{
		if ((w.size() != this->m_word_size) && !pad_words) {
			fprintf(stderr, "Inconsistent word sizes in %s\n", filename);
			exit(1);
		}
		if (w.size() > this->m_word_size)
			this->m_word_size = w.size();
	}

	// If requested, pad them
	this->pad_words_to(this->m_word_size);
}

std::vector<bool>
HexFile::parse_digits(std::vector<int> &digits) const
{
	std::vector<bool> line_data(digits.size() * 4);

	for (int i = 0; i < int(digits.size()) * 4; i++)
		if ((digits.at(digits.size() - i/4 -1) & (1 << (i%4))) != 0)
			line_data.at(i) = true;

	return line_data;
}

bool
HexFile::parse_line(std::string &line)
{
	std::vector<int> digits;

	for (char c : line) {
		if ('0' <= c && c <= '9')
			digits.push_back(c - '0');
		else if ('a' <= c && c <= 'f')
			digits.push_back(10 + c - 'a');
		else if ('A' <= c && c <= 'F')
			digits.push_back(10 + c - 'A');
		else if ('x' == c || 'X' == c ||
			 'z' == c || 'Z' == c)
			digits.push_back(0);
		else if ('_' == c)
			;
		else if (' ' == c || '\t' == c || '\r' == c) {
			if (digits.size()) {
				this->m_data.push_back(this->parse_digits(digits));
				digits.clear();
			}
		} else {
			return false;
		}
	}

	if (digits.size())
		this->m_data.push_back(this->parse_digits(digits));
	
	return true;
}

void
HexFile::pad_words_to(size_t size)
{
	if (this->m_word_size > size)
		return;

	for (auto &w : this->m_data)
		if (w.size() < size)
			w.resize(size, false);

	this->m_word_size = size;
}

void
HexFile::pad_to(size_t size)
{
	while (this->m_data.size() < size)
		this->m_data.push_back(std::vector<bool>(this->m_word_size));
}

std::map<std::vector<bool>, std::pair<std::vector<bool>, int>>
HexFile::generate_pattern(HexFile &to) const
{
	std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> pattern;

	for (int i=0; i<int(this->m_word_size); i++)
	{
		std::vector<bool> pattern_from, pattern_to;

		for (int j=0; j<int(this->m_data.size()); j++)
		{
			pattern_from.push_back(this->m_data.at(j).at(i));
			pattern_to.push_back(to.m_data.at(j).at(i));

			if (pattern_from.size() == 256) {
				if (pattern.count(pattern_from)) {
					fprintf(stderr, "Conflicting from pattern for bit slice from_hexfile[%d:%d][%d]!\n", j, j-255, i);
					exit(1);
				}
				pattern[pattern_from] = std::make_pair(pattern_to, 0);
				pattern_from.clear(), pattern_to.clear();
			}
		}
	}

	return pattern;
}


// Bitstream File
// --------------

class EBRData
{
private:
	std::vector<bool> m_data;
	int m_read_mode;

	int m_pos[2];
	int m_data_line;
	int m_config_line;
	std::vector<std::string> &m_lines;

	friend class AscFile;

protected:
	void load_data   ();
	void save_data   ();
	void load_config ();

public:
	EBRData(std::vector<std::string> &lines, int pos[2]);
	virtual ~EBRData() { };

	void apply_pattern(std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> &pattern);
};

class AscFile
{
private:
	std::vector<std::string> m_lines;
	std::map<int, EBRData> m_ebr;

	EBRData &get_ebr(int pos[2]);

public:
	AscFile();
	virtual ~AscFile() { };

	void load_config(std::istream &is);
	void save_config(std::ostream &os);

	size_t n_ebrs() const { return this->m_ebr.size(); };

	void apply_pattern(std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> &pattern);
};


EBRData::EBRData(std::vector<std::string> &lines, int pos[2]) :
	m_data(4096),
	m_pos{pos[0], pos[1]},
	m_data_line(-1), m_config_line(-1), m_lines(lines)
{

}

void
EBRData::load_data()
{
	auto si = this->m_lines.begin() + this->m_data_line + 16;
	auto ei = this->m_lines.begin() + this->m_data_line;
	int idx = 4096;

	for (auto line=si; line!=ei; line--) {
		for (char c : *line) {
			int digit;

			if ('0' <= c && c <= '9')
				digit = c - '0';
			else if ('a' <= c && c <= 'f')
				digit = 10 + c - 'a';
			else if ('A' <= c && c <= 'F')
				digit = 10 + c - 'A';
			else {
				fprintf(stderr, "Invalid char in BRAM data\n");
				exit(1);
			}

			idx -= 4;

			for (int subidx=3; subidx>=0; subidx--)
				if (digit & (1 << subidx))
					this->m_data.at(idx+subidx) = true;
		}
	}
}

void
EBRData::save_data()
{
	auto si = this->m_lines.begin() + this->m_data_line + 16;
	auto ei = this->m_lines.begin() + this->m_data_line;
	int idx = 4096;

	for (auto line=si; line!=ei; line--) {
		// Hex String
		char hex[65];
		idx -= 256;
		for (int bit=0; bit<256; bit+=4) {
			int digit = (this->m_data[idx+bit+3] ? 8 : 0) |
			            (this->m_data[idx+bit+2] ? 4 : 0) |
			            (this->m_data[idx+bit+1] ? 2 : 0) |
			            (this->m_data[idx+bit+0] ? 1 : 0);
			hex[63-(bit>>2)] = "0123456789abcdef"[digit];
		}
		hex[64] = 0;

		// Put new line
		*line = std::string(hex);
	}
}

void
EBRData::load_config()
{
	this->m_read_mode = (
		((this->m_lines.at(this->m_config_line+3).at(7) == '1') ? 2 : 0) | // RamConfig.CBIT_2
		((this->m_lines.at(this->m_config_line+4).at(7) == '1') ? 1 : 0)   // RamConfig.CBIT_3
	);
}

void
EBRData::apply_pattern(std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> &pattern)
{
	const std::map<int, std::vector<int>> subidx_map =  {
		{ 0, { 0 } },
		{ 1, { 0, 1 } },
		{ 2, { 0, 2, 1, 3 } },
		{ 3, { 0, 4, 2, 6, 1, 5, 3, 7 } },
	};

	const std::vector<int> &subidx = subidx_map.at(this->m_read_mode);
	int W = 16 >> this->m_read_mode;
	int P = 16 / W;

	for (int blk_base=0; blk_base<4096; blk_base+=4096/P)
	{
		for (int bit_base=0; bit_base<16; bit_base+=P)
		{
			std::vector<bool> fbs(256);

			// Create "From Bit Slice" from local memory
			for (int oaddr=0; oaddr<256/P; oaddr++)
				for (int iaddr=0; iaddr<P; iaddr++)
					fbs.at(oaddr*P+iaddr) = this->m_data.at(blk_base+bit_base+oaddr*16+subidx.at(iaddr));

			// Perform substitution
			auto p = pattern.find(fbs);
			if (p == pattern.end())
				continue;

			auto &tbs = p->second.first;
			p->second.second++;

			// Map "To Bit Slice" back into local memory
			for (int oaddr=0; oaddr<256/P; oaddr++)
				for (int iaddr=0; iaddr<P; iaddr++)
					this->m_data.at(blk_base+bit_base+oaddr*16+subidx.at(iaddr)) = tbs.at(oaddr*P+iaddr);
		}
	}
}


AscFile::AscFile()
{
	// Nothing to do for now
}

EBRData &
AscFile::get_ebr(int pos[2])
{
	int p = pos[0] | (pos[1] << 8);
	return (*this->m_ebr.emplace(p, EBRData{this->m_lines, pos}).first).second;
}

void
AscFile::load_config(std::istream &is)
{
	std::string line;
	int pos[2];

	// Load data and track where each EBR is configured and initialized
	for (int l=0; std::getline(is, line); l++) {
		// Save line
		this->m_lines.push_back(line);

		// Keep position of RAM infos
		if (line.substr(0, 9) == ".ram_data") {
			sscanf(line.substr(10).c_str(), "%d %d", &pos[0], &pos[1]);
			this->get_ebr(pos).m_data_line = l;
		} else if (line.substr(0, 10) == ".ramt_tile") {
			sscanf(line.substr(11).c_str(), "%d %d", &pos[0], &pos[1]);
			pos[1] -= 1;
			this->get_ebr(pos).m_config_line = l;
		}
	}

	// Only keep EBR that are initialized
	for (auto it = this->m_ebr.begin(); it != this->m_ebr.end(); )
		if (it->second.m_data_line < 0)
			it = this->m_ebr.erase(it);
		else
			++it;

	// Load data config for those
	for (auto &ebr : this->m_ebr) {
		ebr.second.load_data();
		ebr.second.load_config();
	}
}

void
AscFile::save_config(std::ostream &os)
{
	// Update all EBRs
	for (auto &ebr : this->m_ebr)
		ebr.second.save_data();

	// Output new config
	for (auto &l: this->m_lines)
		os << l << std::endl;
}

void
AscFile::apply_pattern(std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> &pattern)
{
	for (auto &ebr : this->m_ebr)
		ebr.second.apply_pattern(pattern);
}


// Update process
// ---------------

static int
update(struct app_opts *opts)
{
	if (opts->extra_argc != 2)
		help(opts->prog);

	// Parse two source files
	HexFile hf_from (opts->extra_argv[0]);
	HexFile hf_to   (opts->extra_argv[1], true);

	// Perform checks
	if ((hf_to.word_size() > 0) && (hf_from.word_size() > hf_to.word_size())) {
		if (opts->verbose)
			fprintf(stderr, "Padding to_hexfile words from %lu bits to %lu bits\n",
				hf_to.word_size(), hf_from.word_size());
		hf_to.pad_words_to(hf_from.word_size());
	}

	if (hf_to.word_size() != hf_from.word_size()) {
		fprintf(stderr, "Hexfiles have different word sizes! (%lu bits vs. %lu bits)\n",
			hf_from.word_size(), hf_to.word_size());
		return 1;
	}

	if ((hf_to.size() > 0) && (hf_from.size() > hf_to.size())) {
		if (opts->verbose)
			fprintf(stderr, "Padding to_hexfile from %lu words to %lu\n",
				hf_to.size(), hf_from.size());
		hf_to.pad_to(hf_from.size());
	}

	if (hf_to.size() != hf_from.size()) {
		fprintf(stderr, "Hexfiles have different number of words! (%lu vs. %lu)\n",
			hf_from.size(), hf_to.size());
		return 1;
	}

	if (hf_from.size() % 256 != 0) {
		fprintf(stderr, "Hexfile number of words (%lu) is not divisible by 256!\n",
			hf_from.size());
		return 1;
	}

	if (hf_from.size() == 0 || hf_from.word_size() == 0) {
		fprintf(stderr, "Empty from/to hexfiles!\n");
		return 1;
	}

	// Debug
	if (opts->verbose)
		fprintf(stderr, "Loaded pattern for %lu bits wide and %lu words deep memory.\n",
			hf_from.word_size(), hf_from.size());

	// Generate mapping for slices
	std::map<std::vector<bool>, std::pair<std::vector<bool>, int>> pattern = hf_from.generate_pattern(hf_to);
	if (opts->verbose)
		fprintf(stderr, "Extracted %lu bit slices from from/to hexfile data.\n", pattern.size());

	// Load FPGA config from stdin
	AscFile bitstream;
	bitstream.load_config(std::cin);

	if (opts->verbose)
		fprintf(stderr, "Found %lu initialized bram cells in asc file.\n", bitstream.n_ebrs());

	// Apply pattern
	bitstream.apply_pattern(pattern);

	// Check pattern was applied uniformly
	int min_replace_cnt = INT_MAX;
	int max_replace_cnt = INT_MIN;

	for (auto &it : pattern) {
		max_replace_cnt = std::max(max_replace_cnt, it.second.second);
		min_replace_cnt = std::min(min_replace_cnt, it.second.second);
	}

	if (min_replace_cnt != max_replace_cnt) {
		fprintf(stderr, "Found some bitslices up to %d times, others only %d times!\n", max_replace_cnt, min_replace_cnt);
		return 1;
	}

	if (max_replace_cnt == 0) {
		fprintf(stderr, "No memory instances were replaced.\n");
		return 1;
	}

	if (opts->verbose)
		fprintf(stderr, "Found and replaced %d instances of the memory.\n", max_replace_cnt);

	// Save new FPGA config to stdout
	bitstream.save_config(std::cout);

	return 0;
}


// ---------------------------------------------------------------------------
// Generate mode
// ---------------------------------------------------------------------------

static uint64_t
xorshift64star(uint64_t *x)
{
	*x ^= *x >> 12; // a
	*x ^= *x << 25; // b
	*x ^= *x >> 27; // c
	return *x * UINT64_C(2685821657736338717);
}

static int
generate(struct app_opts *opts)
{
	if (opts->extra_argc != 2)
		help(opts->prog);

	int width = atoi(opts->extra_argv[0]);
	int depth = atoi(opts->extra_argv[1]);

	if (width <= 0 || width % 4 != 0) {
		fprintf(stderr, "Hexfile width (%d bits) is not divisible by 4 or nonpositive!\n", width);
		exit(1);
	}

	if (depth <= 0 || depth % 256 != 0) {
		fprintf(stderr, "Hexfile number of words (%d) is not divisible by 256 or nonpositive!\n", depth);
		exit(1);
	}

	if (opts->verbose && opts->seed)
		fprintf(stderr, "Seed: %d\n", opts->seed_nr);


	if (!opts->seed) {
#if defined(__wasm)
		opts->seed_nr = 0;
#else
		opts->seed_nr = getpid();
#endif
	}

	uint64_t x;

	x =  uint64_t(opts->seed_nr) << 32;
	x ^= uint64_t(depth) << 16;
	x ^= uint64_t(width) << 10;

	xorshift64star(&x);
	xorshift64star(&x);
	xorshift64star(&x);

	if (!opts->seed) {
		struct timeval tv;
		gettimeofday(&tv, NULL);
		x ^= uint64_t(tv.tv_sec) << 20;
		x ^= uint64_t(tv.tv_usec);
	}

	xorshift64star(&x);
	xorshift64star(&x);
	xorshift64star(&x);

	for (int i = 0; i < depth; i++) {
		for (int j = 0; j < width / 4; j++) {
			int digit = xorshift64star(&x) & 15;
			std::cout << "0123456789abcdef"[digit];
		}
		std::cout << std::endl;
	}

	return 0;
}


// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

static void
help(const char *cmd)
{
	printf("\n");
	printf("Usage: %s [options] <from_hexfile> <to_hexfile>\n", cmd);
	printf("       %s [options] -g [-s <seed>] <width> <depth>\n", cmd);
	printf("\n");
	printf("Replace BRAM initialization data in a .asc file. This can be used\n");
	printf("for example to replace firmware images without re-running synthesis\n");
	printf("and place&route.\n");
	printf("\n");
	printf("    -g\n");
	printf("        generate a hex file with random contents.\n");
	printf("        use this to generate the hex file used during synthesis, then\n");
	printf("        use the same file as <from_hexfile> later.\n");
	printf("\n");
	printf("    -s <seed>\n");
	printf("        seed random generator with fixed value.\n");
	printf("\n");
	printf("    -v\n");
	printf("        verbose output\n");
	printf("\n");
	exit(1);
}

static void
opts_defaults(struct app_opts *opts)
{
	// Clear
	memset(opts, 0x00, sizeof(*opts));
}

static void
opts_parse(struct app_opts *opts, int argc, char *argv[])
{
	int opt;

	opts->prog = argv[0];

	while ((opt = getopt(argc, argv, "vgs:")) != -1)
	{
		switch (opt)
		{
		case 'v':
			opts->verbose = true;
			break;
		case 'g':
			opts->generate = true;
			break;
		case 's':
			opts->seed = true;
			opts->seed_nr = atoi(optarg);
			break;
		default:
			help(argv[0]);
		}
	}

	opts->extra_argc = argc - optind;
	opts->extra_argv = &argv[optind];
}

int main(int argc, char **argv)
{
	struct app_opts opts;

#ifdef __EMSCRIPTEN__
	EM_ASM(
		if (ENVIRONMENT_IS_NODE)
		{
			FS.mkdir('/hostcwd');
			FS.mount(NODEFS, { root: '.' }, '/hostcwd');
			FS.mkdir('/hostfs');
			FS.mount(NODEFS, { root: '/' }, '/hostfs');
		}
	);
#endif

	opts_defaults(&opts);
	opts_parse(&opts, argc, argv);

	if (opts.generate)
		return generate(&opts);
	else
		return update(&opts);
}