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