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