remove some ice40 specifics
[ecpprog.git] / iceprog.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 ////flash_chip_deselect();
139
140 // TODO: Add full decode of the JEDEC ID.
141 fprintf(stderr, "flash ID:");
142 for (int i = 1; i < len; i++)
143 fprintf(stderr, " 0x%02X", data[i]);
144 fprintf(stderr, "\n");
145 }
146
147 static void flash_reset()
148 {
149 uint8_t data[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
150 xfer_spi(data, 8);
151 }
152
153 static void flash_power_up()
154 {
155 uint8_t data_rpd[1] = { FC_RPD };
156 xfer_spi(data_rpd, 1);
157 }
158
159 static void flash_power_down()
160 {
161 uint8_t data[1] = { FC_PD };
162 jtag_go_to_state(STATE_SHIFT_DR);
163 jtag_tap_shift(data, data, 8, true);
164 }
165
166 static uint8_t flash_read_status()
167 {
168 uint8_t data[2] = { FC_RSR1 };
169
170 xfer_spi(data, 2);
171
172 if (verbose) {
173 fprintf(stderr, "SR1: 0x%02X\n", data[1]);
174 fprintf(stderr, " - SPRL: %s\n",
175 ((data[1] & (1 << 7)) == 0) ?
176 "unlocked" :
177 "locked");
178 fprintf(stderr, " - SPM: %s\n",
179 ((data[1] & (1 << 6)) == 0) ?
180 "Byte/Page Prog Mode" :
181 "Sequential Prog Mode");
182 fprintf(stderr, " - EPE: %s\n",
183 ((data[1] & (1 << 5)) == 0) ?
184 "Erase/Prog success" :
185 "Erase/Prog error");
186 fprintf(stderr, "- SPM: %s\n",
187 ((data[1] & (1 << 4)) == 0) ?
188 "~WP asserted" :
189 "~WP deasserted");
190 fprintf(stderr, " - SWP: ");
191 switch((data[1] >> 2) & 0x3) {
192 case 0:
193 fprintf(stderr, "All sectors unprotected\n");
194 break;
195 case 1:
196 fprintf(stderr, "Some sectors protected\n");
197 break;
198 case 2:
199 fprintf(stderr, "Reserved (xxxx 10xx)\n");
200 break;
201 case 3:
202 fprintf(stderr, "All sectors protected\n");
203 break;
204 }
205 fprintf(stderr, " - WEL: %s\n",
206 ((data[1] & (1 << 1)) == 0) ?
207 "Not write enabled" :
208 "Write enabled");
209 fprintf(stderr, " - ~RDY: %s\n",
210 ((data[1] & (1 << 0)) == 0) ?
211 "Ready" :
212 "Busy");
213 }
214
215 usleep(1000);
216
217 return data[1];
218 }
219
220 static void flash_write_enable()
221 {
222 if (verbose) {
223 fprintf(stderr, "status before enable:\n");
224 flash_read_status();
225 }
226
227 if (verbose)
228 fprintf(stderr, "write enable..\n");
229
230 uint8_t data[1] = { FC_WE };
231 //flash_chip_select();
232 mpsse_xfer_spi(data, 1);
233 //flash_chip_deselect();
234
235 if (verbose) {
236 fprintf(stderr, "status after enable:\n");
237 flash_read_status();
238 }
239 }
240
241 static void flash_bulk_erase()
242 {
243 fprintf(stderr, "bulk erase..\n");
244
245 uint8_t data[1] = { FC_CE };
246 //flash_chip_select();
247 mpsse_xfer_spi(data, 1);
248 //flash_chip_deselect();
249 }
250
251 static void flash_4kB_sector_erase(int addr)
252 {
253 fprintf(stderr, "erase 4kB sector at 0x%06X..\n", addr);
254
255 uint8_t command[4] = { FC_SE, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
256
257 //flash_chip_select();
258 mpsse_send_spi(command, 4);
259 //flash_chip_deselect();
260 }
261
262 static void flash_32kB_sector_erase(int addr)
263 {
264 fprintf(stderr, "erase 64kB sector at 0x%06X..\n", addr);
265
266 uint8_t command[4] = { FC_BE32, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
267
268 //flash_chip_select();
269 mpsse_send_spi(command, 4);
270 //flash_chip_deselect();
271 }
272
273 static void flash_64kB_sector_erase(int addr)
274 {
275 fprintf(stderr, "erase 64kB sector at 0x%06X..\n", addr);
276
277 uint8_t command[4] = { FC_BE64, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
278
279 //flash_chip_select();
280 mpsse_send_spi(command, 4);
281 //flash_chip_deselect();
282 }
283
284 static void flash_prog(int addr, uint8_t *data, int n)
285 {
286 if (verbose)
287 fprintf(stderr, "prog 0x%06X +0x%03X..\n", addr, n);
288
289 uint8_t command[4] = { FC_PP, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
290
291 //flash_chip_select();
292 mpsse_send_spi(command, 4);
293 mpsse_send_spi(data, n);
294 //flash_chip_deselect();
295
296 if (verbose)
297 for (int i = 0; i < n; i++)
298 fprintf(stderr, "%02x%c", data[i], i == n - 1 || i % 32 == 31 ? '\n' : ' ');
299 }
300
301 static void flash_read(int addr, uint8_t *data, int n)
302 {
303 if (verbose)
304 fprintf(stderr, "read 0x%06X +0x%03X..\n", addr, n);
305
306 uint8_t command[4] = { FC_RD, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
307
308 //flash_chip_select();
309 mpsse_send_spi(command, 4);
310 memset(data, 0, n);
311 mpsse_xfer_spi(data, n);
312 //flash_chip_deselect();
313
314 if (verbose)
315 for (int i = 0; i < n; i++)
316 fprintf(stderr, "%02x%c", data[i], i == n - 1 || i % 32 == 31 ? '\n' : ' ');
317 }
318
319 static void flash_wait()
320 {
321 if (verbose)
322 fprintf(stderr, "waiting..");
323
324 int count = 0;
325 while (1)
326 {
327 uint8_t data[2] = { FC_RSR1 };
328
329 //flash_chip_select();
330 mpsse_xfer_spi(data, 2);
331 //flash_chip_deselect();
332
333 if ((data[1] & 0x01) == 0) {
334 if (count < 2) {
335 count++;
336 if (verbose) {
337 fprintf(stderr, "r");
338 fflush(stderr);
339 }
340 } else {
341 if (verbose) {
342 fprintf(stderr, "R");
343 fflush(stderr);
344 }
345 break;
346 }
347 } else {
348 if (verbose) {
349 fprintf(stderr, ".");
350 fflush(stderr);
351 }
352 count = 0;
353 }
354
355 usleep(1000);
356 }
357
358 if (verbose)
359 fprintf(stderr, "\n");
360
361 }
362
363 static void flash_disable_protection()
364 {
365 fprintf(stderr, "disable flash protection...\n");
366
367 // Write Status Register 1 <- 0x00
368 uint8_t data[2] = { FC_WSR1, 0x00 };
369 //flash_chip_select();
370 mpsse_xfer_spi(data, 2);
371 //flash_chip_deselect();
372
373 flash_wait();
374
375 // Read Status Register 1
376 data[0] = FC_RSR1;
377
378 //flash_chip_select();
379 mpsse_xfer_spi(data, 2);
380 //flash_chip_deselect();
381
382 if (data[1] != 0x00)
383 fprintf(stderr, "failed to disable protection, SR now equal to 0x%02x (expected 0x00)\n", data[1]);
384
385 }
386
387 // ---------------------------------------------------------
388 // JTAG -> SPI functions
389 // ---------------------------------------------------------
390
391 /*
392 * JTAG performrs all shifts LSB first, our FLSAH is expeting bytes MSB first,
393 * There are a few ways to fix this, for now we just bit-reverse all the input data to the JTAG core
394 */
395 uint8_t bit_reverse(uint8_t in){
396
397 uint8_t out = (in & 0x01) ? 0x80 : 0x00;
398 out |= (in & 0x02) ? 0x40 : 0x00;
399 out |= (in & 0x04) ? 0x20 : 0x00;
400 out |= (in & 0x08) ? 0x10 : 0x00;
401 out |= (in & 0x10) ? 0x08 : 0x00;
402 out |= (in & 0x20) ? 0x04 : 0x00;
403 out |= (in & 0x40) ? 0x02 : 0x00;
404 out |= (in & 0x80) ? 0x01 : 0x00;
405
406 return out;
407 }
408
409 void xfer_spi(uint8_t* data, uint32_t len){
410 /* Flip bit order of all bytes */
411 for(int i = 0; i < len; i++){
412 data[i] = bit_reverse(data[i]);
413 }
414
415 jtag_go_to_state(STATE_SHIFT_DR);
416 jtag_tap_shift(data, data, len * 8, true);
417
418 /* Flip bit order of all bytes */
419 for(int i = 0; i < len; i++){
420 data[i] = bit_reverse(data[i]);
421 }
422 }
423
424 // ---------------------------------------------------------
425 // ECP5 specific JTAG functions
426 // ---------------------------------------------------------
427
428
429 static void print_idcode(uint32_t idcode){
430 for(int i = 0; i < sizeof(ecp_devices)/sizeof(struct ecp_device_id); i++){
431 if(idcode == ecp_devices[i].device_id)
432 {
433 printf("IDCODE: 0x%08x (%s)\n", idcode ,ecp_devices[i].device_name);
434 return;
435 }
436 }
437 printf("IDCODE: 0x%08x does not match :(\n", idcode);
438 }
439
440 static void read_idcode(){
441
442 uint8_t data[4] = {READ_ID};
443
444 jtag_go_to_state(STATE_SHIFT_IR);
445 jtag_tap_shift(data, data, 8, true);
446
447 data[0] = 0;
448 jtag_go_to_state(STATE_SHIFT_DR);
449 jtag_tap_shift(data, data, 32, true);
450
451 uint32_t idcode = 0;
452
453 /* Format the IDCODE into a 32bit value */
454 for(int i = 0; i< 4; i++)
455 idcode = data[i] << 24 | idcode >> 8;
456
457 print_idcode(idcode);
458 }
459
460
461
462 static void enter_spi_background_mode(){
463
464 uint8_t data_in[4] = {0,0,0,0};
465 uint8_t data_out[4] = {0,0,0,0};
466
467 data_in[0] = 0x3A;
468 jtag_go_to_state(STATE_SHIFT_IR);
469 jtag_tap_shift(data_in, data_out, 8, true);
470
471 /* These bytes seem to be required to un-lock the SPI interface */
472 data_in[0] = 0xFE;
473 data_in[1] = 0x68;
474 jtag_go_to_state(STATE_SHIFT_DR);
475 jtag_tap_shift(data_in, data_out, 16, true);
476
477 /* Entering IDLE is essential */
478 jtag_go_to_state(STATE_RUN_TEST_IDLE);
479
480 }
481
482
483 void ecp_jtag_cmd(uint8_t cmd){
484 uint8_t data_in[1] = {0};
485 uint8_t data_out[1] = {0};
486
487 data_in[0] = cmd;
488 jtag_go_to_state(STATE_SHIFT_IR);
489 jtag_tap_shift(data_in, data_out, 8, true);
490
491 jtag_go_to_state(STATE_RUN_TEST_IDLE);
492 jtag_wait_time(10);
493 }
494
495 // ---------------------------------------------------------
496 // iceprog implementation
497 // ---------------------------------------------------------
498
499 static void help(const char *progname)
500 {
501 fprintf(stderr, "Simple programming tool for FTDI-based Lattice iCE programmers.\n");
502 fprintf(stderr, "Usage: %s [-b|-n|-c] <input file>\n", progname);
503 fprintf(stderr, " %s -r|-R<bytes> <output file>\n", progname);
504 fprintf(stderr, " %s -S <input file>\n", progname);
505 fprintf(stderr, " %s -t\n", progname);
506 fprintf(stderr, "\n");
507 fprintf(stderr, "General options:\n");
508 fprintf(stderr, " -d <device string> use the specified USB device [default: i:0x0403:0x6010 or i:0x0403:0x6014]\n");
509 fprintf(stderr, " d:<devicenode> (e.g. d:002/005)\n");
510 fprintf(stderr, " i:<vendor>:<product> (e.g. i:0x0403:0x6010)\n");
511 fprintf(stderr, " i:<vendor>:<product>:<index> (e.g. i:0x0403:0x6010:0)\n");
512 fprintf(stderr, " s:<vendor>:<product>:<serial-string>\n");
513 fprintf(stderr, " -I [ABCD] connect to the specified interface on the FTDI chip\n");
514 fprintf(stderr, " [default: A]\n");
515 fprintf(stderr, " -o <offset in bytes> start address for read/write [default: 0]\n");
516 fprintf(stderr, " (append 'k' to the argument for size in kilobytes,\n");
517 fprintf(stderr, " or 'M' for size in megabytes)\n");
518 fprintf(stderr, " -s slow SPI (50 kHz instead of 6 MHz)\n");
519 fprintf(stderr, " -v verbose output\n");
520 fprintf(stderr, " -i [4,32,64] select erase block size [default: 64k]\n");
521 fprintf(stderr, "\n");
522 fprintf(stderr, "Mode of operation:\n");
523 fprintf(stderr, " [default] write file contents to flash, then verify\n");
524 fprintf(stderr, " -X write file contents to flash only\n");
525 fprintf(stderr, " -r read first 256 kB from flash and write to file\n");
526 fprintf(stderr, " -R <size in bytes> read the specified number of bytes from flash\n");
527 fprintf(stderr, " (append 'k' to the argument for size in kilobytes,\n");
528 fprintf(stderr, " or 'M' for size in megabytes)\n");
529 fprintf(stderr, " -c do not write flash, only verify (`check')\n");
530 fprintf(stderr, " -S perform SRAM programming\n");
531 fprintf(stderr, " -t just read the flash ID sequence\n");
532 fprintf(stderr, "\n");
533 fprintf(stderr, "Erase mode (only meaningful in default mode):\n");
534 fprintf(stderr, " [default] erase aligned chunks of 64kB in write mode\n");
535 fprintf(stderr, " This means that some data after the written data (or\n");
536 fprintf(stderr, " even before when -o is used) may be erased as well.\n");
537 fprintf(stderr, " -b bulk erase entire flash before writing\n");
538 fprintf(stderr, " -e <size in bytes> erase flash as if we were writing that number of bytes\n");
539 fprintf(stderr, " -n do not erase flash before writing\n");
540 fprintf(stderr, " -p disable write protection before erasing or writing\n");
541 fprintf(stderr, " This can be useful if flash memory appears to be\n");
542 fprintf(stderr, " bricked and won't respond to erasing or programming.\n");
543 fprintf(stderr, "\n");
544 fprintf(stderr, "Miscellaneous options:\n");
545 fprintf(stderr, " --help display this help and exit\n");
546 fprintf(stderr, " -- treat all remaining arguments as filenames\n");
547 fprintf(stderr, "\n");
548 fprintf(stderr, "Exit status:\n");
549 fprintf(stderr, " 0 on success,\n");
550 fprintf(stderr, " 1 if a non-hardware error occurred (e.g., failure to read from or\n");
551 fprintf(stderr, " write to a file, or invoked with invalid options),\n");
552 fprintf(stderr, " 2 if communication with the hardware failed (e.g., cannot find the\n");
553 fprintf(stderr, " iCE FTDI USB device),\n");
554 fprintf(stderr, " 3 if verification of the data failed.\n");
555 fprintf(stderr, "\n");
556 fprintf(stderr, "Notes for iCEstick (iCE40HX-1k devel board):\n");
557 fprintf(stderr, " An unmodified iCEstick can only be programmed via the serial flash.\n");
558 fprintf(stderr, " Direct programming of the SRAM is not supported. For direct SRAM\n");
559 fprintf(stderr, " programming the flash chip and one zero ohm resistor must be desoldered\n");
560 fprintf(stderr, " and the FT2232H SI pin must be connected to the iCE SPI_SI pin, as shown\n");
561 fprintf(stderr, " in this picture:\n");
562 fprintf(stderr, " http://www.clifford.at/gallery/2014-elektronik/IMG_20141115_183838\n");
563 fprintf(stderr, "\n");
564 fprintf(stderr, "Notes for the iCE40-HX8K Breakout Board:\n");
565 fprintf(stderr, " Make sure that the jumper settings on the board match the selected\n");
566 fprintf(stderr, " mode (SRAM or FLASH). See the iCE40-HX8K user manual for details.\n");
567 fprintf(stderr, "\n");
568 fprintf(stderr, "If you have a bug report, please file an issue on github:\n");
569 fprintf(stderr, " https://github.com/cliffordwolf/icestorm/issues\n");
570 }
571
572 int main(int argc, char **argv)
573 {
574 /* used for error reporting */
575 const char *my_name = argv[0];
576 for (size_t i = 0; argv[0][i]; i++)
577 if (argv[0][i] == '/')
578 my_name = argv[0] + i + 1;
579
580 int read_size = 256 * 1024;
581 int erase_block_size = 64;
582 int erase_size = 0;
583 int rw_offset = 0;
584
585 bool read_mode = false;
586 bool check_mode = false;
587 bool erase_mode = false;
588 bool bulk_erase = false;
589 bool dont_erase = false;
590 bool prog_sram = false;
591 bool test_mode = false;
592 bool slow_clock = false;
593 bool disable_protect = false;
594 bool disable_verify = false;
595 const char *filename = NULL;
596 const char *devstr = NULL;
597 int ifnum = 0;
598
599 #ifdef _WIN32
600 _setmode(_fileno(stdin), _O_BINARY);
601 _setmode(_fileno(stdout), _O_BINARY);
602 #endif
603
604 static struct option long_options[] = {
605 {"help", no_argument, NULL, -2},
606 {NULL, 0, NULL, 0}
607 };
608
609 /* Decode command line parameters */
610 int opt;
611 char *endptr;
612 while ((opt = getopt_long(argc, argv, "d:i:I:rR:e:o:cbnStvspX", long_options, NULL)) != -1) {
613 switch (opt) {
614 case 'd': /* device string */
615 devstr = optarg;
616 break;
617 case 'i': /* block erase size */
618 if (!strcmp(optarg, "4"))
619 erase_block_size = 4;
620 else if (!strcmp(optarg, "32"))
621 erase_block_size = 32;
622 else if (!strcmp(optarg, "64"))
623 erase_block_size = 64;
624 else {
625 fprintf(stderr, "%s: `%s' is not a valid erase block size (must be `4', `32' or `64')\n", my_name, optarg);
626 return EXIT_FAILURE;
627 }
628 break;
629 case 'I': /* FTDI Chip interface select */
630 if (!strcmp(optarg, "A"))
631 ifnum = 0;
632 else if (!strcmp(optarg, "B"))
633 ifnum = 1;
634 else if (!strcmp(optarg, "C"))
635 ifnum = 2;
636 else if (!strcmp(optarg, "D"))
637 ifnum = 3;
638 else {
639 fprintf(stderr, "%s: `%s' is not a valid interface (must be `A', `B', `C', or `D')\n", my_name, optarg);
640 return EXIT_FAILURE;
641 }
642 break;
643 case 'r': /* Read 256 bytes to file */
644 read_mode = true;
645 break;
646 case 'R': /* Read n bytes to file */
647 read_mode = true;
648 read_size = strtol(optarg, &endptr, 0);
649 if (*endptr == '\0')
650 /* ok */;
651 else if (!strcmp(endptr, "k"))
652 read_size *= 1024;
653 else if (!strcmp(endptr, "M"))
654 read_size *= 1024 * 1024;
655 else {
656 fprintf(stderr, "%s: `%s' is not a valid size\n", my_name, optarg);
657 return EXIT_FAILURE;
658 }
659 break;
660 case 'e': /* Erase blocks as if we were writing n bytes */
661 erase_mode = true;
662 erase_size = strtol(optarg, &endptr, 0);
663 if (*endptr == '\0')
664 /* ok */;
665 else if (!strcmp(endptr, "k"))
666 erase_size *= 1024;
667 else if (!strcmp(endptr, "M"))
668 erase_size *= 1024 * 1024;
669 else {
670 fprintf(stderr, "%s: `%s' is not a valid size\n", my_name, optarg);
671 return EXIT_FAILURE;
672 }
673 break;
674 case 'o': /* set address offset */
675 rw_offset = strtol(optarg, &endptr, 0);
676 if (*endptr == '\0')
677 /* ok */;
678 else if (!strcmp(endptr, "k"))
679 rw_offset *= 1024;
680 else if (!strcmp(endptr, "M"))
681 rw_offset *= 1024 * 1024;
682 else {
683 fprintf(stderr, "%s: `%s' is not a valid offset\n", my_name, optarg);
684 return EXIT_FAILURE;
685 }
686 break;
687 case 'c': /* do not write just check */
688 check_mode = true;
689 break;
690 case 'b': /* bulk erase before writing */
691 bulk_erase = true;
692 break;
693 case 'n': /* do not erase before writing */
694 dont_erase = true;
695 break;
696 case 'S': /* write to sram directly */
697 prog_sram = true;
698 break;
699 case 't': /* just read flash id */
700 test_mode = true;
701 break;
702 case 'v': /* provide verbose output */
703 verbose = true;
704 break;
705 case 's': /* use slow SPI clock */
706 slow_clock = true;
707 break;
708 case 'p': /* disable flash protect before erase/write */
709 disable_protect = true;
710 break;
711 case 'X': /* disable verification */
712 disable_verify = true;
713 break;
714 case -2:
715 help(argv[0]);
716 return EXIT_SUCCESS;
717 default:
718 /* error message has already been printed */
719 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
720 return EXIT_FAILURE;
721 }
722 }
723
724 /* Make sure that the combination of provided parameters makes sense */
725
726 if (read_mode + erase_mode + check_mode + prog_sram + test_mode > 1) {
727 fprintf(stderr, "%s: options `-r'/`-R', `-e`, `-c', `-S', and `-t' are mutually exclusive\n", my_name);
728 return EXIT_FAILURE;
729 }
730
731 if (bulk_erase && dont_erase) {
732 fprintf(stderr, "%s: options `-b' and `-n' are mutually exclusive\n", my_name);
733 return EXIT_FAILURE;
734 }
735
736 if (disable_protect && (read_mode || check_mode || prog_sram || test_mode)) {
737 fprintf(stderr, "%s: option `-p' only valid in programming mode\n", my_name);
738 return EXIT_FAILURE;
739 }
740
741 if (bulk_erase && (read_mode || check_mode || prog_sram || test_mode)) {
742 fprintf(stderr, "%s: option `-b' only valid in programming mode\n", my_name);
743 return EXIT_FAILURE;
744 }
745
746 if (dont_erase && (read_mode || check_mode || prog_sram || test_mode)) {
747 fprintf(stderr, "%s: option `-n' only valid in programming mode\n", my_name);
748 return EXIT_FAILURE;
749 }
750
751 if (rw_offset != 0 && prog_sram) {
752 fprintf(stderr, "%s: option `-o' not supported in SRAM mode\n", my_name);
753 return EXIT_FAILURE;
754 }
755
756 if (rw_offset != 0 && test_mode) {
757 fprintf(stderr, "%s: option `-o' not supported in test mode\n", my_name);
758 return EXIT_FAILURE;
759 }
760
761 if (optind + 1 == argc) {
762 if (test_mode) {
763 fprintf(stderr, "%s: test mode doesn't take a file name\n", my_name);
764 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
765 return EXIT_FAILURE;
766 }
767 filename = argv[optind];
768 } else if (optind != argc) {
769 fprintf(stderr, "%s: too many arguments\n", my_name);
770 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
771 return EXIT_FAILURE;
772 } else if (bulk_erase || disable_protect) {
773 filename = "/dev/null";
774 } else if (!test_mode && !erase_mode && !disable_protect) {
775 fprintf(stderr, "%s: missing argument\n", my_name);
776 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
777 return EXIT_FAILURE;
778 }
779
780 /* open input/output file in advance
781 so we can fail before initializing the hardware */
782
783 FILE *f = NULL;
784 long file_size = -1;
785
786 if (test_mode) {
787 /* nop */;
788 } else if (erase_mode) {
789 file_size = erase_size;
790 } else if (read_mode) {
791 f = (strcmp(filename, "-") == 0) ? stdout : fopen(filename, "wb");
792 if (f == NULL) {
793 fprintf(stderr, "%s: can't open '%s' for writing: ", my_name, filename);
794 perror(0);
795 return EXIT_FAILURE;
796 }
797 } else {
798 f = (strcmp(filename, "-") == 0) ? stdin : fopen(filename, "rb");
799 if (f == NULL) {
800 fprintf(stderr, "%s: can't open '%s' for reading: ", my_name, filename);
801 perror(0);
802 return EXIT_FAILURE;
803 }
804
805 /* For regular programming, we need to read the file
806 twice--once for programming and once for verifying--and
807 need to know the file size in advance in order to erase
808 the correct amount of memory.
809
810 See if we can seek on the input file. Checking for "-"
811 as an argument isn't enough as we might be reading from a
812 named pipe, or contrarily, the standard input may be an
813 ordinary file. */
814
815 if (!prog_sram && !check_mode) {
816 if (fseek(f, 0L, SEEK_END) != -1) {
817 file_size = ftell(f);
818 if (file_size == -1) {
819 fprintf(stderr, "%s: %s: ftell: ", my_name, filename);
820 perror(0);
821 return EXIT_FAILURE;
822 }
823 if (fseek(f, 0L, SEEK_SET) == -1) {
824 fprintf(stderr, "%s: %s: fseek: ", my_name, filename);
825 perror(0);
826 return EXIT_FAILURE;
827 }
828 } else {
829 FILE *pipe = f;
830
831 f = tmpfile();
832 if (f == NULL) {
833 fprintf(stderr, "%s: can't open temporary file\n", my_name);
834 return EXIT_FAILURE;
835 }
836 file_size = 0;
837
838 while (true) {
839 static unsigned char buffer[4096];
840 size_t rc = fread(buffer, 1, 4096, pipe);
841 if (rc <= 0)
842 break;
843 size_t wc = fwrite(buffer, 1, rc, f);
844 if (wc != rc) {
845 fprintf(stderr, "%s: can't write to temporary file\n", my_name);
846 return EXIT_FAILURE;
847 }
848 file_size += rc;
849 }
850 fclose(pipe);
851
852 /* now seek to the beginning so we can
853 start reading again */
854 fseek(f, 0, SEEK_SET);
855 }
856 }
857 }
858
859 // ---------------------------------------------------------
860 // Initialize USB connection to FT2232H
861 // ---------------------------------------------------------
862
863 fprintf(stderr, "init..\n");
864
865 mpsse_init(ifnum, devstr, slow_clock);
866 mpsse_jtag_init();
867
868 read_idcode();
869
870 /* Reset ECP5 to release SPI interface */
871 ecp_jtag_cmd(ISC_ENABLE);
872 ecp_jtag_cmd(ISC_ERASE);
873 ecp_jtag_cmd(ISC_DISABLE);
874
875 /* Put device into SPI bypass mode */
876 enter_spi_background_mode();
877
878 usleep(20000);
879
880 if (test_mode)
881 {
882 flash_read_id();
883 }
884 else if (prog_sram)
885 {
886 // ---------------------------------------------------------
887 // Reset
888 // ---------------------------------------------------------
889
890 fprintf(stderr, "reset..\n");
891
892 //sram_reset();
893 usleep(100);
894
895 //sram_chip_select();
896 usleep(2000);
897
898
899 // ---------------------------------------------------------
900 // Program
901 // ---------------------------------------------------------
902
903 fprintf(stderr, "programming..\n");
904 while (1) {
905 static unsigned char buffer[4096];
906 int rc = fread(buffer, 1, 4096, f);
907 if (rc <= 0)
908 break;
909 if (verbose)
910 fprintf(stderr, "sending %d bytes.\n", rc);
911 mpsse_send_spi(buffer, rc);
912 }
913
914 mpsse_send_dummy_bytes(6);
915 mpsse_send_dummy_bit();
916
917
918 }
919 else /* program flash */
920 {
921 // ---------------------------------------------------------
922 // Reset
923 // ---------------------------------------------------------
924
925 fprintf(stderr, "reset..\n");
926
927 //flash_chip_deselect();
928 usleep(250000);
929
930
931
932 flash_reset();
933 flash_power_up();
934
935 flash_read_id();
936
937
938 // ---------------------------------------------------------
939 // Program
940 // ---------------------------------------------------------
941
942 if (!read_mode && !check_mode)
943 {
944 if (disable_protect)
945 {
946 flash_write_enable();
947 flash_disable_protection();
948 }
949
950 if (!dont_erase)
951 {
952 if (bulk_erase)
953 {
954 flash_write_enable();
955 flash_bulk_erase();
956 flash_wait();
957 }
958 else
959 {
960 fprintf(stderr, "file size: %ld\n", file_size);
961
962 int block_size = erase_block_size << 10;
963 int block_mask = block_size - 1;
964 int begin_addr = rw_offset & ~block_mask;
965 int end_addr = (rw_offset + file_size + block_mask) & ~block_mask;
966
967 for (int addr = begin_addr; addr < end_addr; addr += block_size) {
968 flash_write_enable();
969 switch(erase_block_size) {
970 case 4:
971 flash_4kB_sector_erase(addr);
972 break;
973 case 32:
974 flash_32kB_sector_erase(addr);
975 break;
976 case 64:
977 flash_64kB_sector_erase(addr);
978 break;
979 }
980 if (verbose) {
981 fprintf(stderr, "Status after block erase:\n");
982 flash_read_status();
983 }
984 flash_wait();
985 }
986 }
987 }
988
989 if (!erase_mode)
990 {
991 fprintf(stderr, "programming..\n");
992
993 for (int rc, addr = 0; true; addr += rc) {
994 uint8_t buffer[256];
995 int page_size = 256 - (rw_offset + addr) % 256;
996 rc = fread(buffer, 1, page_size, f);
997 if (rc <= 0)
998 break;
999 flash_write_enable();
1000 flash_prog(rw_offset + addr, buffer, rc);
1001 flash_wait();
1002 }
1003
1004 /* seek to the beginning for second pass */
1005 fseek(f, 0, SEEK_SET);
1006 }
1007 }
1008
1009 // ---------------------------------------------------------
1010 // Read/Verify
1011 // ---------------------------------------------------------
1012
1013 if (read_mode) {
1014 fprintf(stderr, "reading..\n");
1015 for (int addr = 0; addr < read_size; addr += 256) {
1016 uint8_t buffer[256];
1017 flash_read(rw_offset + addr, buffer, 256);
1018 fwrite(buffer, read_size - addr > 256 ? 256 : read_size - addr, 1, f);
1019 }
1020 } else if (!erase_mode && !disable_verify) {
1021 fprintf(stderr, "reading..\n");
1022 for (int addr = 0; true; addr += 256) {
1023 uint8_t buffer_flash[256], buffer_file[256];
1024 int rc = fread(buffer_file, 1, 256, f);
1025 if (rc <= 0)
1026 break;
1027 flash_read(rw_offset + addr, buffer_flash, rc);
1028 if (memcmp(buffer_file, buffer_flash, rc)) {
1029 fprintf(stderr, "Found difference between flash and file!\n");
1030 mpsse_error(3);
1031 }
1032 }
1033
1034 fprintf(stderr, "VERIFY OK\n");
1035 }
1036
1037
1038 // ---------------------------------------------------------
1039 // Reset
1040 // ---------------------------------------------------------
1041
1042 //flash_power_down();
1043
1044 usleep(250000);
1045
1046
1047 }
1048
1049 if (f != NULL && f != stdin && f != stdout)
1050 fclose(f);
1051
1052 // ---------------------------------------------------------
1053 // Exit
1054 // ---------------------------------------------------------
1055
1056 fprintf(stderr, "Bye.\n");
1057 mpsse_close();
1058 return 0;
1059 }