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