2ac29e3503fff24fbd44d59144086bf7045b5a66
[ecpprog.git] / ecpprog / ecpprog.c
1 /*
2 * ecpprog -- simple programming tool for FTDI-based JTAG programmers
3 * Based on iceprog
4 *
5 * Copyright (C) 2015 Clifford Wolf <clifford@clifford.at>
6 * Copyright (C) 2018 Piotr Esden-Tempski <piotr@esden.net>
7 * Copyright (C) 2020 Gregory Davill <greg.davill@gmail.com>
8 *
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 *
21 * Relevant Documents:
22 * -------------------
23 * http://www.latticesemi.com/~/media/Documents/UserManuals/EI/icestickusermanual.pdf
24 * http://www.micron.com/~/media/documents/products/data-sheet/nor-flash/serial-nor/n25q/n25q_32mb_3v_65nm.pdf
25 */
26
27 #define _GNU_SOURCE
28
29 #include <stdio.h>
30 #include <stdint.h>
31 #include <stdbool.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <errno.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39
40 #ifdef _WIN32
41 #include <io.h> /* _setmode() */
42 #include <fcntl.h> /* _O_BINARY */
43 #endif
44
45 #include "jtag.h"
46 #include "lattice_cmds.h"
47
48 static bool verbose = false;
49
50 // ---------------------------------------------------------
51 // FLASH definitions
52 // ---------------------------------------------------------
53
54 /* Flash command definitions */
55 /* This command list is based on the Winbond W25Q128JV Datasheet */
56 enum flash_cmd {
57 FC_WE = 0x06, /* Write Enable */
58 FC_SRWE = 0x50, /* Volatile SR Write Enable */
59 FC_WD = 0x04, /* Write Disable */
60 FC_RPD = 0xAB, /* Release Power-Down, returns Device ID */
61 FC_MFGID = 0x90, /* Read Manufacturer/Device ID */
62 FC_JEDECID = 0x9F, /* Read JEDEC ID */
63 FC_UID = 0x4B, /* Read Unique ID */
64 FC_RD = 0x03, /* Read Data */
65 FC_FR = 0x0B, /* Fast Read */
66 FC_PP = 0x02, /* Page Program */
67 FC_SE = 0x20, /* Sector Erase 4kb */
68 FC_BE32 = 0x52, /* Block Erase 32kb */
69 FC_BE64 = 0xD8, /* Block Erase 64kb */
70 FC_CE = 0xC7, /* Chip Erase */
71 FC_RSR1 = 0x05, /* Read Status Register 1 */
72 FC_WSR1 = 0x01, /* Write Status Register 1 */
73 FC_RSR2 = 0x35, /* Read Status Register 2 */
74 FC_WSR2 = 0x31, /* Write Status Register 2 */
75 FC_RSR3 = 0x15, /* Read Status Register 3 */
76 FC_WSR3 = 0x11, /* Write Status Register 3 */
77 FC_RSFDP = 0x5A, /* Read SFDP Register */
78 FC_ESR = 0x44, /* Erase Security Register */
79 FC_PSR = 0x42, /* Program Security Register */
80 FC_RSR = 0x48, /* Read Security Register */
81 FC_GBL = 0x7E, /* Global Block Lock */
82 FC_GBU = 0x98, /* Global Block Unlock */
83 FC_RBL = 0x3D, /* Read Block Lock */
84 FC_RPR = 0x3C, /* Read Sector Protection Registers (adesto) */
85 FC_IBL = 0x36, /* Individual Block Lock */
86 FC_IBU = 0x39, /* Individual Block Unlock */
87 FC_EPS = 0x75, /* Erase / Program Suspend */
88 FC_EPR = 0x7A, /* Erase / Program Resume */
89 FC_PD = 0xB9, /* Power-down */
90 FC_QPI = 0x38, /* Enter QPI mode */
91 FC_ERESET = 0x66, /* Enable Reset */
92 FC_RESET = 0x99, /* Reset Device */
93 };
94
95
96 // ---------------------------------------------------------
97 // JTAG -> SPI functions
98 // ---------------------------------------------------------
99
100 /*
101 * JTAG performrs all shifts LSB first, our FLSAH is expeting bytes MSB first,
102 * There are a few ways to fix this, for now we just bit-reverse all the input data to the JTAG core
103 */
104 uint8_t bit_reverse(uint8_t in){
105
106 uint8_t out = (in & 0x01) ? 0x80 : 0x00;
107 out |= (in & 0x02) ? 0x40 : 0x00;
108 out |= (in & 0x04) ? 0x20 : 0x00;
109 out |= (in & 0x08) ? 0x10 : 0x00;
110 out |= (in & 0x10) ? 0x08 : 0x00;
111 out |= (in & 0x20) ? 0x04 : 0x00;
112 out |= (in & 0x40) ? 0x02 : 0x00;
113 out |= (in & 0x80) ? 0x01 : 0x00;
114
115 return out;
116 }
117
118 void xfer_spi(uint8_t* data, uint32_t len){
119 /* Reverse bit order of all bytes */
120 for(int i = 0; i < len; i++){
121 data[i] = bit_reverse(data[i]);
122 }
123
124 /* Don't switch states if we're already in SHIFT-DR */
125 if(jtag_current_state() != STATE_SHIFT_DR)
126 jtag_go_to_state(STATE_SHIFT_DR);
127 jtag_tap_shift(data, data, len * 8, true);
128
129 /* Reverse bit order of all return bytes */
130 for(int i = 0; i < len; i++){
131 data[i] = bit_reverse(data[i]);
132 }
133 }
134
135 void send_spi(uint8_t* data, uint32_t len){
136
137 /* Flip bit order of all bytes */
138 for(int i = 0; i < len; i++){
139 data[i] = bit_reverse(data[i]);
140 }
141
142 jtag_go_to_state(STATE_SHIFT_DR);
143 /* Stay in SHIFT-DR state, this keep CS low */
144 jtag_tap_shift(data, data, len * 8, false);
145
146 /* Flip bit order of all bytes */
147 for(int i = 0; i < len; i++){
148 data[i] = bit_reverse(data[i]);
149 }
150 }
151
152
153 // ---------------------------------------------------------
154 // FLASH function implementations
155 // ---------------------------------------------------------
156
157 static void flash_read_id()
158 {
159 /* JEDEC ID structure:
160 * Byte No. | Data Type
161 * ---------+----------
162 * 0 | FC_JEDECID Request Command
163 * 1 | MFG ID
164 * 2 | Dev ID 1
165 * 3 | Dev ID 2
166 * 4 | Ext Dev Str Len
167 */
168
169 uint8_t data[260] = { FC_JEDECID };
170 int len = 5; // command + 4 response bytes
171
172 if (verbose)
173 fprintf(stderr, "read flash ID..\n");
174
175 // Write command and read first 4 bytes
176 xfer_spi(data, len);
177
178 if (data[4] == 0xFF)
179 fprintf(stderr, "Extended Device String Length is 0xFF, "
180 "this is likely a read error. Ignorig...\n");
181 else {
182 // Read extended JEDEC ID bytes
183 if (data[4] != 0) {
184 len += data[4];
185 data[0] = FC_JEDECID;
186 xfer_spi(data, len);
187 }
188 }
189
190 fprintf(stderr, "flash ID:");
191 for (int i = 1; i < len; i++)
192 fprintf(stderr, " 0x%02X", data[i]);
193 fprintf(stderr, "\n");
194 }
195
196 static void flash_reset()
197 {
198 uint8_t data[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
199
200 // This disables CRM is if it was enabled
201 jtag_go_to_state(STATE_SHIFT_DR);
202 jtag_tap_shift(data, data, 64, true);
203
204 // This disables QPI if it was enabled
205 jtag_go_to_state(STATE_SHIFT_DR);
206 jtag_tap_shift(data, data, 2, true);
207
208 // This issues a flash reset command
209 jtag_go_to_state(STATE_SHIFT_DR);
210 jtag_tap_shift(data, data, 8, true);
211 }
212
213 static uint8_t read_status_1(){
214 uint8_t data[2] = { FC_RSR1 };
215
216 xfer_spi(data, 2);
217
218 if (verbose) {
219 fprintf(stderr, "SR1: 0x%02X\n", data[1]);
220 fprintf(stderr, " - SPRL: %s\n",
221 ((data[1] & (1 << 7)) == 0) ?
222 "unlocked" :
223 "locked");
224 fprintf(stderr, " - SPM: %s\n",
225 ((data[1] & (1 << 6)) == 0) ?
226 "Byte/Page Prog Mode" :
227 "Sequential Prog Mode");
228 fprintf(stderr, " - EPE: %s\n",
229 ((data[1] & (1 << 5)) == 0) ?
230 "Erase/Prog success" :
231 "Erase/Prog error");
232 fprintf(stderr, "- SPM: %s\n",
233 ((data[1] & (1 << 4)) == 0) ?
234 "~WP asserted" :
235 "~WP deasserted");
236 fprintf(stderr, " - SWP: ");
237 switch((data[1] >> 2) & 0x3) {
238 case 0:
239 fprintf(stderr, "All sectors unprotected\n");
240 break;
241 case 1:
242 fprintf(stderr, "Some sectors protected\n");
243 break;
244 case 2:
245 fprintf(stderr, "Reserved (xxxx 10xx)\n");
246 break;
247 case 3:
248 fprintf(stderr, "All sectors protected\n");
249 break;
250 }
251 fprintf(stderr, " - WEL: %s\n",
252 ((data[1] & (1 << 1)) == 0) ?
253 "Not write enabled" :
254 "Write enabled");
255 fprintf(stderr, " - ~RDY: %s\n",
256 ((data[1] & (1 << 0)) == 0) ?
257 "Ready" :
258 "Busy");
259 }
260
261 return data[1];
262 }
263
264 static uint8_t read_status_2(){
265 uint8_t data[2] = { FC_RSR2 };
266
267 xfer_spi(data, 2);
268
269 if (verbose) {
270 fprintf(stderr, "SR2: 0x%02X\n", data[1]);
271 fprintf(stderr, " - QE: %s\n",
272 ((data[1] & (1 << 2)) == 0) ?
273 "enabled" :
274 "disabled");
275
276 }
277
278 return data[1];
279 }
280
281 static uint8_t flash_read_status()
282 {
283 uint8_t ret = read_status_1();
284 read_status_2();
285
286 return ret;
287 }
288
289
290 static void flash_write_enable()
291 {
292 if (verbose) {
293 fprintf(stderr, "status before enable:\n");
294 flash_read_status();
295 }
296
297 if (verbose)
298 fprintf(stderr, "write enable..\n");
299
300 uint8_t data[1] = { FC_WE };
301 xfer_spi(data, 1);
302
303 if (verbose) {
304 fprintf(stderr, "status after enable:\n");
305 flash_read_status();
306 }
307 }
308
309 static void flash_bulk_erase()
310 {
311 fprintf(stderr, "bulk erase..\n");
312
313 uint8_t data[1] = { FC_CE };
314 xfer_spi(data, 1);
315 }
316
317 static void flash_4kB_sector_erase(int addr)
318 {
319 fprintf(stderr, "erase 4kB sector at 0x%06X..\n", addr);
320
321 uint8_t command[4] = { FC_SE, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
322
323 xfer_spi(command, 4);
324 }
325
326 static void flash_32kB_sector_erase(int addr)
327 {
328 fprintf(stderr, "erase 64kB sector at 0x%06X..\n", addr);
329
330 uint8_t command[4] = { FC_BE32, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
331
332 xfer_spi(command, 4);
333 }
334
335 static void flash_64kB_sector_erase(int addr)
336 {
337 fprintf(stderr, "erase 64kB sector at 0x%06X..\n", addr);
338
339 uint8_t command[4] = { FC_BE64, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
340
341 xfer_spi(command, 4);
342 }
343
344 static void flash_prog(int addr, uint8_t *data, int n)
345 {
346 if (verbose)
347 fprintf(stderr, "prog 0x%06X +0x%03X..\n", addr, n);
348
349 uint8_t command[4] = { FC_PP, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
350
351 send_spi(command, 4);
352 xfer_spi(data, n);
353
354 if (verbose)
355 for (int i = 0; i < n; i++)
356 fprintf(stderr, "%02x%c", data[i], i == n - 1 || i % 32 == 31 ? '\n' : ' ');
357 }
358
359
360 static void flash_start_read(int addr)
361 {
362 if (verbose)
363 fprintf(stderr, "Start Read 0x%06X\n", addr);
364
365 uint8_t command[4] = { FC_RD, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
366
367 send_spi(command, 4);
368 }
369
370 static void flash_continue_read(uint8_t *data, int n)
371 {
372 if (verbose)
373 fprintf(stderr, "Contiune Read +0x%03X..\n", n);
374
375 memset(data, 0, n);
376 send_spi(data, n);
377
378 if (verbose)
379 for (int i = 0; i < n; i++)
380 fprintf(stderr, "%02x%c", data[i], i == n - 1 || i % 32 == 31 ? '\n' : ' ');
381 }
382
383 static void flash_wait()
384 {
385 if (verbose)
386 fprintf(stderr, "waiting..");
387
388 int count = 0;
389 while (1)
390 {
391 uint8_t data[2] = { FC_RSR1 };
392
393 xfer_spi(data, 2);
394
395 if ((data[1] & 0x01) == 0) {
396 if (count < 2) {
397 count++;
398 if (verbose) {
399 fprintf(stderr, "r");
400 fflush(stderr);
401 }
402 } else {
403 if (verbose) {
404 fprintf(stderr, "R");
405 fflush(stderr);
406 }
407 break;
408 }
409 } else {
410 if (verbose) {
411 fprintf(stderr, ".");
412 fflush(stderr);
413 }
414 count = 0;
415 }
416
417 usleep(1000);
418 }
419
420 if (verbose)
421 fprintf(stderr, "\n");
422
423 }
424
425 static void flash_disable_protection()
426 {
427 fprintf(stderr, "disable flash protection...\n");
428
429 // Write Status Register 1 <- 0x00
430 uint8_t data[2] = { FC_WSR1, 0x00 };
431 xfer_spi(data, 2);
432
433 flash_wait();
434
435 // Read Status Register 1
436 data[0] = FC_RSR1;
437
438 xfer_spi(data, 2);
439
440 if (data[1] != 0x00)
441 fprintf(stderr, "failed to disable protection, SR now equal to 0x%02x (expected 0x00)\n", data[1]);
442
443 }
444
445 // ---------------------------------------------------------
446 // ECP5 specific JTAG functions
447 // ---------------------------------------------------------
448
449
450 static void print_idcode(uint32_t idcode){
451 for(int i = 0; i < sizeof(ecp_devices)/sizeof(struct ecp_device_id); i++){
452 if(idcode == ecp_devices[i].device_id)
453 {
454 printf("IDCODE: 0x%08x (%s)\n", idcode ,ecp_devices[i].device_name);
455 return;
456 }
457 }
458 printf("IDCODE: 0x%08x does not match :(\n", idcode);
459 }
460
461 static void read_idcode(){
462
463 uint8_t data[4] = {READ_ID};
464
465 jtag_go_to_state(STATE_SHIFT_IR);
466 jtag_tap_shift(data, data, 8, true);
467
468 data[0] = 0;
469 jtag_go_to_state(STATE_SHIFT_DR);
470 jtag_tap_shift(data, data, 32, true);
471
472 uint32_t idcode = 0;
473
474 /* Format the IDCODE into a 32bit value */
475 for(int i = 0; i< 4; i++)
476 idcode = data[i] << 24 | idcode >> 8;
477
478 print_idcode(idcode);
479 }
480
481
482 static void print_status_register(uint32_t status){
483 printf("ECP5 Status Register: 0x%08x\n", status);
484
485 if(verbose){
486 printf(" Transparent Mode: %s\n", status & (1 << 0) ? "Yes" : "No" );
487 printf(" Config Target: %s\n", status & (7 << 1) ? "eFuse" : "SRAM" );
488 printf(" JTAG Active: %s\n", status & (1 << 4) ? "Yes" : "No" );
489 printf(" PWD Protection: %s\n", status & (1 << 5) ? "Yes" : "No" );
490 printf(" Decrypt Enable: %s\n", status & (1 << 7) ? "Yes" : "No" );
491 printf(" DONE: %s\n", status & (1 << 8) ? "Yes" : "No" );
492 printf(" ISC Enable: %s\n", status & (1 << 9) ? "Yes" : "No" );
493 printf(" Write Enable: %s\n", status & (1 << 10) ? "Writable" : "Not Writable");
494 printf(" Read Enable: %s\n", status & (1 << 11) ? "Readable" : "Not Readable");
495 printf(" Busy Flag: %s\n", status & (1 << 12) ? "Yes" : "No" );
496 printf(" Fail Flag: %s\n", status & (1 << 13) ? "Yes" : "No" );
497 printf(" Feature OTP: %s\n", status & (1 << 14) ? "Yes" : "No" );
498 printf(" Decrypt Only: %s\n", status & (1 << 15) ? "Yes" : "No" );
499 printf(" PWD Enable: %s\n", status & (1 << 16) ? "Yes" : "No" );
500 printf(" Encrypt Preamble: %s\n", status & (1 << 20) ? "Yes" : "No" );
501 printf(" Std Preamble: %s\n", status & (1 << 21) ? "Yes" : "No" );
502 printf(" SPIm Fail 1: %s\n", status & (1 << 22) ? "Yes" : "No" );
503
504 uint8_t bse_error = (status & (7 << 23)) >> 23;
505 switch (bse_error){
506 case 0b000: printf(" BSE Error Code: No Error (0b000)\n"); break;
507 case 0b001: printf(" BSE Error Code: ID Error (0b001)\n"); break;
508 case 0b010: printf(" BSE Error Code: CMD Error - illegal command (0b010)\n"); break;
509 case 0b011: printf(" BSE Error Code: CRC Error (0b011)\n"); break;
510 case 0b100: printf(" BSE Error Code: PRMB Error - preamble error (0b100)\n"); break;
511 case 0b101: printf(" BSE Error Code: ABRT Error - configuration aborted by the user (0b101)\n"); break;
512 case 0b110: printf(" BSE Error Code: OVFL Error - data overflow error (0b110)\n"); break;
513 case 0b111: printf(" BSE Error Code: SDM Error - bitstream pass the size of SRAM array (0b111)\n"); break;
514 }
515
516 printf(" Execution Error: %s\n", status & (1 << 26) ? "Yes" : "No" );
517 printf(" ID Error: %s\n", status & (1 << 27) ? "Yes" : "No" );
518 printf(" Invalid Command: %s\n", status & (1 << 28) ? "Yes" : "No" );
519 printf(" SED Error: %s\n", status & (1 << 29) ? "Yes" : "No" );
520 printf(" Bypass Mode: %s\n", status & (1 << 30) ? "Yes" : "No" );
521 printf(" Flow Through Mode: %s\n", status & (1 << 31) ? "Yes" : "No" );
522 }
523 }
524
525
526 static void read_status_register(){
527
528 uint8_t data[4] = {LSC_READ_STATUS};
529
530 jtag_go_to_state(STATE_SHIFT_IR);
531 jtag_tap_shift(data, data, 8, true);
532
533 data[0] = 0;
534 jtag_go_to_state(STATE_SHIFT_DR);
535 jtag_tap_shift(data, data, 32, true);
536 //jtag_go_to_state(STATE_PAUSE_DR);
537
538 uint32_t status = 0;
539
540 /* Format the IDCODE into a 32bit value */
541 for(int i = 0; i< 4; i++)
542 status = data[i] << 24 | status >> 8;
543
544 print_status_register(status);
545 }
546
547
548
549 static void enter_spi_background_mode(){
550
551 uint8_t data[4] = {0x3A};
552
553 jtag_go_to_state(STATE_SHIFT_IR);
554 jtag_tap_shift(data, data, 8, true);
555
556 /* These bytes seem to be required to un-lock the SPI interface */
557 data[0] = 0xFE;
558 data[1] = 0x68;
559 jtag_go_to_state(STATE_SHIFT_DR);
560 jtag_tap_shift(data, data, 16, true);
561
562 /* Entering IDLE is essential */
563 jtag_go_to_state(STATE_RUN_TEST_IDLE);
564 }
565
566
567 void ecp_jtag_cmd(uint8_t cmd){
568 uint8_t data[1] = {cmd};
569
570 jtag_go_to_state(STATE_SHIFT_IR);
571 jtag_tap_shift(data, data, 8, true);
572
573 jtag_go_to_state(STATE_RUN_TEST_IDLE);
574 jtag_wait_time(32);
575 }
576
577 void ecp_jtag_cmd8(uint8_t cmd, uint8_t param){
578 uint8_t data[1] = {cmd};
579
580 jtag_go_to_state(STATE_SHIFT_IR);
581 jtag_tap_shift(data, data, 8, true);
582
583 data[0] = param;
584 jtag_go_to_state(STATE_SHIFT_DR);
585 jtag_tap_shift(data, data, 8, true);
586
587 jtag_go_to_state(STATE_RUN_TEST_IDLE);
588 jtag_wait_time(32);
589 }
590
591 // ---------------------------------------------------------
592 // iceprog implementation
593 // ---------------------------------------------------------
594
595 static void help(const char *progname)
596 {
597 fprintf(stderr, "Simple programming tool for FTDI-based Lattice ECP JTAG programmers.\n");
598 fprintf(stderr, "Usage: %s [-b|-n|-c] <input file>\n", progname);
599 fprintf(stderr, " %s -r|-R<bytes> <output file>\n", progname);
600 fprintf(stderr, " %s -S <input file>\n", progname);
601 fprintf(stderr, " %s -t\n", progname);
602 fprintf(stderr, "\n");
603 fprintf(stderr, "General options:\n");
604 fprintf(stderr, " -d <device string> use the specified USB device [default: i:0x0403:0x6010 or i:0x0403:0x6014]\n");
605 fprintf(stderr, " d:<devicenode> (e.g. d:002/005)\n");
606 fprintf(stderr, " i:<vendor>:<product> (e.g. i:0x0403:0x6010)\n");
607 fprintf(stderr, " i:<vendor>:<product>:<index> (e.g. i:0x0403:0x6010:0)\n");
608 fprintf(stderr, " s:<vendor>:<product>:<serial-string>\n");
609 fprintf(stderr, " -I [ABCD] connect to the specified interface on the FTDI chip\n");
610 fprintf(stderr, " [default: A]\n");
611 fprintf(stderr, " -o <offset in bytes> start address for read/write [default: 0]\n");
612 fprintf(stderr, " (append 'k' to the argument for size in kilobytes,\n");
613 fprintf(stderr, " or 'M' for size in megabytes)\n");
614 fprintf(stderr, " -s slow SPI (50 kHz instead of 6 MHz)\n");
615 fprintf(stderr, " -v verbose output\n");
616 fprintf(stderr, " -i [4,32,64] select erase block size [default: 64k]\n");
617 fprintf(stderr, " -a reinitialize the device after any operation\n");
618 fprintf(stderr, "\n");
619 fprintf(stderr, "Mode of operation:\n");
620 fprintf(stderr, " [default] write file contents to flash, then verify\n");
621 fprintf(stderr, " -X write file contents to flash only\n");
622 fprintf(stderr, " -r read first 256 kB from flash and write to file\n");
623 fprintf(stderr, " -R <size in bytes> read the specified number of bytes from flash\n");
624 fprintf(stderr, " (append 'k' to the argument for size in kilobytes,\n");
625 fprintf(stderr, " or 'M' for size in megabytes)\n");
626 fprintf(stderr, " -c do not write flash, only verify (`check')\n");
627 fprintf(stderr, " -S perform SRAM programming\n");
628 fprintf(stderr, " -t just read the flash ID sequence\n");
629 fprintf(stderr, "\n");
630 fprintf(stderr, "Erase mode (only meaningful in default mode):\n");
631 fprintf(stderr, " [default] erase aligned chunks of 64kB in write mode\n");
632 fprintf(stderr, " This means that some data after the written data (or\n");
633 fprintf(stderr, " even before when -o is used) may be erased as well.\n");
634 fprintf(stderr, " -b bulk erase entire flash before writing\n");
635 fprintf(stderr, " -e <size in bytes> erase flash as if we were writing that number of bytes\n");
636 fprintf(stderr, " -n do not erase flash before writing\n");
637 fprintf(stderr, " -p disable write protection before erasing or writing\n");
638 fprintf(stderr, " This can be useful if flash memory appears to be\n");
639 fprintf(stderr, " bricked and won't respond to erasing or programming.\n");
640 fprintf(stderr, "\n");
641 fprintf(stderr, "Miscellaneous options:\n");
642 fprintf(stderr, " --help display this help and exit\n");
643 fprintf(stderr, " -- treat all remaining arguments as filenames\n");
644 fprintf(stderr, "\n");
645 fprintf(stderr, "Exit status:\n");
646 fprintf(stderr, " 0 on success,\n");
647 fprintf(stderr, " 1 if a non-hardware error occurred (e.g., failure to read from or\n");
648 fprintf(stderr, " write to a file, or invoked with invalid options),\n");
649 fprintf(stderr, " 2 if communication with the hardware failed (e.g., cannot find the\n");
650 fprintf(stderr, " iCE FTDI USB device),\n");
651 fprintf(stderr, " 3 if verification of the data failed.\n");
652 fprintf(stderr, "\n");
653 fprintf(stderr, "If you have a bug report, please file an issue on github:\n");
654 fprintf(stderr, " https://github.com/gregdavill/ecpprog/issues\n");
655 }
656
657 int main(int argc, char **argv)
658 {
659 /* used for error reporting */
660 const char *my_name = argv[0];
661 for (size_t i = 0; argv[0][i]; i++)
662 if (argv[0][i] == '/')
663 my_name = argv[0] + i + 1;
664
665 int read_size = 256 * 1024;
666 int erase_block_size = 64;
667 int erase_size = 0;
668 int rw_offset = 0;
669
670 bool reinitialize = false;
671 bool read_mode = false;
672 bool check_mode = false;
673 bool erase_mode = false;
674 bool bulk_erase = false;
675 bool dont_erase = false;
676 bool prog_sram = false;
677 bool test_mode = false;
678 bool slow_clock = false;
679 bool disable_protect = false;
680 bool disable_verify = false;
681 const char *filename = NULL;
682 const char *devstr = NULL;
683 int ifnum = 0;
684
685 #ifdef _WIN32
686 _setmode(_fileno(stdin), _O_BINARY);
687 _setmode(_fileno(stdout), _O_BINARY);
688 #endif
689
690 static struct option long_options[] = {
691 {"help", no_argument, NULL, -2},
692 {NULL, 0, NULL, 0}
693 };
694
695 /* Decode command line parameters */
696 int opt;
697 char *endptr;
698 while ((opt = getopt_long(argc, argv, "d:i:I:rR:e:o:cabnStvspX", long_options, NULL)) != -1) {
699 switch (opt) {
700 case 'd': /* device string */
701 devstr = optarg;
702 break;
703 case 'i': /* block erase size */
704 if (!strcmp(optarg, "4"))
705 erase_block_size = 4;
706 else if (!strcmp(optarg, "32"))
707 erase_block_size = 32;
708 else if (!strcmp(optarg, "64"))
709 erase_block_size = 64;
710 else {
711 fprintf(stderr, "%s: `%s' is not a valid erase block size (must be `4', `32' or `64')\n", my_name, optarg);
712 return EXIT_FAILURE;
713 }
714 break;
715 case 'I': /* FTDI Chip interface select */
716 if (!strcmp(optarg, "A"))
717 ifnum = 0;
718 else if (!strcmp(optarg, "B"))
719 ifnum = 1;
720 else if (!strcmp(optarg, "C"))
721 ifnum = 2;
722 else if (!strcmp(optarg, "D"))
723 ifnum = 3;
724 else {
725 fprintf(stderr, "%s: `%s' is not a valid interface (must be `A', `B', `C', or `D')\n", my_name, optarg);
726 return EXIT_FAILURE;
727 }
728 break;
729 case 'r': /* Read 256 bytes to file */
730 read_mode = true;
731 break;
732 case 'R': /* Read n bytes to file */
733 read_mode = true;
734 read_size = strtol(optarg, &endptr, 0);
735 if (*endptr == '\0')
736 /* ok */;
737 else if (!strcmp(endptr, "k"))
738 read_size *= 1024;
739 else if (!strcmp(endptr, "M"))
740 read_size *= 1024 * 1024;
741 else {
742 fprintf(stderr, "%s: `%s' is not a valid size\n", my_name, optarg);
743 return EXIT_FAILURE;
744 }
745 break;
746 case 'e': /* Erase blocks as if we were writing n bytes */
747 erase_mode = true;
748 erase_size = strtol(optarg, &endptr, 0);
749 if (*endptr == '\0')
750 /* ok */;
751 else if (!strcmp(endptr, "k"))
752 erase_size *= 1024;
753 else if (!strcmp(endptr, "M"))
754 erase_size *= 1024 * 1024;
755 else {
756 fprintf(stderr, "%s: `%s' is not a valid size\n", my_name, optarg);
757 return EXIT_FAILURE;
758 }
759 break;
760 case 'o': /* set address offset */
761 rw_offset = strtol(optarg, &endptr, 0);
762 if (*endptr == '\0')
763 /* ok */;
764 else if (!strcmp(endptr, "k"))
765 rw_offset *= 1024;
766 else if (!strcmp(endptr, "M"))
767 rw_offset *= 1024 * 1024;
768 else {
769 fprintf(stderr, "%s: `%s' is not a valid offset\n", my_name, optarg);
770 return EXIT_FAILURE;
771 }
772 break;
773 case 'c': /* do not write just check */
774 check_mode = true;
775 break;
776 case 'a': /* reinitialize ECP5 device reading new configuration */
777 reinitialize = true;
778 break;
779 case 'b': /* bulk erase before writing */
780 bulk_erase = true;
781 break;
782 case 'n': /* do not erase before writing */
783 dont_erase = true;
784 break;
785 case 'S': /* write to sram directly */
786 prog_sram = true;
787 break;
788 case 't': /* just read flash id */
789 test_mode = true;
790 break;
791 case 'v': /* provide verbose output */
792 verbose = true;
793 break;
794 case 's': /* use slow SPI clock */
795 slow_clock = true;
796 break;
797 case 'p': /* disable flash protect before erase/write */
798 disable_protect = true;
799 break;
800 case 'X': /* disable verification */
801 disable_verify = true;
802 break;
803 case -2:
804 help(argv[0]);
805 return EXIT_SUCCESS;
806 default:
807 /* error message has already been printed */
808 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
809 return EXIT_FAILURE;
810 }
811 }
812
813 /* Make sure that the combination of provided parameters makes sense */
814
815 if (read_mode + erase_mode + check_mode + prog_sram + test_mode > 1) {
816 fprintf(stderr, "%s: options `-r'/`-R', `-e`, `-c', `-S', and `-t' are mutually exclusive\n", my_name);
817 return EXIT_FAILURE;
818 }
819
820 if (bulk_erase && dont_erase) {
821 fprintf(stderr, "%s: options `-b' and `-n' are mutually exclusive\n", my_name);
822 return EXIT_FAILURE;
823 }
824
825 if (disable_protect && (read_mode || check_mode || prog_sram || test_mode)) {
826 fprintf(stderr, "%s: option `-p' only valid in programming mode\n", my_name);
827 return EXIT_FAILURE;
828 }
829
830 if (bulk_erase && (read_mode || check_mode || prog_sram || test_mode)) {
831 fprintf(stderr, "%s: option `-b' only valid in programming mode\n", my_name);
832 return EXIT_FAILURE;
833 }
834
835 if (dont_erase && (read_mode || check_mode || prog_sram || test_mode)) {
836 fprintf(stderr, "%s: option `-n' only valid in programming mode\n", my_name);
837 return EXIT_FAILURE;
838 }
839
840 if (rw_offset != 0 && prog_sram) {
841 fprintf(stderr, "%s: option `-o' not supported in SRAM mode\n", my_name);
842 return EXIT_FAILURE;
843 }
844
845 if (rw_offset != 0 && test_mode) {
846 fprintf(stderr, "%s: option `-o' not supported in test mode\n", my_name);
847 return EXIT_FAILURE;
848 }
849
850 if (optind + 1 == argc) {
851 if (test_mode) {
852 fprintf(stderr, "%s: test mode doesn't take a file name\n", my_name);
853 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
854 return EXIT_FAILURE;
855 }
856 filename = argv[optind];
857 } else if (optind != argc) {
858 fprintf(stderr, "%s: too many arguments\n", my_name);
859 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
860 return EXIT_FAILURE;
861 } else if (bulk_erase || disable_protect) {
862 filename = "/dev/null";
863 } else if (!test_mode && !erase_mode && !disable_protect) {
864 fprintf(stderr, "%s: missing argument\n", my_name);
865 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
866 return EXIT_FAILURE;
867 }
868
869 /* open input/output file in advance
870 so we can fail before initializing the hardware */
871
872 FILE *f = NULL;
873 long file_size = -1;
874
875 if (test_mode) {
876 /* nop */;
877 } else if (erase_mode) {
878 file_size = erase_size;
879 } else if (read_mode) {
880 f = (strcmp(filename, "-") == 0) ? stdout : fopen(filename, "wb");
881 if (f == NULL) {
882 fprintf(stderr, "%s: can't open '%s' for writing: ", my_name, filename);
883 perror(0);
884 return EXIT_FAILURE;
885 }
886 file_size = read_size;
887 } else {
888 f = (strcmp(filename, "-") == 0) ? stdin : fopen(filename, "rb");
889 if (f == NULL) {
890 fprintf(stderr, "%s: can't open '%s' for reading: ", my_name, filename);
891 perror(0);
892 return EXIT_FAILURE;
893 }
894
895 /* For regular programming, we need to read the file
896 twice--once for programming and once for verifying--and
897 need to know the file size in advance in order to erase
898 the correct amount of memory.
899
900 See if we can seek on the input file. Checking for "-"
901 as an argument isn't enough as we might be reading from a
902 named pipe, or contrarily, the standard input may be an
903 ordinary file. */
904
905 if (!prog_sram && !check_mode) {
906 if (fseek(f, 0L, SEEK_END) != -1) {
907 file_size = ftell(f);
908 if (file_size == -1) {
909 fprintf(stderr, "%s: %s: ftell: ", my_name, filename);
910 perror(0);
911 return EXIT_FAILURE;
912 }
913 if (fseek(f, 0L, SEEK_SET) == -1) {
914 fprintf(stderr, "%s: %s: fseek: ", my_name, filename);
915 perror(0);
916 return EXIT_FAILURE;
917 }
918 } else {
919 FILE *pipe = f;
920
921 f = tmpfile();
922 if (f == NULL) {
923 fprintf(stderr, "%s: can't open temporary file\n", my_name);
924 return EXIT_FAILURE;
925 }
926 file_size = 0;
927
928 while (true) {
929 static unsigned char buffer[4096];
930 size_t rc = fread(buffer, 1, 4096, pipe);
931 if (rc <= 0)
932 break;
933 size_t wc = fwrite(buffer, 1, rc, f);
934 if (wc != rc) {
935 fprintf(stderr, "%s: can't write to temporary file\n", my_name);
936 return EXIT_FAILURE;
937 }
938 file_size += rc;
939 }
940 fclose(pipe);
941
942 /* now seek to the beginning so we can
943 start reading again */
944 fseek(f, 0, SEEK_SET);
945 }
946 }
947 }
948
949 // ---------------------------------------------------------
950 // Initialize USB connection to FT2232H
951 // ---------------------------------------------------------
952
953 fprintf(stderr, "init..\n");
954 jtag_init(ifnum, devstr, slow_clock);
955
956 read_idcode();
957 read_status_register();
958
959 if (test_mode)
960 {
961 /* Reset ECP5 to release SPI interface */
962 ecp_jtag_cmd(ISC_ENABLE);
963 ecp_jtag_cmd(ISC_ERASE);
964 ecp_jtag_cmd(ISC_DISABLE);
965
966 /* Put device into SPI bypass mode */
967 enter_spi_background_mode();
968
969 flash_reset();
970 flash_read_id();
971
972 flash_read_status();
973 }
974 else if (prog_sram)
975 {
976 // ---------------------------------------------------------
977 // Reset
978 // ---------------------------------------------------------
979 fprintf(stderr, "reset..\n");
980
981 ecp_jtag_cmd8(ISC_ENABLE, 0);
982 ecp_jtag_cmd8(ISC_ERASE, 0);
983 ecp_jtag_cmd8(LSC_RESET_CRC, 0);
984
985 read_status_register();
986
987 // ---------------------------------------------------------
988 // Program
989 // ---------------------------------------------------------
990
991 fprintf(stderr, "programming..\n");
992 ecp_jtag_cmd(LSC_BITSTREAM_BURST);
993 while (1) {
994 const uint32_t len = 16*1024;
995 static unsigned char buffer[16*1024];
996 int rc = fread(buffer, 1, len, f);
997 if (rc <= 0)
998 break;
999 if (verbose)
1000 fprintf(stderr, "sending %d bytes.\n", rc);
1001
1002 for(int i = 0; i < rc; i++){
1003 buffer[i] = bit_reverse(buffer[i]);
1004 }
1005
1006 jtag_go_to_state(STATE_CAPTURE_DR);
1007 jtag_tap_shift(buffer, buffer, rc*8, false);
1008 }
1009
1010 ecp_jtag_cmd(ISC_DISABLE);
1011 read_status_register();
1012 }
1013 else /* program flash */
1014 {
1015 // ---------------------------------------------------------
1016 // Reset
1017 // ---------------------------------------------------------
1018
1019 fprintf(stderr, "reset..\n");
1020 /* Reset ECP5 to release SPI interface */
1021 ecp_jtag_cmd8(ISC_ENABLE, 0);
1022 ecp_jtag_cmd8(ISC_ERASE, 0);
1023 ecp_jtag_cmd8(ISC_DISABLE, 0);
1024
1025 /* Put device into SPI bypass mode */
1026 enter_spi_background_mode();
1027
1028 flash_reset();
1029
1030 flash_read_id();
1031
1032
1033 // ---------------------------------------------------------
1034 // Program
1035 // ---------------------------------------------------------
1036
1037 if (!read_mode && !check_mode)
1038 {
1039 if (disable_protect)
1040 {
1041 flash_write_enable();
1042 flash_disable_protection();
1043 }
1044
1045 if (!dont_erase)
1046 {
1047 if (bulk_erase)
1048 {
1049 flash_write_enable();
1050 flash_bulk_erase();
1051 flash_wait();
1052 }
1053 else
1054 {
1055 fprintf(stderr, "file size: %ld\n", file_size);
1056
1057 int block_size = erase_block_size << 10;
1058 int block_mask = block_size - 1;
1059 int begin_addr = rw_offset & ~block_mask;
1060 int end_addr = (rw_offset + file_size + block_mask) & ~block_mask;
1061
1062 for (int addr = begin_addr; addr < end_addr; addr += block_size) {
1063 flash_write_enable();
1064 switch(erase_block_size) {
1065 case 4:
1066 flash_4kB_sector_erase(addr);
1067 break;
1068 case 32:
1069 flash_32kB_sector_erase(addr);
1070 break;
1071 case 64:
1072 flash_64kB_sector_erase(addr);
1073 break;
1074 }
1075 if (verbose) {
1076 fprintf(stderr, "Status after block erase:\n");
1077 flash_read_status();
1078 }
1079 flash_wait();
1080 }
1081 }
1082 }
1083
1084 if (!erase_mode)
1085 {
1086 for (int rc, addr = 0; true; addr += rc) {
1087 uint8_t buffer[256];
1088
1089 /* Show progress */
1090 fprintf(stderr, "\r\033[0Kprogramming.. %04u/%04lu", addr, file_size);
1091
1092 int page_size = 256 - (rw_offset + addr) % 256;
1093 rc = fread(buffer, 1, page_size, f);
1094 if (rc <= 0)
1095 break;
1096 flash_write_enable();
1097 flash_prog(rw_offset + addr, buffer, rc);
1098 flash_wait();
1099
1100 }
1101
1102 fprintf(stderr, "\n");
1103 /* seek to the beginning for second pass */
1104 fseek(f, 0, SEEK_SET);
1105 }
1106 }
1107
1108 // ---------------------------------------------------------
1109 // Read/Verify
1110 // ---------------------------------------------------------
1111
1112 if (read_mode) {
1113
1114 flash_start_read(rw_offset);
1115 for (int addr = 0; addr < read_size; addr += 4096) {
1116 uint8_t buffer[4096];
1117
1118 /* Show progress */
1119 fprintf(stderr, "\r\033[0Kreading.. %04u/%04lu", addr, file_size);
1120
1121 flash_continue_read(buffer, 4096);
1122 fwrite(buffer, read_size - addr > 4096 ? 4096 : read_size - addr, 1, f);
1123 }
1124 fprintf(stderr, "\n");
1125 } else if (!erase_mode && !disable_verify) {
1126
1127 flash_start_read(rw_offset);
1128 for (int addr = 0; addr < read_size; addr += 4096) {
1129 uint8_t buffer_flash[4096], buffer_file[4096];
1130
1131 int rc = fread(buffer_file, 1, 4096, f);
1132 if (rc <= 0)
1133 break;
1134
1135 flash_continue_read(buffer_flash, rc);
1136
1137 /* Show progress */
1138 fprintf(stderr, "\r\033[0Kverify.. %04u/%04lu", addr + rc, file_size);
1139 if (memcmp(buffer_file, buffer_flash, rc)) {
1140 fprintf(stderr, "Found difference between flash and file!\n");
1141 jtag_error(3);
1142 }
1143
1144 }
1145 fprintf(stderr, " VERIFY OK\n");
1146 }
1147 }
1148
1149 if (reinitialize) {
1150 fprintf(stderr, "rebooting ECP5...\n");
1151 ecp_jtag_cmd(LSC_REFRESH);
1152 }
1153
1154 if (f != NULL && f != stdin && f != stdout)
1155 fclose(f);
1156
1157 // ---------------------------------------------------------
1158 // Exit
1159 // ---------------------------------------------------------
1160
1161 fprintf(stderr, "Bye.\n");
1162 jtag_deinit();
1163 return 0;
1164 }