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