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