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