flash/nor/tcl.c: add filld command to write double-word with 64-bit value
[fw/openocd] / src / flash / nor / tcl.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath <Dominic.Rath@gmx.de>              *
3  *   Copyright (C) 2007,2008 Ã˜yvind Harboe <oyvind.harboe@zylin.com>       *
4  *   Copyright (C) 2008 by Spencer Oliver <spen@spen-soft.co.uk>           *
5  *   Copyright (C) 2009 Zachary T Welch <zw@superlucidity.net>             *
6  *   Copyright (C) 2017-2018 Tomas Vanek <vanekt@fbl.cz>                   *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
20  ***************************************************************************/
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24 #include "imp.h"
25 #include <helper/time_support.h>
26 #include <target/image.h>
27
28 /**
29  * @file
30  * Implements Tcl commands used to access NOR flash facilities.
31  */
32
33 COMMAND_HELPER(flash_command_get_bank_maybe_probe, unsigned name_index,
34                struct flash_bank **bank, bool do_probe)
35 {
36         const char *name = CMD_ARGV[name_index];
37         int retval;
38         if (do_probe) {
39                 retval = get_flash_bank_by_name(name, bank);
40         } else {
41                 *bank  = get_flash_bank_by_name_noprobe(name);
42                 retval = ERROR_OK;
43         }
44
45         if (retval != ERROR_OK)
46                 return retval;
47         if (*bank)
48                 return ERROR_OK;
49
50         unsigned bank_num;
51         COMMAND_PARSE_NUMBER(uint, name, bank_num);
52
53         if (do_probe) {
54                 return get_flash_bank_by_num(bank_num, bank);
55         } else {
56                 *bank  = get_flash_bank_by_num_noprobe(bank_num);
57                 retval = (bank) ? ERROR_OK : ERROR_FAIL;
58                 return retval;
59         }
60 }
61
62 COMMAND_HELPER(flash_command_get_bank, unsigned name_index,
63         struct flash_bank **bank)
64 {
65         return CALL_COMMAND_HANDLER(flash_command_get_bank_maybe_probe,
66                                     name_index, bank, true);
67 }
68
69 COMMAND_HANDLER(handle_flash_info_command)
70 {
71         struct flash_bank *p;
72         int j = 0;
73         int retval;
74         bool show_sectors = false;
75         bool prot_block_available;
76
77         if (CMD_ARGC < 1 || CMD_ARGC > 2)
78                 return ERROR_COMMAND_SYNTAX_ERROR;
79
80         if (CMD_ARGC == 2) {
81                 if (strcmp("sectors", CMD_ARGV[1]) == 0)
82                         show_sectors = true;
83                 else
84                         return ERROR_COMMAND_SYNTAX_ERROR;
85         }
86
87         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
88         if (retval != ERROR_OK)
89                 return retval;
90
91         if (p != NULL) {
92                 char buf[1024];
93                 int num_blocks;
94                 struct flash_sector *block_array;
95
96                 /* attempt auto probe */
97                 retval = p->driver->auto_probe(p);
98                 if (retval != ERROR_OK)
99                         return retval;
100
101                 /* If the driver does not implement protection, we show the default
102                  * state of is_protected array - usually protection state unknown */
103                 if (p->driver->protect_check == NULL) {
104                         retval = ERROR_FLASH_OPER_UNSUPPORTED;
105                 } else {
106                         /* We must query the hardware to avoid printing stale information! */
107                         retval = p->driver->protect_check(p);
108                         if (retval != ERROR_OK && retval != ERROR_FLASH_OPER_UNSUPPORTED)
109                                 return retval;
110                 }
111                 if (retval == ERROR_FLASH_OPER_UNSUPPORTED)
112                         LOG_WARNING("Flash protection check is not implemented.");
113
114                 command_print(CMD,
115                         "#%d : %s at " TARGET_ADDR_FMT ", size 0x%8.8" PRIx32
116                         ", buswidth %i, chipwidth %i",
117                         p->bank_number,
118                         p->driver->name,
119                         p->base,
120                         p->size,
121                         p->bus_width,
122                         p->chip_width);
123
124                 prot_block_available = p->num_prot_blocks && p->prot_blocks;
125                 if (!show_sectors && prot_block_available) {
126                         block_array = p->prot_blocks;
127                         num_blocks = p->num_prot_blocks;
128                 } else {
129                         block_array = p->sectors;
130                         num_blocks = p->num_sectors;
131                 }
132
133                 for (j = 0; j < num_blocks; j++) {
134                         char *protect_state = "";
135
136                         if (block_array[j].is_protected == 0)
137                                 protect_state = "not protected";
138                         else if (block_array[j].is_protected == 1)
139                                 protect_state = "protected";
140                         else if (!show_sectors || !prot_block_available)
141                                 protect_state = "protection state unknown";
142
143                         command_print(CMD,
144                                 "\t#%3i: 0x%8.8" PRIx32 " (0x%" PRIx32 " %" PRIi32 "kB) %s",
145                                 j,
146                                 block_array[j].offset,
147                                 block_array[j].size,
148                                 block_array[j].size >> 10,
149                                 protect_state);
150                 }
151
152                 if (p->driver->info != NULL) {
153                         retval = p->driver->info(p, buf, sizeof(buf));
154                         if (retval == ERROR_OK)
155                                 command_print(CMD, "%s", buf);
156                         else
157                                 LOG_ERROR("error retrieving flash info");
158                 }
159         }
160
161         return retval;
162 }
163
164 COMMAND_HANDLER(handle_flash_probe_command)
165 {
166         struct flash_bank *p;
167         int retval;
168
169         if (CMD_ARGC != 1)
170                 return ERROR_COMMAND_SYNTAX_ERROR;
171
172         retval = CALL_COMMAND_HANDLER(flash_command_get_bank_maybe_probe, 0, &p, false);
173         if (retval != ERROR_OK)
174                 return retval;
175
176         if (p) {
177                 retval = p->driver->probe(p);
178                 if (retval == ERROR_OK)
179                         command_print(CMD,
180                                 "flash '%s' found at " TARGET_ADDR_FMT,
181                                 p->driver->name,
182                                 p->base);
183         } else {
184                 command_print(CMD, "flash bank '#%s' is out of bounds", CMD_ARGV[0]);
185                 retval = ERROR_FAIL;
186         }
187
188         return retval;
189 }
190
191 COMMAND_HANDLER(handle_flash_erase_check_command)
192 {
193         bool blank = true;
194         if (CMD_ARGC != 1)
195                 return ERROR_COMMAND_SYNTAX_ERROR;
196
197         struct flash_bank *p;
198         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
199         if (ERROR_OK != retval)
200                 return retval;
201
202         int j;
203         retval = p->driver->erase_check(p);
204         if (retval == ERROR_OK)
205                 command_print(CMD, "successfully checked erase state");
206         else {
207                 command_print(CMD,
208                         "unknown error when checking erase state of flash bank #%s at "
209                         TARGET_ADDR_FMT,
210                         CMD_ARGV[0],
211                         p->base);
212         }
213
214         for (j = 0; j < p->num_sectors; j++) {
215                 char *erase_state;
216
217                 if (p->sectors[j].is_erased == 0)
218                         erase_state = "not erased";
219                 else if (p->sectors[j].is_erased == 1)
220                         continue;
221                 else
222                         erase_state = "erase state unknown";
223
224                 blank = false;
225                 command_print(CMD,
226                         "\t#%3i: 0x%8.8" PRIx32 " (0x%" PRIx32 " %" PRIi32 "kB) %s",
227                         j,
228                         p->sectors[j].offset,
229                         p->sectors[j].size,
230                         p->sectors[j].size >> 10,
231                         erase_state);
232         }
233
234         if (blank)
235                 command_print(CMD, "\tBank is erased");
236         return retval;
237 }
238
239 COMMAND_HANDLER(handle_flash_erase_address_command)
240 {
241         struct flash_bank *p;
242         int retval = ERROR_OK;
243         target_addr_t address;
244         uint32_t length;
245         bool do_pad = false;
246         bool do_unlock = false;
247         struct target *target = get_current_target(CMD_CTX);
248
249         while (CMD_ARGC >= 3) {
250                 /* Optionally pad out the address range to block/sector
251                  * boundaries.  We can't know if there's data in that part
252                  * of the flash; only do padding if we're told to.
253                  */
254                 if (strcmp("pad", CMD_ARGV[0]) == 0)
255                         do_pad = true;
256                 else if (strcmp("unlock", CMD_ARGV[0]) == 0)
257                         do_unlock = true;
258                 else
259                         return ERROR_COMMAND_SYNTAX_ERROR;
260                 CMD_ARGC--;
261                 CMD_ARGV++;
262         }
263         if (CMD_ARGC != 2)
264                 return ERROR_COMMAND_SYNTAX_ERROR;
265
266         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
267         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], length);
268
269         if (length <= 0) {
270                 command_print(CMD, "Length must be >0");
271                 return ERROR_COMMAND_SYNTAX_ERROR;
272         }
273
274         retval = get_flash_bank_by_addr(target, address, true, &p);
275         if (retval != ERROR_OK)
276                 return retval;
277
278         /* We can't know if we did a resume + halt, in which case we no longer know the erased state
279          **/
280         flash_set_dirty();
281
282         struct duration bench;
283         duration_start(&bench);
284
285         if (do_unlock)
286                 retval = flash_unlock_address_range(target, address, length);
287
288         if (retval == ERROR_OK)
289                 retval = flash_erase_address_range(target, do_pad, address, length);
290
291         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
292                 command_print(CMD, "erased address " TARGET_ADDR_FMT " (length %"
293                                 PRIi32 ")"
294                         " in %fs (%0.3f KiB/s)", address, length,
295                         duration_elapsed(&bench), duration_kbps(&bench, length));
296         }
297
298         return retval;
299 }
300
301 COMMAND_HANDLER(handle_flash_erase_command)
302 {
303         if (CMD_ARGC != 3)
304                 return ERROR_COMMAND_SYNTAX_ERROR;
305
306         uint32_t first;
307         uint32_t last;
308
309         struct flash_bank *p;
310         int retval;
311
312         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
313         if (retval != ERROR_OK)
314                 return retval;
315
316         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], first);
317         if (strcmp(CMD_ARGV[2], "last") == 0)
318                 last = p->num_sectors - 1;
319         else
320                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], last);
321
322         if (!(first <= last)) {
323                 command_print(CMD, "ERROR: "
324                         "first sector must be <= last");
325                 return ERROR_FAIL;
326         }
327
328         if (!(last <= (uint32_t)(p->num_sectors - 1))) {
329                 command_print(CMD, "ERROR: "
330                         "last sector must be <= %" PRIu32,
331                         p->num_sectors - 1);
332                 return ERROR_FAIL;
333         }
334
335         struct duration bench;
336         duration_start(&bench);
337
338         retval = flash_driver_erase(p, first, last);
339
340         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
341                 command_print(CMD, "erased sectors %" PRIu32 " "
342                         "through %" PRIu32 " on flash bank %d "
343                         "in %fs", first, last, p->bank_number, duration_elapsed(&bench));
344         }
345
346         return retval;
347 }
348
349 COMMAND_HANDLER(handle_flash_protect_command)
350 {
351         if (CMD_ARGC != 4)
352                 return ERROR_COMMAND_SYNTAX_ERROR;
353
354         uint32_t first;
355         uint32_t last;
356
357         struct flash_bank *p;
358         int retval;
359         int num_blocks;
360
361         retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
362         if (retval != ERROR_OK)
363                 return retval;
364
365         if (p->num_prot_blocks)
366                 num_blocks = p->num_prot_blocks;
367         else
368                 num_blocks = p->num_sectors;
369
370         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[1], first);
371         if (strcmp(CMD_ARGV[2], "last") == 0)
372                 last = num_blocks - 1;
373         else
374                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], last);
375
376         bool set;
377         COMMAND_PARSE_ON_OFF(CMD_ARGV[3], set);
378
379         if (!(first <= last)) {
380                 command_print(CMD, "ERROR: "
381                         "first %s must be <= last",
382                         (p->num_prot_blocks) ? "block" : "sector");
383                 return ERROR_FAIL;
384         }
385
386         if (!(last <= (uint32_t)(num_blocks - 1))) {
387                 command_print(CMD, "ERROR: "
388                         "last %s must be <= %" PRIu32,
389                         (p->num_prot_blocks) ? "block" : "sector",
390                         num_blocks - 1);
391                 return ERROR_FAIL;
392         }
393
394         retval = flash_driver_protect(p, set, first, last);
395         if (retval == ERROR_OK) {
396                 command_print(CMD, "%s protection for %s %" PRIu32
397                         " through %" PRIu32 " on flash bank %d",
398                         (set) ? "set" : "cleared",
399                         (p->num_prot_blocks) ? "blocks" : "sectors",
400                         first, last, p->bank_number);
401         }
402
403         return retval;
404 }
405
406 COMMAND_HANDLER(handle_flash_write_image_command)
407 {
408         struct target *target = get_current_target(CMD_CTX);
409
410         struct image image;
411         uint32_t written;
412
413         int retval;
414
415         /* flash auto-erase is disabled by default*/
416         int auto_erase = 0;
417         bool auto_unlock = false;
418
419         while (CMD_ARGC) {
420                 if (strcmp(CMD_ARGV[0], "erase") == 0) {
421                         auto_erase = 1;
422                         CMD_ARGV++;
423                         CMD_ARGC--;
424                         command_print(CMD, "auto erase enabled");
425                 } else if (strcmp(CMD_ARGV[0], "unlock") == 0) {
426                         auto_unlock = true;
427                         CMD_ARGV++;
428                         CMD_ARGC--;
429                         command_print(CMD, "auto unlock enabled");
430                 } else
431                         break;
432         }
433
434         if (CMD_ARGC < 1)
435                 return ERROR_COMMAND_SYNTAX_ERROR;
436
437         if (!target) {
438                 LOG_ERROR("no target selected");
439                 return ERROR_FAIL;
440         }
441
442         struct duration bench;
443         duration_start(&bench);
444
445         if (CMD_ARGC >= 2) {
446                 image.base_address_set = 1;
447                 COMMAND_PARSE_NUMBER(llong, CMD_ARGV[1], image.base_address);
448         } else {
449                 image.base_address_set = 0;
450                 image.base_address = 0x0;
451         }
452
453         image.start_address_set = 0;
454
455         retval = image_open(&image, CMD_ARGV[0], (CMD_ARGC == 3) ? CMD_ARGV[2] : NULL);
456         if (retval != ERROR_OK)
457                 return retval;
458
459         retval = flash_write_unlock(target, &image, &written, auto_erase, auto_unlock);
460         if (retval != ERROR_OK) {
461                 image_close(&image);
462                 return retval;
463         }
464
465         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
466                 command_print(CMD, "wrote %" PRIu32 " bytes from file %s "
467                         "in %fs (%0.3f KiB/s)", written, CMD_ARGV[0],
468                         duration_elapsed(&bench), duration_kbps(&bench, written));
469         }
470
471         image_close(&image);
472
473         return retval;
474 }
475
476 COMMAND_HANDLER(handle_flash_fill_command)
477 {
478         target_addr_t address;
479         uint64_t pattern;
480         uint32_t count;
481         struct target *target = get_current_target(CMD_CTX);
482         unsigned i;
483         uint32_t wordsize;
484         int retval;
485
486         if (CMD_ARGC != 3)
487                 return ERROR_COMMAND_SYNTAX_ERROR;
488
489         COMMAND_PARSE_ADDRESS(CMD_ARGV[0], address);
490         COMMAND_PARSE_NUMBER(u64, CMD_ARGV[1], pattern);
491         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], count);
492
493         struct flash_bank *bank;
494         retval = get_flash_bank_by_addr(target, address, true, &bank);
495         if (retval != ERROR_OK)
496                 return retval;
497
498         switch (CMD_NAME[4]) {
499                 case 'd':
500                         wordsize = 8;
501                         break;
502                 case 'w':
503                         wordsize = 4;
504                         break;
505                 case 'h':
506                         wordsize = 2;
507                         break;
508                 case 'b':
509                         wordsize = 1;
510                         break;
511                 default:
512                         return ERROR_COMMAND_SYNTAX_ERROR;
513         }
514
515         if (count == 0)
516                 return ERROR_OK;
517
518         if (address + count * wordsize > bank->base + bank->size) {
519                 LOG_ERROR("Cannot cross flash bank borders");
520                 return ERROR_FAIL;
521         }
522
523         uint32_t size_bytes = count * wordsize;
524         target_addr_t aligned_start = flash_write_align_start(bank, address);
525         target_addr_t end_addr = address + size_bytes - 1;
526         target_addr_t aligned_end = flash_write_align_end(bank, end_addr);
527         uint32_t aligned_size = aligned_end + 1 - aligned_start;
528         uint32_t padding_at_start = address - aligned_start;
529         uint32_t padding_at_end = aligned_end - end_addr;
530
531         uint8_t *buffer = malloc(aligned_size);
532         if (buffer == NULL)
533                 return ERROR_FAIL;
534
535         if (padding_at_start) {
536                 memset(buffer, bank->default_padded_value, padding_at_start);
537                 LOG_WARNING("Start address " TARGET_ADDR_FMT
538                         " breaks the required alignment of flash bank %s",
539                         address, bank->name);
540                 LOG_WARNING("Padding %" PRId32 " bytes from " TARGET_ADDR_FMT,
541                     padding_at_start, aligned_start);
542         }
543
544         uint8_t *ptr = buffer + padding_at_start;
545
546         switch (wordsize) {
547                 case 8:
548                         for (i = 0; i < count; i++, ptr += wordsize)
549                                 target_buffer_set_u64(target, ptr, pattern);
550                         break;
551                 case 4:
552                         for (i = 0; i < count; i++, ptr += wordsize)
553                                 target_buffer_set_u32(target, ptr, pattern);
554                         break;
555                 case 2:
556                         for (i = 0; i < count; i++, ptr += wordsize)
557                                 target_buffer_set_u16(target, ptr, pattern);
558                         break;
559                 case 1:
560                         memset(ptr, pattern, count);
561                         ptr += count;
562                         break;
563                 default:
564                         LOG_ERROR("BUG: can't happen");
565                         exit(-1);
566         }
567
568         if (padding_at_end) {
569                 memset(ptr, bank->default_padded_value, padding_at_end);
570                 LOG_INFO("Padding at " TARGET_ADDR_FMT " with %" PRId32
571                         " bytes (bank write end alignment)",
572                         end_addr + 1, padding_at_end);
573         }
574
575         struct duration bench;
576         duration_start(&bench);
577
578         retval = flash_driver_write(bank, buffer, aligned_start - bank->base, aligned_size);
579         if (retval != ERROR_OK)
580                 goto done;
581
582         retval = flash_driver_read(bank, buffer, address - bank->base, size_bytes);
583         if (retval != ERROR_OK)
584                 goto done;
585
586         for (i = 0, ptr = buffer; i < count; i++) {
587                 uint64_t readback = 0;
588
589                 switch (wordsize) {
590                         case 8:
591                                 readback = target_buffer_get_u64(target, ptr);
592                                 break;
593                         case 4:
594                                 readback = target_buffer_get_u32(target, ptr);
595                                 break;
596                         case 2:
597                                 readback = target_buffer_get_u16(target, ptr);
598                                 break;
599                         case 1:
600                                 readback = *ptr;
601                                 break;
602                 }
603                 if (readback != pattern) {
604                         LOG_ERROR(
605                                 "Verification error address " TARGET_ADDR_FMT
606                                 ", read back 0x%02" PRIx64 ", expected 0x%02" PRIx64,
607                                 address + i * wordsize, readback, pattern);
608                         retval = ERROR_FAIL;
609                         goto done;
610                 }
611                 ptr += wordsize;
612         }
613
614         if ((retval == ERROR_OK) && (duration_measure(&bench) == ERROR_OK)) {
615                 command_print(CMD, "wrote %" PRIu32 " bytes to " TARGET_ADDR_FMT
616                         " in %fs (%0.3f KiB/s)", size_bytes, address,
617                         duration_elapsed(&bench), duration_kbps(&bench, size_bytes));
618         }
619
620 done:
621         free(buffer);
622
623         return retval;
624 }
625
626 COMMAND_HANDLER(handle_flash_write_bank_command)
627 {
628         uint32_t offset;
629         uint8_t *buffer;
630         size_t length;
631         struct fileio *fileio;
632
633         if (CMD_ARGC < 2 || CMD_ARGC > 3)
634                 return ERROR_COMMAND_SYNTAX_ERROR;
635
636         struct duration bench;
637         duration_start(&bench);
638
639         struct flash_bank *bank;
640         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
641         if (ERROR_OK != retval)
642                 return retval;
643
644         offset = 0;
645
646         if (CMD_ARGC > 2)
647                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], offset);
648
649         if (offset > bank->size) {
650                 LOG_ERROR("Offset 0x%8.8" PRIx32 " is out of range of the flash bank",
651                         offset);
652                 return ERROR_COMMAND_ARGUMENT_INVALID;
653         }
654
655         if (fileio_open(&fileio, CMD_ARGV[1], FILEIO_READ, FILEIO_BINARY) != ERROR_OK)
656                 return ERROR_FAIL;
657
658         size_t filesize;
659         retval = fileio_size(fileio, &filesize);
660         if (retval != ERROR_OK) {
661                 fileio_close(fileio);
662                 return retval;
663         }
664
665         length = MIN(filesize, bank->size - offset);
666
667         if (!length) {
668                 LOG_INFO("Nothing to write to flash bank");
669                 fileio_close(fileio);
670                 return ERROR_OK;
671         }
672
673         if (length != filesize)
674                 LOG_INFO("File content exceeds flash bank size. Only writing the "
675                         "first %zu bytes of the file", length);
676
677         target_addr_t start_addr = bank->base + offset;
678         target_addr_t aligned_start = flash_write_align_start(bank, start_addr);
679         target_addr_t end_addr = start_addr + length - 1;
680         target_addr_t aligned_end = flash_write_align_end(bank, end_addr);
681         uint32_t aligned_size = aligned_end + 1 - aligned_start;
682         uint32_t padding_at_start = start_addr - aligned_start;
683         uint32_t padding_at_end = aligned_end - end_addr;
684
685         buffer = malloc(aligned_size);
686         if (buffer == NULL) {
687                 fileio_close(fileio);
688                 LOG_ERROR("Out of memory");
689                 return ERROR_FAIL;
690         }
691
692         if (padding_at_start) {
693                 memset(buffer, bank->default_padded_value, padding_at_start);
694                 LOG_WARNING("Start offset 0x%08" PRIx32
695                         " breaks the required alignment of flash bank %s",
696                         offset, bank->name);
697                 LOG_WARNING("Padding %" PRId32 " bytes from " TARGET_ADDR_FMT,
698                     padding_at_start, aligned_start);
699         }
700
701         uint8_t *ptr = buffer + padding_at_start;
702         size_t buf_cnt;
703         if (fileio_read(fileio, length, ptr, &buf_cnt) != ERROR_OK) {
704                 free(buffer);
705                 fileio_close(fileio);
706                 return ERROR_FAIL;
707         }
708
709         if (buf_cnt != length) {
710                 LOG_ERROR("Short read");
711                 free(buffer);
712                 return ERROR_FAIL;
713         }
714
715         ptr += length;
716
717         if (padding_at_end) {
718                 memset(ptr, bank->default_padded_value, padding_at_end);
719                 LOG_INFO("Padding at " TARGET_ADDR_FMT " with %" PRId32
720                         " bytes (bank write end alignment)",
721                         end_addr + 1, padding_at_end);
722         }
723
724         retval = flash_driver_write(bank, buffer, aligned_start - bank->base, aligned_size);
725
726         free(buffer);
727
728         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK)) {
729                 command_print(CMD, "wrote %zu bytes from file %s to flash bank %u"
730                         " at offset 0x%8.8" PRIx32 " in %fs (%0.3f KiB/s)",
731                         length, CMD_ARGV[1], bank->bank_number, offset,
732                         duration_elapsed(&bench), duration_kbps(&bench, length));
733         }
734
735         fileio_close(fileio);
736
737         return retval;
738 }
739
740 COMMAND_HANDLER(handle_flash_read_bank_command)
741 {
742         uint32_t offset;
743         uint8_t *buffer;
744         struct fileio *fileio;
745         uint32_t length;
746         size_t written;
747
748         if (CMD_ARGC < 2 || CMD_ARGC > 4)
749                 return ERROR_COMMAND_SYNTAX_ERROR;
750
751         struct duration bench;
752         duration_start(&bench);
753
754         struct flash_bank *p;
755         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
756
757         if (ERROR_OK != retval)
758                 return retval;
759
760         offset = 0;
761
762         if (CMD_ARGC > 2)
763                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], offset);
764
765         if (offset > p->size) {
766                 LOG_ERROR("Offset 0x%8.8" PRIx32 " is out of range of the flash bank",
767                         offset);
768                 return ERROR_COMMAND_ARGUMENT_INVALID;
769         }
770
771         length = p->size - offset;
772
773         if (CMD_ARGC > 3)
774                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[3], length);
775
776         if (offset + length > p->size) {
777                 LOG_ERROR("Length of %" PRIu32 " bytes with offset 0x%8.8" PRIx32
778                         " is out of range of the flash bank", length, offset);
779                 return ERROR_COMMAND_ARGUMENT_INVALID;
780         }
781
782         buffer = malloc(length);
783         if (buffer == NULL) {
784                 LOG_ERROR("Out of memory");
785                 return ERROR_FAIL;
786         }
787
788         retval = flash_driver_read(p, buffer, offset, length);
789         if (retval != ERROR_OK) {
790                 LOG_ERROR("Read error");
791                 free(buffer);
792                 return retval;
793         }
794
795         retval = fileio_open(&fileio, CMD_ARGV[1], FILEIO_WRITE, FILEIO_BINARY);
796         if (retval != ERROR_OK) {
797                 LOG_ERROR("Could not open file");
798                 free(buffer);
799                 return retval;
800         }
801
802         retval = fileio_write(fileio, length, buffer, &written);
803         fileio_close(fileio);
804         free(buffer);
805         if (retval != ERROR_OK) {
806                 LOG_ERROR("Could not write file");
807                 return ERROR_FAIL;
808         }
809
810         if (duration_measure(&bench) == ERROR_OK)
811                 command_print(CMD, "wrote %zd bytes to file %s from flash bank %u"
812                         " at offset 0x%8.8" PRIx32 " in %fs (%0.3f KiB/s)",
813                         written, CMD_ARGV[1], p->bank_number, offset,
814                         duration_elapsed(&bench), duration_kbps(&bench, written));
815
816         return retval;
817 }
818
819
820 COMMAND_HANDLER(handle_flash_verify_bank_command)
821 {
822         uint32_t offset;
823         uint8_t *buffer_file, *buffer_flash;
824         struct fileio *fileio;
825         size_t read_cnt;
826         size_t filesize;
827         size_t length;
828         int differ;
829
830         if (CMD_ARGC < 2 || CMD_ARGC > 3)
831                 return ERROR_COMMAND_SYNTAX_ERROR;
832
833         struct duration bench;
834         duration_start(&bench);
835
836         struct flash_bank *p;
837         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
838         if (ERROR_OK != retval)
839                 return retval;
840
841         offset = 0;
842
843         if (CMD_ARGC > 2)
844                 COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], offset);
845
846         if (offset > p->size) {
847                 LOG_ERROR("Offset 0x%8.8" PRIx32 " is out of range of the flash bank",
848                         offset);
849                 return ERROR_COMMAND_ARGUMENT_INVALID;
850         }
851
852         retval = fileio_open(&fileio, CMD_ARGV[1], FILEIO_READ, FILEIO_BINARY);
853         if (retval != ERROR_OK) {
854                 LOG_ERROR("Could not open file");
855                 return retval;
856         }
857
858         retval = fileio_size(fileio, &filesize);
859         if (retval != ERROR_OK) {
860                 fileio_close(fileio);
861                 return retval;
862         }
863
864         length = MIN(filesize, p->size - offset);
865
866         if (!length) {
867                 LOG_INFO("Nothing to compare with flash bank");
868                 fileio_close(fileio);
869                 return ERROR_OK;
870         }
871
872         if (length != filesize)
873                 LOG_INFO("File content exceeds flash bank size. Only comparing the "
874                         "first %zu bytes of the file", length);
875
876         buffer_file = malloc(length);
877         if (buffer_file == NULL) {
878                 LOG_ERROR("Out of memory");
879                 fileio_close(fileio);
880                 return ERROR_FAIL;
881         }
882
883         retval = fileio_read(fileio, length, buffer_file, &read_cnt);
884         fileio_close(fileio);
885         if (retval != ERROR_OK) {
886                 LOG_ERROR("File read failure");
887                 free(buffer_file);
888                 return retval;
889         }
890
891         if (read_cnt != length) {
892                 LOG_ERROR("Short read");
893                 free(buffer_file);
894                 return ERROR_FAIL;
895         }
896
897         buffer_flash = malloc(length);
898         if (buffer_flash == NULL) {
899                 LOG_ERROR("Out of memory");
900                 free(buffer_file);
901                 return ERROR_FAIL;
902         }
903
904         retval = flash_driver_read(p, buffer_flash, offset, length);
905         if (retval != ERROR_OK) {
906                 LOG_ERROR("Flash read error");
907                 free(buffer_flash);
908                 free(buffer_file);
909                 return retval;
910         }
911
912         if (duration_measure(&bench) == ERROR_OK)
913                 command_print(CMD, "read %zd bytes from file %s and flash bank %u"
914                         " at offset 0x%8.8" PRIx32 " in %fs (%0.3f KiB/s)",
915                         length, CMD_ARGV[1], p->bank_number, offset,
916                         duration_elapsed(&bench), duration_kbps(&bench, length));
917
918         differ = memcmp(buffer_file, buffer_flash, length);
919         command_print(CMD, "contents %s", differ ? "differ" : "match");
920         if (differ) {
921                 uint32_t t;
922                 int diffs = 0;
923                 for (t = 0; t < length; t++) {
924                         if (buffer_flash[t] == buffer_file[t])
925                                 continue;
926                         command_print(CMD, "diff %d address 0x%08x. Was 0x%02x instead of 0x%02x",
927                                         diffs, t + offset, buffer_flash[t], buffer_file[t]);
928                         if (diffs++ >= 127) {
929                                 command_print(CMD, "More than 128 errors, the rest are not printed.");
930                                 break;
931                         }
932                         keep_alive();
933                 }
934         }
935         free(buffer_flash);
936         free(buffer_file);
937
938         return differ ? ERROR_FAIL : ERROR_OK;
939 }
940
941 void flash_set_dirty(void)
942 {
943         struct flash_bank *c;
944         int i;
945
946         /* set all flash to require erasing */
947         for (c = flash_bank_list(); c; c = c->next) {
948                 for (i = 0; i < c->num_sectors; i++)
949                         c->sectors[i].is_erased = 0;
950         }
951 }
952
953 COMMAND_HANDLER(handle_flash_padded_value_command)
954 {
955         if (CMD_ARGC != 2)
956                 return ERROR_COMMAND_SYNTAX_ERROR;
957
958         struct flash_bank *p;
959         int retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &p);
960         if (ERROR_OK != retval)
961                 return retval;
962
963         COMMAND_PARSE_NUMBER(u8, CMD_ARGV[1], p->default_padded_value);
964
965         command_print(CMD, "Default padded value set to 0x%" PRIx8 " for flash bank %u", \
966                         p->default_padded_value, p->bank_number);
967
968         return retval;
969 }
970
971 static const struct command_registration flash_exec_command_handlers[] = {
972         {
973                 .name = "probe",
974                 .handler = handle_flash_probe_command,
975                 .mode = COMMAND_EXEC,
976                 .usage = "bank_id",
977                 .help = "Identify a flash bank.",
978         },
979         {
980                 .name = "info",
981                 .handler = handle_flash_info_command,
982                 .mode = COMMAND_EXEC,
983                 .usage = "bank_id ['sectors']",
984                 .help = "Print information about a flash bank.",
985         },
986         {
987                 .name = "erase_check",
988                 .handler = handle_flash_erase_check_command,
989                 .mode = COMMAND_EXEC,
990                 .usage = "bank_id",
991                 .help = "Check erase state of all blocks in a "
992                         "flash bank.",
993         },
994         {
995                 .name = "erase_sector",
996                 .handler = handle_flash_erase_command,
997                 .mode = COMMAND_EXEC,
998                 .usage = "bank_id first_sector_num (last_sector_num|'last')",
999                 .help = "Erase a range of sectors in a flash bank.",
1000         },
1001         {
1002                 .name = "erase_address",
1003                 .handler = handle_flash_erase_address_command,
1004                 .mode = COMMAND_EXEC,
1005                 .usage = "['pad'] ['unlock'] address length",
1006                 .help = "Erase flash sectors starting at address and "
1007                         "continuing for length bytes.  If 'pad' is specified, "
1008                         "data outside that range may also be erased: the start "
1009                         "address may be decreased, and length increased, so "
1010                         "that all of the first and last sectors are erased. "
1011                         "If 'unlock' is specified, then the flash is unprotected "
1012                         "before erasing.",
1013
1014         },
1015         {
1016                 .name = "filld",
1017                 .handler = handle_flash_fill_command,
1018                 .mode = COMMAND_EXEC,
1019                 .usage = "address value n",
1020                 .help = "Fill n double-words with 64-bit value, starting at "
1021                         "word address.  (No autoerase.)",
1022         },
1023         {
1024                 .name = "fillw",
1025                 .handler = handle_flash_fill_command,
1026                 .mode = COMMAND_EXEC,
1027                 .usage = "address value n",
1028                 .help = "Fill n words with 32-bit value, starting at "
1029                         "word address.  (No autoerase.)",
1030         },
1031         {
1032                 .name = "fillh",
1033                 .handler = handle_flash_fill_command,
1034                 .mode = COMMAND_EXEC,
1035                 .usage = "address value n",
1036                 .help = "Fill n halfwords with 16-bit value, starting at "
1037                         "word address.  (No autoerase.)",
1038         },
1039         {
1040                 .name = "fillb",
1041                 .handler = handle_flash_fill_command,
1042                 .mode = COMMAND_EXEC,
1043                 .usage = "address value n",
1044                 .help = "Fill n bytes with 8-bit value, starting at "
1045                         "word address.  (No autoerase.)",
1046         },
1047         {
1048                 .name = "write_bank",
1049                 .handler = handle_flash_write_bank_command,
1050                 .mode = COMMAND_EXEC,
1051                 .usage = "bank_id filename [offset]",
1052                 .help = "Write binary data from file to flash bank. Allow optional "
1053                         "offset from beginning of the bank (defaults to zero).",
1054         },
1055         {
1056                 .name = "write_image",
1057                 .handler = handle_flash_write_image_command,
1058                 .mode = COMMAND_EXEC,
1059                 .usage = "[erase] [unlock] filename [offset [file_type]]",
1060                 .help = "Write an image to flash.  Optionally first unprotect "
1061                         "and/or erase the region to be used.  Allow optional "
1062                         "offset from beginning of bank (defaults to zero)",
1063         },
1064         {
1065                 .name = "read_bank",
1066                 .handler = handle_flash_read_bank_command,
1067                 .mode = COMMAND_EXEC,
1068                 .usage = "bank_id filename [offset [length]]",
1069                 .help = "Read binary data from flash bank to file. Allow optional "
1070                         "offset from beginning of the bank (defaults to zero).",
1071         },
1072         {
1073                 .name = "verify_bank",
1074                 .handler = handle_flash_verify_bank_command,
1075                 .mode = COMMAND_EXEC,
1076                 .usage = "bank_id filename [offset]",
1077                 .help = "Compare the contents of a file with the contents of the "
1078                         "flash bank. Allow optional offset from beginning of the bank "
1079                         "(defaults to zero).",
1080         },
1081         {
1082                 .name = "protect",
1083                 .handler = handle_flash_protect_command,
1084                 .mode = COMMAND_EXEC,
1085                 .usage = "bank_id first_block [last_block|'last'] "
1086                         "('on'|'off')",
1087                 .help = "Turn protection on or off for a range of protection "
1088                         "blocks or sectors in a given flash bank. "
1089                         "See 'flash info' output for a list of blocks.",
1090         },
1091         {
1092                 .name = "padded_value",
1093                 .handler = handle_flash_padded_value_command,
1094                 .mode = COMMAND_EXEC,
1095                 .usage = "bank_id value",
1096                 .help = "Set default flash padded value",
1097         },
1098         COMMAND_REGISTRATION_DONE
1099 };
1100
1101 static int flash_init_drivers(struct command_context *cmd_ctx)
1102 {
1103         if (!flash_bank_list())
1104                 return ERROR_OK;
1105
1106         struct command *parent = command_find_in_context(cmd_ctx, "flash");
1107         return register_commands(cmd_ctx, parent, flash_exec_command_handlers);
1108 }
1109
1110 COMMAND_HANDLER(handle_flash_bank_command)
1111 {
1112         if (CMD_ARGC < 7) {
1113                 LOG_ERROR("usage: flash bank <name> <driver> "
1114                         "<base> <size> <chip_width> <bus_width> <target>");
1115                 return ERROR_COMMAND_SYNTAX_ERROR;
1116         }
1117         /* save bank name and advance arguments for compatibility */
1118         const char *bank_name = *CMD_ARGV++;
1119         CMD_ARGC--;
1120
1121         struct target *target = get_target(CMD_ARGV[5]);
1122         if (target == NULL) {
1123                 LOG_ERROR("target '%s' not defined", CMD_ARGV[5]);
1124                 return ERROR_FAIL;
1125         }
1126
1127         const char *driver_name = CMD_ARGV[0];
1128         const struct flash_driver *driver = flash_driver_find_by_name(driver_name);
1129         if (NULL == driver) {
1130                 /* no matching flash driver found */
1131                 LOG_ERROR("flash driver '%s' not found", driver_name);
1132                 return ERROR_FAIL;
1133         }
1134
1135         /* check the flash bank name is unique */
1136         if (get_flash_bank_by_name_noprobe(bank_name) != NULL) {
1137                 /* flash bank name already exists  */
1138                 LOG_ERROR("flash bank name '%s' already exists", bank_name);
1139                 return ERROR_FAIL;
1140         }
1141
1142         /* register flash specific commands */
1143         if (NULL != driver->commands) {
1144                 int retval = register_commands(CMD_CTX, NULL,
1145                                 driver->commands);
1146                 if (ERROR_OK != retval) {
1147                         LOG_ERROR("couldn't register '%s' commands",
1148                                 driver_name);
1149                         return ERROR_FAIL;
1150                 }
1151         }
1152
1153         struct flash_bank *c = calloc(1, sizeof(*c));
1154         c->name = strdup(bank_name);
1155         c->target = target;
1156         c->driver = driver;
1157         COMMAND_PARSE_NUMBER(target_addr, CMD_ARGV[1], c->base);
1158         COMMAND_PARSE_NUMBER(u32, CMD_ARGV[2], c->size);
1159         COMMAND_PARSE_NUMBER(int, CMD_ARGV[3], c->chip_width);
1160         COMMAND_PARSE_NUMBER(int, CMD_ARGV[4], c->bus_width);
1161         c->default_padded_value = c->erased_value = 0xff;
1162         c->minimal_write_gap = FLASH_WRITE_GAP_SECTOR;
1163
1164         int retval;
1165         retval = CALL_COMMAND_HANDLER(driver->flash_bank_command, c);
1166         if (ERROR_OK != retval) {
1167                 LOG_ERROR("'%s' driver rejected flash bank at " TARGET_ADDR_FMT
1168                                 "; usage: %s", driver_name, c->base, driver->usage);
1169                 free(c);
1170                 return retval;
1171         }
1172
1173         if (driver->usage == NULL)
1174                 LOG_DEBUG("'%s' driver usage field missing", driver_name);
1175
1176         flash_bank_add(c);
1177
1178         return ERROR_OK;
1179 }
1180
1181 COMMAND_HANDLER(handle_flash_banks_command)
1182 {
1183         if (CMD_ARGC != 0)
1184                 return ERROR_COMMAND_SYNTAX_ERROR;
1185
1186         unsigned n = 0;
1187         for (struct flash_bank *p = flash_bank_list(); p; p = p->next, n++) {
1188                 command_print(CMD, "#%d : %s (%s) at " TARGET_ADDR_FMT ", size 0x%8.8" PRIx32 ", "
1189                         "buswidth %u, chipwidth %u", p->bank_number,
1190                         p->name, p->driver->name, p->base, p->size,
1191                         p->bus_width, p->chip_width);
1192         }
1193         return ERROR_OK;
1194 }
1195
1196 static int jim_flash_list(Jim_Interp *interp, int argc, Jim_Obj * const *argv)
1197 {
1198         if (argc != 1) {
1199                 Jim_WrongNumArgs(interp, 1, argv,
1200                         "no arguments to 'flash list' command");
1201                 return JIM_ERR;
1202         }
1203
1204         Jim_Obj *list = Jim_NewListObj(interp, NULL, 0);
1205
1206         for (struct flash_bank *p = flash_bank_list(); p; p = p->next) {
1207                 Jim_Obj *elem = Jim_NewListObj(interp, NULL, 0);
1208
1209                 Jim_ListAppendElement(interp, elem, Jim_NewStringObj(interp, "name", -1));
1210                 Jim_ListAppendElement(interp, elem, Jim_NewStringObj(interp, p->driver->name, -1));
1211                 Jim_ListAppendElement(interp, elem, Jim_NewStringObj(interp, "base", -1));
1212                 Jim_ListAppendElement(interp, elem, Jim_NewIntObj(interp, p->base));
1213                 Jim_ListAppendElement(interp, elem, Jim_NewStringObj(interp, "size", -1));
1214                 Jim_ListAppendElement(interp, elem, Jim_NewIntObj(interp, p->size));
1215                 Jim_ListAppendElement(interp, elem, Jim_NewStringObj(interp, "bus_width", -1));
1216                 Jim_ListAppendElement(interp, elem, Jim_NewIntObj(interp, p->bus_width));
1217                 Jim_ListAppendElement(interp, elem, Jim_NewStringObj(interp, "chip_width", -1));
1218                 Jim_ListAppendElement(interp, elem, Jim_NewIntObj(interp, p->chip_width));
1219
1220                 Jim_ListAppendElement(interp, list, elem);
1221         }
1222
1223         Jim_SetResult(interp, list);
1224
1225         return JIM_OK;
1226 }
1227
1228 COMMAND_HANDLER(handle_flash_init_command)
1229 {
1230         if (CMD_ARGC != 0)
1231                 return ERROR_COMMAND_SYNTAX_ERROR;
1232
1233         static bool flash_initialized;
1234         if (flash_initialized) {
1235                 LOG_INFO("'flash init' has already been called");
1236                 return ERROR_OK;
1237         }
1238         flash_initialized = true;
1239
1240         LOG_DEBUG("Initializing flash devices...");
1241         return flash_init_drivers(CMD_CTX);
1242 }
1243
1244 static const struct command_registration flash_config_command_handlers[] = {
1245         {
1246                 .name = "bank",
1247                 .handler = handle_flash_bank_command,
1248                 .mode = COMMAND_CONFIG,
1249                 .usage = "bank_id driver_name base_address size_bytes "
1250                         "chip_width_bytes bus_width_bytes target "
1251                         "[driver_options ...]",
1252                 .help = "Define a new bank with the given name, "
1253                         "using the specified NOR flash driver.",
1254         },
1255         {
1256                 .name = "init",
1257                 .mode = COMMAND_CONFIG,
1258                 .handler = handle_flash_init_command,
1259                 .help = "Initialize flash devices.",
1260                 .usage = "",
1261         },
1262         {
1263                 .name = "banks",
1264                 .mode = COMMAND_ANY,
1265                 .handler = handle_flash_banks_command,
1266                 .help = "Display table with information about flash banks.",
1267                 .usage = "",
1268         },
1269         {
1270                 .name = "list",
1271                 .mode = COMMAND_ANY,
1272                 .jim_handler = jim_flash_list,
1273                 .help = "Returns a list of details about the flash banks.",
1274         },
1275         COMMAND_REGISTRATION_DONE
1276 };
1277 static const struct command_registration flash_command_handlers[] = {
1278         {
1279                 .name = "flash",
1280                 .mode = COMMAND_ANY,
1281                 .help = "NOR flash command group",
1282                 .chain = flash_config_command_handlers,
1283                 .usage = "",
1284         },
1285         COMMAND_REGISTRATION_DONE
1286 };
1287
1288 int flash_register_commands(struct command_context *cmd_ctx)
1289 {
1290         return register_commands(cmd_ctx, NULL, flash_command_handlers);
1291 }