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