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