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