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