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