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