Update README
[ecpprog.git] / ecpprog / ecpprog.c
1 /*
2 * ecpprog -- simple programming tool for FTDI-based JTAG programmers
3 * Based on iceprog
4 *
5 * Copyright (C) 2015 Clifford Wolf <clifford@clifford.at>
6 * Copyright (C) 2018 Piotr Esden-Tempski <piotr@esden.net>
7 * Copyright (C) 2020 Gregory Davill <greg.davill@gmail.com>
8 *
9 * Permission to use, copy, modify, and/or distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 *
21 * Relevant Documents:
22 * -------------------
23 * http://www.latticesemi.com/~/media/Documents/UserManuals/EI/icestickusermanual.pdf
24 * http://www.micron.com/~/media/documents/products/data-sheet/nor-flash/serial-nor/n25q/n25q_32mb_3v_65nm.pdf
25 */
26
27 #define _GNU_SOURCE
28
29 #include <stdio.h>
30 #include <stdint.h>
31 #include <stdbool.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <getopt.h>
36 #include <errno.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39
40 #ifdef _WIN32
41 #include <io.h> /* _setmode() */
42 #include <fcntl.h> /* _O_BINARY */
43 #endif
44
45 #include "jtag.h"
46 #include "lattice_cmds.h"
47
48 static bool verbose = false;
49
50 enum device_type {
51 TYPE_NONE = 0,
52 TYPE_ECP5 = 1,
53 TYPE_NX = 2,
54 };
55
56 struct device_info {
57 const char* name;
58 uint32_t id;
59 enum device_type type;
60 };
61
62 static struct device_info connected_device = {0};
63
64
65 // ---------------------------------------------------------
66 // FLASH definitions
67 // ---------------------------------------------------------
68
69 /* Flash command definitions */
70 /* This command list is based on the Winbond W25Q128JV Datasheet */
71 enum flash_cmd {
72 FC_WE = 0x06, /* Write Enable */
73 FC_SRWE = 0x50, /* Volatile SR Write Enable */
74 FC_WD = 0x04, /* Write Disable */
75 FC_RPD = 0xAB, /* Release Power-Down, returns Device ID */
76 FC_MFGID = 0x90, /* Read Manufacturer/Device ID */
77 FC_JEDECID = 0x9F, /* Read JEDEC ID */
78 FC_UID = 0x4B, /* Read Unique ID */
79 FC_RD = 0x03, /* Read Data */
80 FC_FR = 0x0B, /* Fast Read */
81 FC_PP = 0x02, /* Page Program */
82 FC_SE = 0x20, /* Sector Erase 4kb */
83 FC_BE32 = 0x52, /* Block Erase 32kb */
84 FC_BE64 = 0xD8, /* Block Erase 64kb */
85 FC_CE = 0xC7, /* Chip Erase */
86 FC_RSR1 = 0x05, /* Read Status Register 1 */
87 FC_WSR1 = 0x01, /* Write Status Register 1 */
88 FC_RSR2 = 0x35, /* Read Status Register 2 */
89 FC_WSR2 = 0x31, /* Write Status Register 2 */
90 FC_RSR3 = 0x15, /* Read Status Register 3 */
91 FC_WSR3 = 0x11, /* Write Status Register 3 */
92 FC_RSFDP = 0x5A, /* Read SFDP Register */
93 FC_ESR = 0x44, /* Erase Security Register */
94 FC_PSR = 0x42, /* Program Security Register */
95 FC_RSR = 0x48, /* Read Security Register */
96 FC_GBL = 0x7E, /* Global Block Lock */
97 FC_GBU = 0x98, /* Global Block Unlock */
98 FC_RBL = 0x3D, /* Read Block Lock */
99 FC_RPR = 0x3C, /* Read Sector Protection Registers (adesto) */
100 FC_IBL = 0x36, /* Individual Block Lock */
101 FC_IBU = 0x39, /* Individual Block Unlock */
102 FC_EPS = 0x75, /* Erase / Program Suspend */
103 FC_EPR = 0x7A, /* Erase / Program Resume */
104 FC_PD = 0xB9, /* Power-down */
105 FC_QPI = 0x38, /* Enter QPI mode */
106 FC_ERESET = 0x66, /* Enable Reset */
107 FC_RESET = 0x99, /* Reset Device */
108 };
109
110
111 // ---------------------------------------------------------
112 // JTAG -> SPI functions
113 // ---------------------------------------------------------
114
115 /*
116 * JTAG performrs all shifts LSB first, our FLSAH is expeting bytes MSB first,
117 * There are a few ways to fix this, for now we just bit-reverse all the input data to the JTAG core
118 */
119 uint8_t bit_reverse(uint8_t in){
120
121 uint8_t out = (in & 0x01) ? 0x80 : 0x00;
122 out |= (in & 0x02) ? 0x40 : 0x00;
123 out |= (in & 0x04) ? 0x20 : 0x00;
124 out |= (in & 0x08) ? 0x10 : 0x00;
125 out |= (in & 0x10) ? 0x08 : 0x00;
126 out |= (in & 0x20) ? 0x04 : 0x00;
127 out |= (in & 0x40) ? 0x02 : 0x00;
128 out |= (in & 0x80) ? 0x01 : 0x00;
129
130 return out;
131 }
132
133 void xfer_spi(uint8_t* data, uint32_t len){
134 /* Reverse bit order of all bytes */
135 for(int i = 0; i < len; i++){
136 data[i] = bit_reverse(data[i]);
137 }
138
139 /* Don't switch states if we're already in SHIFT-DR */
140 if(jtag_current_state() != STATE_SHIFT_DR)
141 jtag_go_to_state(STATE_SHIFT_DR);
142 jtag_tap_shift(data, data, len * 8, true);
143
144 /* Reverse bit order of all return bytes */
145 for(int i = 0; i < len; i++){
146 data[i] = bit_reverse(data[i]);
147 }
148 }
149
150 void send_spi(uint8_t* data, uint32_t len){
151
152 /* Flip bit order of all bytes */
153 for(int i = 0; i < len; i++){
154 data[i] = bit_reverse(data[i]);
155 }
156
157 jtag_go_to_state(STATE_SHIFT_DR);
158 /* Stay in SHIFT-DR state, this keep CS low */
159 jtag_tap_shift(data, data, len * 8, false);
160
161 /* Flip bit order of all bytes */
162 for(int i = 0; i < len; i++){
163 data[i] = bit_reverse(data[i]);
164 }
165 }
166
167
168 // ---------------------------------------------------------
169 // FLASH function implementations
170 // ---------------------------------------------------------
171
172 static void flash_read_id()
173 {
174 /* JEDEC ID structure:
175 * Byte No. | Data Type
176 * ---------+----------
177 * 0 | FC_JEDECID Request Command
178 * 1 | MFG ID
179 * 2 | Dev ID 1
180 * 3 | Dev ID 2
181 * 4 | Ext Dev Str Len
182 */
183
184 uint8_t data[260] = { FC_JEDECID };
185 int len = 4; // command + 4 response bytes
186
187 if (verbose)
188 fprintf(stderr, "read flash ID..\n");
189
190 // Write command and read first 4 bytes
191 xfer_spi(data, len);
192
193 fprintf(stderr, "flash ID:");
194 for (int i = 1; i < len; i++)
195 fprintf(stderr, " 0x%02X", data[i]);
196 fprintf(stderr, "\n");
197 }
198
199 static void flash_reset()
200 {
201 uint8_t data[8] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
202
203 // This disables CRM is if it was enabled
204 jtag_go_to_state(STATE_SHIFT_DR);
205 jtag_tap_shift(data, data, 64, true);
206
207 // This disables QPI if it was enabled
208 jtag_go_to_state(STATE_SHIFT_DR);
209 jtag_tap_shift(data, data, 2, true);
210
211 // This issues a flash reset command
212 jtag_go_to_state(STATE_SHIFT_DR);
213 jtag_tap_shift(data, data, 8, true);
214 }
215
216 static uint8_t read_status_1(){
217 uint8_t data[2] = { FC_RSR1 };
218
219 xfer_spi(data, 2);
220
221 if (verbose) {
222 fprintf(stderr, "SR1: 0x%02X\n", data[1]);
223 fprintf(stderr, " - SPRL: %s\n",
224 ((data[1] & (1 << 7)) == 0) ?
225 "unlocked" :
226 "locked");
227 fprintf(stderr, " - SPM: %s\n",
228 ((data[1] & (1 << 6)) == 0) ?
229 "Byte/Page Prog Mode" :
230 "Sequential Prog Mode");
231 fprintf(stderr, " - EPE: %s\n",
232 ((data[1] & (1 << 5)) == 0) ?
233 "Erase/Prog success" :
234 "Erase/Prog error");
235 fprintf(stderr, "- SPM: %s\n",
236 ((data[1] & (1 << 4)) == 0) ?
237 "~WP asserted" :
238 "~WP deasserted");
239 fprintf(stderr, " - SWP: ");
240 switch((data[1] >> 2) & 0x3) {
241 case 0:
242 fprintf(stderr, "All sectors unprotected\n");
243 break;
244 case 1:
245 fprintf(stderr, "Some sectors protected\n");
246 break;
247 case 2:
248 fprintf(stderr, "Reserved (xxxx 10xx)\n");
249 break;
250 case 3:
251 fprintf(stderr, "All sectors protected\n");
252 break;
253 }
254 fprintf(stderr, " - WEL: %s\n",
255 ((data[1] & (1 << 1)) == 0) ?
256 "Not write enabled" :
257 "Write enabled");
258 fprintf(stderr, " - ~RDY: %s\n",
259 ((data[1] & (1 << 0)) == 0) ?
260 "Ready" :
261 "Busy");
262 }
263
264 return data[1];
265 }
266
267 static uint8_t read_status_2(){
268 uint8_t data[2] = { FC_RSR2 };
269
270 xfer_spi(data, 2);
271
272 if (verbose) {
273 fprintf(stderr, "SR2: 0x%02X\n", data[1]);
274 fprintf(stderr, " - QE: %s\n",
275 ((data[1] & (1 << 2)) == 0) ?
276 "enabled" :
277 "disabled");
278
279 }
280
281 return data[1];
282 }
283
284 static uint8_t flash_read_status()
285 {
286 uint8_t ret = read_status_1();
287 read_status_2();
288
289 return ret;
290 }
291
292
293 static void flash_write_enable()
294 {
295 if (verbose) {
296 fprintf(stderr, "status before enable:\n");
297 flash_read_status();
298 }
299
300 if (verbose)
301 fprintf(stderr, "write enable..\n");
302
303 uint8_t data[1] = { FC_WE };
304 xfer_spi(data, 1);
305
306 if (verbose) {
307 fprintf(stderr, "status after enable:\n");
308 flash_read_status();
309 }
310 }
311
312 static void flash_bulk_erase()
313 {
314 fprintf(stderr, "bulk erase..\n");
315
316 uint8_t data[1] = { FC_CE };
317 xfer_spi(data, 1);
318 }
319
320 static void flash_4kB_sector_erase(int addr)
321 {
322 fprintf(stderr, "erase 4kB sector at 0x%06X..\n", addr);
323
324 uint8_t command[4] = { FC_SE, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
325
326 xfer_spi(command, 4);
327 }
328
329 static void flash_32kB_sector_erase(int addr)
330 {
331 fprintf(stderr, "erase 64kB sector at 0x%06X..\n", addr);
332
333 uint8_t command[4] = { FC_BE32, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
334
335 xfer_spi(command, 4);
336 }
337
338 static void flash_64kB_sector_erase(int addr)
339 {
340 fprintf(stderr, "erase 64kB sector at 0x%06X..\n", addr);
341
342 uint8_t command[4] = { FC_BE64, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
343
344 xfer_spi(command, 4);
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 send_spi(command, 4);
355 xfer_spi(data, n);
356
357 if (verbose)
358 for (int i = 0; i < n; i++)
359 fprintf(stderr, "%02x%c", data[i], i == n - 1 || i % 32 == 31 ? '\n' : ' ');
360 }
361
362
363 static void flash_start_read(int addr)
364 {
365 if (verbose)
366 fprintf(stderr, "Start Read 0x%06X\n", addr);
367
368 uint8_t command[4] = { FC_RD, (uint8_t)(addr >> 16), (uint8_t)(addr >> 8), (uint8_t)addr };
369
370 send_spi(command, 4);
371 }
372
373 static void flash_continue_read(uint8_t *data, int n)
374 {
375 if (verbose)
376 fprintf(stderr, "Contiune Read +0x%03X..\n", n);
377
378 memset(data, 0, n);
379 send_spi(data, n);
380
381 if (verbose)
382 for (int i = 0; i < n; i++)
383 fprintf(stderr, "%02x%c", data[i], i == n - 1 || i % 32 == 31 ? '\n' : ' ');
384 }
385
386 static void flash_wait()
387 {
388 if (verbose)
389 fprintf(stderr, "waiting..");
390
391 int count = 0;
392 while (1)
393 {
394 uint8_t data[2] = { FC_RSR1 };
395
396 xfer_spi(data, 2);
397
398 if ((data[1] & 0x01) == 0) {
399 if (count < 2) {
400 count++;
401 if (verbose) {
402 fprintf(stderr, "r");
403 fflush(stderr);
404 }
405 } else {
406 if (verbose) {
407 fprintf(stderr, "R");
408 fflush(stderr);
409 }
410 break;
411 }
412 } else {
413 if (verbose) {
414 fprintf(stderr, ".");
415 fflush(stderr);
416 }
417 count = 0;
418 }
419
420 usleep(1000);
421 }
422
423 if (verbose)
424 fprintf(stderr, "\n");
425
426 }
427
428 static void flash_disable_protection()
429 {
430 fprintf(stderr, "disable flash protection...\n");
431
432 // Write Status Register 1 <- 0x00
433 uint8_t data[2] = { FC_WSR1, 0x00 };
434 xfer_spi(data, 2);
435
436 flash_wait();
437
438 // Read Status Register 1
439 data[0] = FC_RSR1;
440
441 xfer_spi(data, 2);
442
443 if (data[1] != 0x00)
444 fprintf(stderr, "failed to disable protection, SR now equal to 0x%02x (expected 0x00)\n", data[1]);
445
446 }
447
448 // ---------------------------------------------------------
449 // ECP5 specific JTAG functions
450 // ---------------------------------------------------------
451
452 static void print_idcode(uint32_t idcode){
453 connected_device.id = idcode;
454
455 /* ECP5 Parts */
456 for(int i = 0; i < sizeof(ecp_devices)/sizeof(struct device_id_pair); i++){
457 if(idcode == ecp_devices[i].device_id)
458 {
459 connected_device.name = ecp_devices[i].device_name;
460 connected_device.type = TYPE_ECP5;
461 printf("IDCODE: 0x%08x (%s)\n", idcode ,ecp_devices[i].device_name);
462 return;
463 }
464 }
465
466 /* NX Parts */
467 for(int i = 0; i < sizeof(nx_devices)/sizeof(struct device_id_pair); i++){
468 if(idcode == nx_devices[i].device_id)
469 {
470 connected_device.name = nx_devices[i].device_name;
471 connected_device.type = TYPE_NX;
472 printf("IDCODE: 0x%08x (%s)\n", idcode ,nx_devices[i].device_name);
473 return;
474 }
475 }
476 printf("IDCODE: 0x%08x does not match :(\n", idcode);
477 }
478
479 static void read_idcode(){
480
481 uint8_t data[4] = {READ_ID};
482
483 jtag_go_to_state(STATE_SHIFT_IR);
484 jtag_tap_shift(data, data, 8, true);
485
486 data[0] = 0;
487 jtag_go_to_state(STATE_SHIFT_DR);
488 jtag_tap_shift(data, data, 32, true);
489
490 uint32_t idcode = 0;
491
492 /* Format the IDCODE into a 32bit value */
493 for(int i = 0; i< 4; i++)
494 idcode = data[i] << 24 | idcode >> 8;
495
496 print_idcode(idcode);
497 }
498
499 void print_ecp5_status_register(uint32_t status){
500 printf("ECP5 Status Register: 0x%08x\n", status);
501
502 if(verbose){
503 printf(" Transparent Mode: %s\n", status & (1 << 0) ? "Yes" : "No" );
504 printf(" Config Target: %s\n", status & (7 << 1) ? "eFuse" : "SRAM" );
505 printf(" JTAG Active: %s\n", status & (1 << 4) ? "Yes" : "No" );
506 printf(" PWD Protection: %s\n", status & (1 << 5) ? "Yes" : "No" );
507 printf(" Decrypt Enable: %s\n", status & (1 << 7) ? "Yes" : "No" );
508 printf(" DONE: %s\n", status & (1 << 8) ? "Yes" : "No" );
509 printf(" ISC Enable: %s\n", status & (1 << 9) ? "Yes" : "No" );
510 printf(" Write Enable: %s\n", status & (1 << 10) ? "Writable" : "Not Writable");
511 printf(" Read Enable: %s\n", status & (1 << 11) ? "Readable" : "Not Readable");
512 printf(" Busy Flag: %s\n", status & (1 << 12) ? "Yes" : "No" );
513 printf(" Fail Flag: %s\n", status & (1 << 13) ? "Yes" : "No" );
514 printf(" Feature OTP: %s\n", status & (1 << 14) ? "Yes" : "No" );
515 printf(" Decrypt Only: %s\n", status & (1 << 15) ? "Yes" : "No" );
516 printf(" PWD Enable: %s\n", status & (1 << 16) ? "Yes" : "No" );
517 printf(" Encrypt Preamble: %s\n", status & (1 << 20) ? "Yes" : "No" );
518 printf(" Std Preamble: %s\n", status & (1 << 21) ? "Yes" : "No" );
519 printf(" SPIm Fail 1: %s\n", status & (1 << 22) ? "Yes" : "No" );
520
521 uint8_t bse_error = (status & (7 << 23)) >> 23;
522 switch (bse_error){
523 case 0b000: printf(" BSE Error Code: No Error (0b000)\n"); break;
524 case 0b001: printf(" BSE Error Code: ID Error (0b001)\n"); break;
525 case 0b010: printf(" BSE Error Code: CMD Error - illegal command (0b010)\n"); break;
526 case 0b011: printf(" BSE Error Code: CRC Error (0b011)\n"); break;
527 case 0b100: printf(" BSE Error Code: PRMB Error - preamble error (0b100)\n"); break;
528 case 0b101: printf(" BSE Error Code: ABRT Error - configuration aborted by the user (0b101)\n"); break;
529 case 0b110: printf(" BSE Error Code: OVFL Error - data overflow error (0b110)\n"); break;
530 case 0b111: printf(" BSE Error Code: SDM Error - bitstream pass the size of SRAM array (0b111)\n"); break;
531 }
532
533 printf(" Execution Error: %s\n", status & (1 << 26) ? "Yes" : "No" );
534 printf(" ID Error: %s\n", status & (1 << 27) ? "Yes" : "No" );
535 printf(" Invalid Command: %s\n", status & (1 << 28) ? "Yes" : "No" );
536 printf(" SED Error: %s\n", status & (1 << 29) ? "Yes" : "No" );
537 printf(" Bypass Mode: %s\n", status & (1 << 30) ? "Yes" : "No" );
538 printf(" Flow Through Mode: %s\n", status & (1 << 31) ? "Yes" : "No" );
539 }
540 }
541
542 void print_nx_status_register(uint64_t status){
543 printf("NX Status Register: 0x%016lx\n", status);
544
545 if(verbose){
546 printf(" Transparent Mode: %s\n", status & (1 << 0) ? "Yes" : "No" );
547 printf(" Config Target: ");
548 uint8_t config_target = status & (0b111 << 1) >> 1;
549 switch (config_target){
550 case 0b000: printf("SRAM (0b000)\n"); break;
551 case 0b001: printf("EFUSE Normal (0b001)\n"); break;
552 case 0b010: printf("EFUSE Pseudo (0b010)\n"); break;
553 case 0b011: printf("EFUSE Safe (0b011)\n"); break;
554 default: printf("Invalid (%u)\n", config_target); break;
555 }
556
557 printf(" JTAG Active: %s\n", status & (1 << 4) ? "Yes" : "No" );
558 printf(" PWD Protection: %s\n", status & (1 << 5) ? "Yes" : "No" );
559 printf(" OTP: %s\n", status & (1 << 6) ? "Yes" : "No" );
560 printf(" DONE: %s\n", status & (1 << 8) ? "Yes" : "No" );
561 printf(" ISC Enable: %s\n", status & (1 << 9) ? "Yes" : "No" );
562 printf(" Write Enable: %s\n", status & (1 << 10) ? "Writable" : "Not Writable");
563 printf(" Read Enable: %s\n", status & (1 << 11) ? "Readable" : "Not Readable");
564 printf(" Busy Flag: %s\n", status & (1 << 12) ? "Yes" : "No" );
565 printf(" Fail Flag: %s\n", status & (1 << 13) ? "Yes" : "No" );
566 printf(" Decrypt Only: %s\n", status & (1 << 15) ? "Yes" : "No" );
567 printf(" PWD Enable: %s\n", status & (1 << 16) ? "Yes" : "No" );
568 printf(" PWD All: %s\n", status & (1 << 17) ? "Yes" : "No" );
569 printf(" CID EN: %s\n", status & (1 << 18) ? "Yes" : "No" );
570 printf(" Encrypt Preamble: %s\n", status & (1 << 21) ? "Yes" : "No" );
571 printf(" Std Preamble: %s\n", status & (1 << 22) ? "Yes" : "No" );
572 printf(" SPIm Fail 1: %s\n", status & (1 << 23) ? "Yes" : "No" );
573
574 uint8_t bse_error = (status & (0b1111 << 24)) >> 24;
575 switch (bse_error){
576 case 0b0000: printf(" BSE Error Code: No Error (0b000)\n"); break;
577 case 0b0001: printf(" BSE Error Code: ID Error (0b001)\n"); break;
578 case 0b0010: printf(" BSE Error Code: CMD Error - illegal command (0b010)\n"); break;
579 case 0b0011: printf(" BSE Error Code: CRC Error (0b011)\n"); break;
580 case 0b0100: printf(" BSE Error Code: PRMB Error - preamble error (0b100)\n"); break;
581 case 0b0101: printf(" BSE Error Code: ABRT Error - configuration aborted by the user (0b101)\n"); break;
582 case 0b0110: printf(" BSE Error Code: OVFL Error - data overflow error (0b110)\n"); break;
583 case 0b0111: printf(" BSE Error Code: SDM Error - bitstream pass the size of SRAM array (0b111)\n"); break;
584 case 0b1000: printf(" BSE Error Code: Authentication Error (0b1000)\n"); break;
585 case 0b1001: printf(" BSE Error Code: Authentication Setup Error (0b1001)\n"); break;
586 case 0b1010: printf(" BSE Error Code: Bitstream Engine Timeout Error (0b1010) \n"); break;
587 }
588
589 printf(" Execution Error: %s\n", status & (1 << 28) ? "Yes" : "No" );
590 printf(" ID Error: %s\n", status & (1 << 29) ? "Yes" : "No" );
591 printf(" Invalid Command: %s\n", status & (1 << 30) ? "Yes" : "No" );
592 printf(" WDT Busy: %s\n", status & (1 << 31) ? "Yes" : "No" );
593 printf(" Dry Run DONE: %s\n", status & (1UL << 33) ? "Yes" : "No" );
594
595 uint8_t bse_error1 = (status & (0b1111UL << 34)) >> 34;
596 switch (bse_error1){
597 case 0b0000: printf(" BSE Error 1 Code: (Previous Bitstream) No Error (0b000)\n"); break;
598 case 0b0001: printf(" BSE Error 1 Code: (Previous Bitstream) ID Error (0b001)\n"); break;
599 case 0b0010: printf(" BSE Error 1 Code: (Previous Bitstream) CMD Error - illegal command (0b010)\n"); break;
600 case 0b0011: printf(" BSE Error 1 Code: (Previous Bitstream) CRC Error (0b011)\n"); break;
601 case 0b0100: printf(" BSE Error 1 Code: (Previous Bitstream) PRMB Error - preamble error (0b100)\n"); break;
602 case 0b0101: printf(" BSE Error 1 Code: (Previous Bitstream) ABRT Error - configuration aborted by the user (0b101)\n"); break;
603 case 0b0110: printf(" BSE Error 1 Code: (Previous Bitstream) OVFL Error - data overflow error (0b110)\n"); break;
604 case 0b0111: printf(" BSE Error 1 Code: (Previous Bitstream) SDM Error - bitstream pass the size of SRAM array (0b111)\n"); break;
605 case 0b1000: printf(" BSE Error 1 Code: (Previous Bitstream) Authentication Error (0b1000)\n"); break;
606 case 0b1001: printf(" BSE Error 1 Code: (Previous Bitstream) Authentication Setup Error (0b1001)\n"); break;
607 case 0b1010: printf(" BSE Error 1 Code: (Previous Bitstream) Bitstream Engine Timeout Error (0b1010) \n"); break;
608 }
609
610 printf(" Bypass Mode: %s\n", status & (1UL << 38) ? "Yes" : "No" );
611 printf(" Flow Through Mode: %s\n", status & (1UL << 39) ? "Yes" : "No" );
612 printf(" SFDP Timeout: %s\n", status & (1UL << 42) ? "Yes" : "No" );
613 printf(" Key Destroy Pass: %s\n", status & (1UL << 43) ? "Yes" : "No" );
614 printf(" INITN: %s\n", status & (1UL << 44) ? "Yes" : "No" );
615 printf(" I3C Parity Error 2: %s\n", status & (1UL << 45) ? "Yes" : "No" );
616 printf(" Init Bus ID Error: %s\n", status & (1UL << 46) ? "Yes" : "No" );
617 printf(" I3C Parity Error 1: %s\n", status & (1UL << 47) ? "Yes" : "No" );
618
619 uint8_t auth_mode = (status & (0b11UL << 48)) >> 48;
620 switch (auth_mode){
621 case 0b00: printf(" Authentication Mode: No Auth (0b00)\n"); break;
622 case 0b01: printf(" Authentication Mode: ECDSA (0b01)\n"); break;
623 case 0b10: printf(" Authentication Mode: HMAC (0b10)\n"); break;
624 case 0b11: printf(" Authentication Mode: No Auth (0b11)\n"); break;
625 }
626
627 printf(" Authentication Done: %s\n", status & (1UL << 50) ? "Yes" : "No" );
628 printf(" Dry Run Authentication Done: %s\n", status & (1UL << 51) ? "Yes" : "No" );
629 printf(" JTAG Locked: %s\n", status & (1UL << 52) ? "Yes" : "No" );
630 printf(" SSPI Locked: %s\n", status & (1UL << 53) ? "Yes" : "No" );
631 printf(" I2C/I3C Locked: %s\n", status & (1UL << 54) ? "Yes" : "No" );
632 printf(" PUB Read Lock: %s\n", status & (1UL << 55) ? "Yes" : "No" );
633 printf(" PUB Write Lock: %s\n", status & (1UL << 56) ? "Yes" : "No" );
634 printf(" FEA Read Lock: %s\n", status & (1UL << 57) ? "Yes" : "No" );
635 printf(" FEA Write Lock: %s\n", status & (1UL << 58) ? "Yes" : "No" );
636 printf(" AES Read Lock: %s\n", status & (1UL << 59) ? "Yes" : "No" );
637 printf(" AES Write Lock: %s\n", status & (1UL << 60) ? "Yes" : "No" );
638 printf(" PWD Read Lock: %s\n", status & (1UL << 61) ? "Yes" : "No" );
639 printf(" PWD Write Lock: %s\n", status & (1UL << 62) ? "Yes" : "No" );
640 printf(" Global Lock: %s\n", status & (1UL << 63) ? "Yes" : "No" );
641 }
642
643 }
644
645 static void read_status_register(){
646
647 uint8_t data[8] = {LSC_READ_STATUS};
648
649 jtag_go_to_state(STATE_SHIFT_IR);
650 jtag_tap_shift(data, data, 8, true);
651
652 data[0] = 0;
653 jtag_go_to_state(STATE_SHIFT_DR);
654 //jtag_go_to_state(STATE_PAUSE_DR);
655
656 if(connected_device.type == TYPE_ECP5){
657 jtag_tap_shift(data, data, 32, true);
658 uint32_t status = 0;
659
660 /* Format the status into a 32bit value */
661 for(int i = 0; i< 4; i++)
662 status = data[i] << 24 | status >> 8;
663
664 print_ecp5_status_register(status);
665 }else if(connected_device.type == TYPE_NX){
666
667 jtag_tap_shift(data, data, 64, true);
668
669 uint64_t status = 0;
670
671 /* Format the status into a 32bit value */
672 for(int i = 0; i< 8; i++)
673 status = (uint64_t)data[i] << 56 | status >> 8;
674
675 print_nx_status_register(status);
676 }
677 }
678
679
680
681 static void enter_spi_background_mode(){
682
683 uint8_t data[4] = {0x3A};
684
685 jtag_go_to_state(STATE_SHIFT_IR);
686 jtag_tap_shift(data, data, 8, true);
687
688 /* These bytes seem to be required to un-lock the SPI interface */
689 data[0] = 0xFE;
690 data[1] = 0x68;
691 jtag_go_to_state(STATE_SHIFT_DR);
692 jtag_tap_shift(data, data, 16, true);
693
694 /* Entering IDLE is essential */
695 jtag_go_to_state(STATE_RUN_TEST_IDLE);
696 }
697
698
699 void ecp_jtag_cmd(uint8_t cmd){
700 uint8_t data[1] = {cmd};
701
702 jtag_go_to_state(STATE_SHIFT_IR);
703 jtag_tap_shift(data, data, 8, true);
704
705 jtag_go_to_state(STATE_RUN_TEST_IDLE);
706 jtag_wait_time(32);
707 }
708
709 void ecp_jtag_cmd8(uint8_t cmd, uint8_t param){
710 uint8_t data[1] = {cmd};
711
712 jtag_go_to_state(STATE_SHIFT_IR);
713 jtag_tap_shift(data, data, 8, true);
714
715 data[0] = param;
716 jtag_go_to_state(STATE_SHIFT_DR);
717 jtag_tap_shift(data, data, 8, true);
718
719 jtag_go_to_state(STATE_RUN_TEST_IDLE);
720 jtag_wait_time(32);
721 }
722
723 // ---------------------------------------------------------
724 // iceprog implementation
725 // ---------------------------------------------------------
726
727 static void help(const char *progname)
728 {
729 fprintf(stderr, "Simple programming tool for Lattice ECP5/NX using FTDI-based JTAG programmers.\n");
730 fprintf(stderr, "Usage: %s [-b|-n|-c] <input file>\n", progname);
731 fprintf(stderr, " %s -r|-R<bytes> <output file>\n", progname);
732 fprintf(stderr, " %s -S <input file>\n", progname);
733 fprintf(stderr, " %s -t\n", progname);
734 fprintf(stderr, "\n");
735 fprintf(stderr, "General options:\n");
736 fprintf(stderr, " -d <device string> use the specified USB device [default: i:0x0403:0x6010 or i:0x0403:0x6014]\n");
737 fprintf(stderr, " d:<devicenode> (e.g. d:002/005)\n");
738 fprintf(stderr, " i:<vendor>:<product> (e.g. i:0x0403:0x6010)\n");
739 fprintf(stderr, " i:<vendor>:<product>:<index> (e.g. i:0x0403:0x6010:0)\n");
740 fprintf(stderr, " s:<vendor>:<product>:<serial-string>\n");
741 fprintf(stderr, " -I [ABCD] connect to the specified interface on the FTDI chip\n");
742 fprintf(stderr, " [default: A]\n");
743 fprintf(stderr, " -o <offset in bytes> start address for read/write [default: 0]\n");
744 fprintf(stderr, " (append 'k' to the argument for size in kilobytes,\n");
745 fprintf(stderr, " or 'M' for size in megabytes)\n");
746 fprintf(stderr, " -k <divider> divider for SPI clock [default: 1]\n");
747 fprintf(stderr, " clock speed is 6MHz/divider");
748 fprintf(stderr, " -s slow SPI. (50 kHz instead of 6 MHz)\n");
749 fprintf(stderr, " Equivalent to -k 30\n");
750 fprintf(stderr, " -v verbose output\n");
751 fprintf(stderr, " -i [4,32,64] select erase block size [default: 64k]\n");
752 fprintf(stderr, " -a reinitialize the device after any operation\n");
753 fprintf(stderr, "\n");
754 fprintf(stderr, "Mode of operation:\n");
755 fprintf(stderr, " [default] write file contents to flash, then verify\n");
756 fprintf(stderr, " -X write file contents to flash only\n");
757 fprintf(stderr, " -r read first 256 kB from flash and write to file\n");
758 fprintf(stderr, " -R <size in bytes> read the specified number of bytes from flash\n");
759 fprintf(stderr, " (append 'k' to the argument for size in kilobytes,\n");
760 fprintf(stderr, " or 'M' for size in megabytes)\n");
761 fprintf(stderr, " -c do not write flash, only verify (`check')\n");
762 fprintf(stderr, " -S perform SRAM programming\n");
763 fprintf(stderr, " -t just read the flash ID sequence\n");
764 fprintf(stderr, "\n");
765 fprintf(stderr, "Erase mode (only meaningful in default mode):\n");
766 fprintf(stderr, " [default] erase aligned chunks of 64kB in write mode\n");
767 fprintf(stderr, " This means that some data after the written data (or\n");
768 fprintf(stderr, " even before when -o is used) may be erased as well.\n");
769 fprintf(stderr, " -b bulk erase entire flash before writing\n");
770 fprintf(stderr, " -e <size in bytes> erase flash as if we were writing that number of bytes\n");
771 fprintf(stderr, " -n do not erase flash before writing\n");
772 fprintf(stderr, " -p disable write protection before erasing or writing\n");
773 fprintf(stderr, " This can be useful if flash memory appears to be\n");
774 fprintf(stderr, " bricked and won't respond to erasing or programming.\n");
775 fprintf(stderr, "\n");
776 fprintf(stderr, "Miscellaneous options:\n");
777 fprintf(stderr, " --help display this help and exit\n");
778 fprintf(stderr, " -- treat all remaining arguments as filenames\n");
779 fprintf(stderr, "\n");
780 fprintf(stderr, "Exit status:\n");
781 fprintf(stderr, " 0 on success,\n");
782 fprintf(stderr, " 1 if a non-hardware error occurred (e.g., failure to read from or\n");
783 fprintf(stderr, " write to a file, or invoked with invalid options),\n");
784 fprintf(stderr, " 2 if communication with the hardware failed (e.g., cannot find the\n");
785 fprintf(stderr, " iCE FTDI USB device),\n");
786 fprintf(stderr, " 3 if verification of the data failed.\n");
787 fprintf(stderr, "\n");
788 fprintf(stderr, "If you have a bug report, please file an issue on github:\n");
789 fprintf(stderr, " https://github.com/gregdavill/ecpprog/issues\n");
790 }
791
792 int main(int argc, char **argv)
793 {
794 /* used for error reporting */
795 const char *my_name = argv[0];
796 for (size_t i = 0; argv[0][i]; i++)
797 if (argv[0][i] == '/')
798 my_name = argv[0] + i + 1;
799
800 int read_size = 256 * 1024;
801 int erase_block_size = 64;
802 int erase_size = 0;
803 int rw_offset = 0;
804 int clkdiv = 1;
805
806 bool reinitialize = false;
807 bool read_mode = false;
808 bool check_mode = false;
809 bool erase_mode = false;
810 bool bulk_erase = false;
811 bool dont_erase = false;
812 bool prog_sram = false;
813 bool test_mode = false;
814 bool disable_protect = false;
815 bool disable_verify = false;
816 const char *filename = NULL;
817 const char *devstr = NULL;
818 int ifnum = 0;
819
820 #ifdef _WIN32
821 _setmode(_fileno(stdin), _O_BINARY);
822 _setmode(_fileno(stdout), _O_BINARY);
823 #endif
824
825 static struct option long_options[] = {
826 {"help", no_argument, NULL, -2},
827 {NULL, 0, NULL, 0}
828 };
829
830 /* Decode command line parameters */
831 int opt;
832 char *endptr;
833 while ((opt = getopt_long(argc, argv, "d:i:I:rR:e:o:k:scbnStvpX", long_options, NULL)) != -1) {
834 switch (opt) {
835 case 'd': /* device string */
836 devstr = optarg;
837 break;
838 case 'i': /* block erase size */
839 if (!strcmp(optarg, "4"))
840 erase_block_size = 4;
841 else if (!strcmp(optarg, "32"))
842 erase_block_size = 32;
843 else if (!strcmp(optarg, "64"))
844 erase_block_size = 64;
845 else {
846 fprintf(stderr, "%s: `%s' is not a valid erase block size (must be `4', `32' or `64')\n", my_name, optarg);
847 return EXIT_FAILURE;
848 }
849 break;
850 case 'I': /* FTDI Chip interface select */
851 if (!strcmp(optarg, "A"))
852 ifnum = 0;
853 else if (!strcmp(optarg, "B"))
854 ifnum = 1;
855 else if (!strcmp(optarg, "C"))
856 ifnum = 2;
857 else if (!strcmp(optarg, "D"))
858 ifnum = 3;
859 else {
860 fprintf(stderr, "%s: `%s' is not a valid interface (must be `A', `B', `C', or `D')\n", my_name, optarg);
861 return EXIT_FAILURE;
862 }
863 break;
864 case 'r': /* Read 256 bytes to file */
865 read_mode = true;
866 break;
867 case 'R': /* Read n bytes to file */
868 read_mode = true;
869 read_size = strtol(optarg, &endptr, 0);
870 if (*endptr == '\0')
871 /* ok */;
872 else if (!strcmp(endptr, "k"))
873 read_size *= 1024;
874 else if (!strcmp(endptr, "M"))
875 read_size *= 1024 * 1024;
876 else {
877 fprintf(stderr, "%s: `%s' is not a valid size\n", my_name, optarg);
878 return EXIT_FAILURE;
879 }
880 break;
881 case 'e': /* Erase blocks as if we were writing n bytes */
882 erase_mode = true;
883 erase_size = strtol(optarg, &endptr, 0);
884 if (*endptr == '\0')
885 /* ok */;
886 else if (!strcmp(endptr, "k"))
887 erase_size *= 1024;
888 else if (!strcmp(endptr, "M"))
889 erase_size *= 1024 * 1024;
890 else {
891 fprintf(stderr, "%s: `%s' is not a valid size\n", my_name, optarg);
892 return EXIT_FAILURE;
893 }
894 break;
895 case 'o': /* set address offset */
896 rw_offset = strtol(optarg, &endptr, 0);
897 if (*endptr == '\0')
898 /* ok */;
899 else if (!strcmp(endptr, "k"))
900 rw_offset *= 1024;
901 else if (!strcmp(endptr, "M"))
902 rw_offset *= 1024 * 1024;
903 else {
904 fprintf(stderr, "%s: `%s' is not a valid offset\n", my_name, optarg);
905 return EXIT_FAILURE;
906 }
907 break;
908 case 'k': /* set clock div */
909 clkdiv = strtol(optarg, &endptr, 0);
910 if (clkdiv < 1 || clkdiv > 65536) {
911 fprintf(stderr, "%s: clock divider must be in range 1-65536 `%s' is not a valid divider\n", my_name, optarg);
912 return EXIT_FAILURE;
913 }
914 break;
915 case 's': /* use slow SPI clock */
916 clkdiv = 30;
917 break;
918 case 'c': /* do not write just check */
919 check_mode = true;
920 break;
921 case 'a': /* reinitialize ECP5 device reading new configuration */
922 reinitialize = true;
923 break;
924 case 'b': /* bulk erase before writing */
925 bulk_erase = true;
926 break;
927 case 'n': /* do not erase before writing */
928 dont_erase = true;
929 break;
930 case 'S': /* write to sram directly */
931 prog_sram = true;
932 break;
933 case 't': /* just read flash id */
934 test_mode = true;
935 break;
936 case 'v': /* provide verbose output */
937 verbose = true;
938 break;
939 case 'p': /* disable flash protect before erase/write */
940 disable_protect = true;
941 break;
942 case 'X': /* disable verification */
943 disable_verify = true;
944 break;
945 case -2:
946 help(argv[0]);
947 return EXIT_SUCCESS;
948 default:
949 /* error message has already been printed */
950 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
951 return EXIT_FAILURE;
952 }
953 }
954
955 /* Make sure that the combination of provided parameters makes sense */
956
957 if (read_mode + erase_mode + check_mode + prog_sram + test_mode > 1) {
958 fprintf(stderr, "%s: options `-r'/`-R', `-e`, `-c', `-S', and `-t' are mutually exclusive\n", my_name);
959 return EXIT_FAILURE;
960 }
961
962 if (bulk_erase && dont_erase) {
963 fprintf(stderr, "%s: options `-b' and `-n' are mutually exclusive\n", my_name);
964 return EXIT_FAILURE;
965 }
966
967 if (disable_protect && (read_mode || check_mode || prog_sram || test_mode)) {
968 fprintf(stderr, "%s: option `-p' only valid in programming mode\n", my_name);
969 return EXIT_FAILURE;
970 }
971
972 if (bulk_erase && (read_mode || check_mode || prog_sram || test_mode)) {
973 fprintf(stderr, "%s: option `-b' only valid in programming mode\n", my_name);
974 return EXIT_FAILURE;
975 }
976
977 if (dont_erase && (read_mode || check_mode || prog_sram || test_mode)) {
978 fprintf(stderr, "%s: option `-n' only valid in programming mode\n", my_name);
979 return EXIT_FAILURE;
980 }
981
982 if (rw_offset != 0 && prog_sram) {
983 fprintf(stderr, "%s: option `-o' not supported in SRAM mode\n", my_name);
984 return EXIT_FAILURE;
985 }
986
987 if (rw_offset != 0 && test_mode) {
988 fprintf(stderr, "%s: option `-o' not supported in test mode\n", my_name);
989 return EXIT_FAILURE;
990 }
991
992 if (optind + 1 == argc) {
993 if (test_mode) {
994 fprintf(stderr, "%s: test mode doesn't take a file name\n", my_name);
995 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
996 return EXIT_FAILURE;
997 }
998 filename = argv[optind];
999 } else if (optind != argc) {
1000 fprintf(stderr, "%s: too many arguments\n", my_name);
1001 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
1002 return EXIT_FAILURE;
1003 } else if (bulk_erase || disable_protect) {
1004 filename = "/dev/null";
1005 } else if (!test_mode && !erase_mode && !disable_protect) {
1006 fprintf(stderr, "%s: missing argument\n", my_name);
1007 fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]);
1008 return EXIT_FAILURE;
1009 }
1010
1011 /* open input/output file in advance
1012 so we can fail before initializing the hardware */
1013
1014 FILE *f = NULL;
1015 long file_size = -1;
1016
1017 if (test_mode) {
1018 /* nop */;
1019 } else if (erase_mode) {
1020 file_size = erase_size;
1021 } else if (read_mode) {
1022 f = (strcmp(filename, "-") == 0) ? stdout : fopen(filename, "wb");
1023 if (f == NULL) {
1024 fprintf(stderr, "%s: can't open '%s' for writing: ", my_name, filename);
1025 perror(0);
1026 return EXIT_FAILURE;
1027 }
1028 file_size = read_size;
1029 } else {
1030 f = (strcmp(filename, "-") == 0) ? stdin : fopen(filename, "rb");
1031 if (f == NULL) {
1032 fprintf(stderr, "%s: can't open '%s' for reading: ", my_name, filename);
1033 perror(0);
1034 return EXIT_FAILURE;
1035 }
1036
1037 /* For regular programming, we need to read the file
1038 twice--once for programming and once for verifying--and
1039 need to know the file size in advance in order to erase
1040 the correct amount of memory.
1041
1042 See if we can seek on the input file. Checking for "-"
1043 as an argument isn't enough as we might be reading from a
1044 named pipe, or contrarily, the standard input may be an
1045 ordinary file. */
1046
1047 if (!prog_sram) {
1048 if (fseek(f, 0L, SEEK_END) != -1) {
1049 file_size = ftell(f);
1050 if (file_size == -1) {
1051 fprintf(stderr, "%s: %s: ftell: ", my_name, filename);
1052 perror(0);
1053 return EXIT_FAILURE;
1054 }
1055 if (fseek(f, 0L, SEEK_SET) == -1) {
1056 fprintf(stderr, "%s: %s: fseek: ", my_name, filename);
1057 perror(0);
1058 return EXIT_FAILURE;
1059 }
1060 } else {
1061 FILE *pipe = f;
1062
1063 f = tmpfile();
1064 if (f == NULL) {
1065 fprintf(stderr, "%s: can't open temporary file\n", my_name);
1066 return EXIT_FAILURE;
1067 }
1068 file_size = 0;
1069
1070 while (true) {
1071 static unsigned char buffer[4096];
1072 size_t rc = fread(buffer, 1, 4096, pipe);
1073 if (rc <= 0)
1074 break;
1075 size_t wc = fwrite(buffer, 1, rc, f);
1076 if (wc != rc) {
1077 fprintf(stderr, "%s: can't write to temporary file\n", my_name);
1078 return EXIT_FAILURE;
1079 }
1080 file_size += rc;
1081 }
1082 fclose(pipe);
1083
1084 /* now seek to the beginning so we can
1085 start reading again */
1086 fseek(f, 0, SEEK_SET);
1087 }
1088 }
1089 }
1090
1091 // ---------------------------------------------------------
1092 // Initialize USB connection to FT2232H
1093 // ---------------------------------------------------------
1094
1095 fprintf(stderr, "init..\n");
1096 jtag_init(ifnum, devstr, clkdiv);
1097
1098 read_idcode();
1099 read_status_register();
1100
1101 if (test_mode)
1102 {
1103 /* Reset ECP5 to release SPI interface */
1104 ecp_jtag_cmd8(ISC_ENABLE,0);
1105 usleep(10000);
1106 ecp_jtag_cmd8(ISC_ERASE,0);
1107 usleep(10000);
1108 ecp_jtag_cmd(ISC_DISABLE);
1109
1110 /* Put device into SPI bypass mode */
1111 enter_spi_background_mode();
1112
1113 flash_reset();
1114 flash_read_id();
1115
1116 flash_read_status();
1117 }
1118 else if (prog_sram)
1119 {
1120 // ---------------------------------------------------------
1121 // Reset
1122 // ---------------------------------------------------------
1123 fprintf(stderr, "reset..\n");
1124
1125 ecp_jtag_cmd8(ISC_ENABLE, 0);
1126 ecp_jtag_cmd8(ISC_ERASE, 0);
1127 ecp_jtag_cmd8(LSC_RESET_CRC, 0);
1128
1129 read_status_register();
1130
1131 // ---------------------------------------------------------
1132 // Program
1133 // ---------------------------------------------------------
1134
1135 fprintf(stderr, "programming..\n");
1136 ecp_jtag_cmd(LSC_BITSTREAM_BURST);
1137 while (1) {
1138 const uint32_t len = 16*1024;
1139 static unsigned char buffer[16*1024];
1140 int rc = fread(buffer, 1, len, f);
1141 if (rc <= 0)
1142 break;
1143 if (verbose)
1144 fprintf(stderr, "sending %d bytes.\n", rc);
1145
1146 for(int i = 0; i < rc; i++){
1147 buffer[i] = bit_reverse(buffer[i]);
1148 }
1149
1150 jtag_go_to_state(STATE_CAPTURE_DR);
1151 jtag_tap_shift(buffer, buffer, rc*8, false);
1152 }
1153
1154 ecp_jtag_cmd(ISC_DISABLE);
1155 read_status_register();
1156 }
1157 else /* program flash */
1158 {
1159 // ---------------------------------------------------------
1160 // Reset
1161 // ---------------------------------------------------------
1162
1163 fprintf(stderr, "reset..\n");
1164 /* Reset ECP5 to release SPI interface */
1165 ecp_jtag_cmd8(ISC_ENABLE, 0);
1166 ecp_jtag_cmd8(ISC_ERASE, 0);
1167 ecp_jtag_cmd8(ISC_DISABLE, 0);
1168
1169 /* Put device into SPI bypass mode */
1170 enter_spi_background_mode();
1171
1172 flash_reset();
1173
1174 flash_read_id();
1175
1176
1177 // ---------------------------------------------------------
1178 // Program
1179 // ---------------------------------------------------------
1180
1181 if (!read_mode && !check_mode)
1182 {
1183 if (disable_protect)
1184 {
1185 flash_write_enable();
1186 flash_disable_protection();
1187 }
1188
1189 if (!dont_erase)
1190 {
1191 if (bulk_erase)
1192 {
1193 flash_write_enable();
1194 flash_bulk_erase();
1195 flash_wait();
1196 }
1197 else
1198 {
1199 fprintf(stderr, "file size: %ld\n", file_size);
1200
1201 int block_size = erase_block_size << 10;
1202 int block_mask = block_size - 1;
1203 int begin_addr = rw_offset & ~block_mask;
1204 int end_addr = (rw_offset + file_size + block_mask) & ~block_mask;
1205
1206 for (int addr = begin_addr; addr < end_addr; addr += block_size) {
1207 flash_write_enable();
1208 switch(erase_block_size) {
1209 case 4:
1210 flash_4kB_sector_erase(addr);
1211 break;
1212 case 32:
1213 flash_32kB_sector_erase(addr);
1214 break;
1215 case 64:
1216 flash_64kB_sector_erase(addr);
1217 break;
1218 }
1219 if (verbose) {
1220 fprintf(stderr, "Status after block erase:\n");
1221 flash_read_status();
1222 }
1223 flash_wait();
1224 }
1225 }
1226 }
1227
1228 if (!erase_mode)
1229 {
1230 for (int rc, addr = 0; true; addr += rc) {
1231 uint8_t buffer[256];
1232
1233 /* Show progress */
1234 fprintf(stderr, "\r\033[0Kprogramming.. %04u/%04lu", addr, file_size);
1235
1236 int page_size = 256 - (rw_offset + addr) % 256;
1237 rc = fread(buffer, 1, page_size, f);
1238 if (rc <= 0)
1239 break;
1240 flash_write_enable();
1241 flash_prog(rw_offset + addr, buffer, rc);
1242 flash_wait();
1243
1244 }
1245
1246 fprintf(stderr, "\n");
1247 /* seek to the beginning for second pass */
1248 fseek(f, 0, SEEK_SET);
1249 }
1250 }
1251
1252 // ---------------------------------------------------------
1253 // Read/Verify
1254 // ---------------------------------------------------------
1255
1256 if (read_mode) {
1257
1258 flash_start_read(rw_offset);
1259 for (int addr = 0; addr < read_size; addr += 4096) {
1260 uint8_t buffer[4096];
1261
1262 /* Show progress */
1263 fprintf(stderr, "\r\033[0Kreading.. %04u/%04u", addr + 4096, read_size);
1264
1265 flash_continue_read(buffer, 4096);
1266 fwrite(buffer, read_size - addr > 4096 ? 4096 : read_size - addr, 1, f);
1267 }
1268 fprintf(stderr, "\n");
1269 } else if (!erase_mode && !disable_verify) {
1270
1271 flash_start_read(rw_offset);
1272 for (int addr = 0; addr < file_size; addr += 4096) {
1273 uint8_t buffer_flash[4096], buffer_file[4096];
1274
1275 int rc = fread(buffer_file, 1, 4096, f);
1276 if (rc <= 0)
1277 break;
1278
1279 flash_continue_read(buffer_flash, rc);
1280
1281 /* Show progress */
1282 fprintf(stderr, "\r\033[0Kverify.. %04u/%04lu", addr + rc, file_size);
1283 if (memcmp(buffer_file, buffer_flash, rc)) {
1284 fprintf(stderr, "Found difference between flash and file!\n");
1285 jtag_error(3);
1286 }
1287
1288 }
1289 fprintf(stderr, " VERIFY OK\n");
1290 }
1291 }
1292
1293 if (reinitialize) {
1294 fprintf(stderr, "rebooting ECP5...\n");
1295 ecp_jtag_cmd(LSC_REFRESH);
1296 }
1297
1298 if (f != NULL && f != stdin && f != stdout)
1299 fclose(f);
1300
1301 // ---------------------------------------------------------
1302 // Exit
1303 // ---------------------------------------------------------
1304
1305 fprintf(stderr, "Bye.\n");
1306 jtag_deinit();
1307 return 0;
1308 }