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