1a04e123f9db4e07a285bc16c8a9d307fe9660ef
[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 static int handle_flash_bank_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
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 static int handle_flash_info_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
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 static int handle_flash_probe_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
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 static int handle_flash_erase_check_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
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 static int handle_flash_erase_address_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
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 static int handle_flash_protect_check_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
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 static int handle_flash_erase_command(struct command_context_s *cmd_ctx,
532                 char *cmd, char **args, int argc)
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 static int handle_flash_protect_command(struct command_context_s *cmd_ctx,
573                 char *cmd, char **args, int argc)
574 {
575         if (argc != 3)
576                 return ERROR_COMMAND_SYNTAX_ERROR;
577
578         uint32_t bank_nr;
579         uint32_t first;
580         uint32_t last;
581         int set;
582
583         COMMAND_PARSE_NUMBER(u32, args[0], bank_nr);
584         flash_bank_t *p = get_flash_bank_by_num(bank_nr);
585         if (!p)
586                 return ERROR_OK;
587
588         COMMAND_PARSE_NUMBER(u32, args[1], first);
589         if (strcmp(args[2], "last") == 0)
590                 last = p->num_sectors - 1;
591         else
592                 COMMAND_PARSE_NUMBER(u32, args[2], last);
593
594         if (strcmp(args[3], "on") == 0)
595                 set = 1;
596         else if (strcmp(args[3], "off") == 0)
597                 set = 0;
598         else
599                 return ERROR_COMMAND_SYNTAX_ERROR;
600
601         int retval;
602         if ((retval = flash_check_sector_parameters(cmd_ctx,
603                         first, last, p->num_sectors)) != ERROR_OK)
604                 return retval;
605
606         retval = flash_driver_protect(p, set, first, last);
607         if (retval == ERROR_OK) {
608                 command_print(cmd_ctx, "%s protection for sectors %i "
609                                 "through %i on flash bank %i",
610                         (set) ? "set" : "cleared", (int) first,
611                         (int) last, (int) bank_nr);
612         }
613
614         return ERROR_OK;
615 }
616
617 static int handle_flash_write_image_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
618 {
619         target_t *target = get_current_target(cmd_ctx);
620
621         image_t image;
622         uint32_t written;
623
624         int retval;
625
626         if (argc < 1)
627         {
628                 return ERROR_COMMAND_SYNTAX_ERROR;
629         }
630
631         /* flash auto-erase is disabled by default*/
632         int auto_erase = 0;
633         bool auto_unlock = false;
634
635         for (;;)
636         {
637                 if (strcmp(args[0], "erase") == 0)
638                 {
639                         auto_erase = 1;
640                         args++;
641                         argc--;
642                         command_print(cmd_ctx, "auto erase enabled");
643                 } else if (strcmp(args[0], "unlock") == 0)
644                 {
645                         auto_unlock = true;
646                         args++;
647                         argc--;
648                         command_print(cmd_ctx, "auto unlock enabled");
649                 } else
650                 {
651                         break;
652                 }
653         }
654
655         if (argc < 1)
656         {
657                 return ERROR_COMMAND_SYNTAX_ERROR;
658         }
659
660         if (!target)
661         {
662                 LOG_ERROR("no target selected");
663                 return ERROR_FAIL;
664         }
665
666         struct duration bench;
667         duration_start(&bench);
668
669         if (argc >= 2)
670         {
671                 image.base_address_set = 1;
672                 COMMAND_PARSE_NUMBER(int, args[1], image.base_address);
673         }
674         else
675         {
676                 image.base_address_set = 0;
677                 image.base_address = 0x0;
678         }
679
680         image.start_address_set = 0;
681
682         retval = image_open(&image, args[0], (argc == 3) ? args[2] : NULL);
683         if (retval != ERROR_OK)
684         {
685                 return retval;
686         }
687
688         retval = flash_write_unlock(target, &image, &written, auto_erase, auto_unlock);
689         if (retval != ERROR_OK)
690         {
691                 image_close(&image);
692                 return retval;
693         }
694
695         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
696         {
697                 command_print(cmd_ctx, "wrote %" PRIu32 " byte from file %s "
698                                 "in %fs (%0.3f kb/s)", written, args[0],
699                                 duration_elapsed(&bench), duration_kbps(&bench, written));
700         }
701
702         image_close(&image);
703
704         return retval;
705 }
706
707 static int handle_flash_fill_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
708 {
709         int err = ERROR_OK;
710         uint32_t address;
711         uint32_t pattern;
712         uint32_t count;
713         uint8_t chunk[1024];
714         uint8_t readback[1024];
715         uint32_t wrote = 0;
716         uint32_t cur_size = 0;
717         uint32_t chunk_count;
718         target_t *target = get_current_target(cmd_ctx);
719         uint32_t i;
720         uint32_t wordsize;
721
722         if (argc != 3)
723                 return ERROR_COMMAND_SYNTAX_ERROR;
724
725         COMMAND_PARSE_NUMBER(u32, args[0], address);
726         COMMAND_PARSE_NUMBER(u32, args[1], pattern);
727         COMMAND_PARSE_NUMBER(u32, args[2], count);
728
729         if (count == 0)
730                 return ERROR_OK;
731
732         switch (cmd[4])
733         {
734         case 'w':
735                 wordsize = 4;
736                 break;
737         case 'h':
738                 wordsize = 2;
739                 break;
740         case 'b':
741                 wordsize = 1;
742                 break;
743         default:
744                 return ERROR_COMMAND_SYNTAX_ERROR;
745         }
746
747         chunk_count = MIN(count, (1024 / wordsize));
748         switch (wordsize)
749         {
750         case 4:
751                 for (i = 0; i < chunk_count; i++)
752                 {
753                         target_buffer_set_u32(target, chunk + i * wordsize, pattern);
754                 }
755                 break;
756         case 2:
757                 for (i = 0; i < chunk_count; i++)
758                 {
759                         target_buffer_set_u16(target, chunk + i * wordsize, pattern);
760                 }
761                 break;
762         case 1:
763                 memset(chunk, pattern, chunk_count);
764                 break;
765         default:
766                 LOG_ERROR("BUG: can't happen");
767                 exit(-1);
768         }
769
770         struct duration bench;
771         duration_start(&bench);
772
773         for (wrote = 0; wrote < (count*wordsize); wrote += cur_size)
774         {
775                 cur_size = MIN((count*wordsize - wrote), sizeof(chunk));
776                 flash_bank_t *bank;
777                 bank = get_flash_bank_by_addr(target, address);
778                 if (bank == NULL)
779                 {
780                         return ERROR_FAIL;
781                 }
782                 err = flash_driver_write(bank, chunk, address - bank->base + wrote, cur_size);
783                 if (err != ERROR_OK)
784                         return err;
785
786                 err = target_read_buffer(target, address + wrote, cur_size, readback);
787                 if (err != ERROR_OK)
788                         return err;
789
790                 unsigned i;
791                 for (i = 0; i < cur_size; i++)
792                 {
793                         if (readback[i]!=chunk[i])
794                         {
795                                 LOG_ERROR("Verfication error address 0x%08" PRIx32 ", read back 0x%02x, expected 0x%02x",
796                                                   address + wrote + i, readback[i], chunk[i]);
797                                 return ERROR_FAIL;
798                         }
799                 }
800         }
801
802         if (duration_measure(&bench) == ERROR_OK)
803         {
804                 command_print(cmd_ctx, "wrote %" PRIu32 " bytes to 0x%8.8" PRIx32 
805                                 " in %fs (%0.3f kb/s)", wrote, address,
806                                 duration_elapsed(&bench), duration_kbps(&bench, wrote));
807         }
808         return ERROR_OK;
809 }
810
811 static int handle_flash_write_bank_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
812 {
813         uint32_t offset;
814         uint8_t *buffer;
815         uint32_t buf_cnt;
816         fileio_t fileio;
817
818         if (argc != 3)
819                 return ERROR_COMMAND_SYNTAX_ERROR;
820
821         struct duration bench;
822         duration_start(&bench);
823
824         flash_bank_t *p;
825         int retval = flash_command_get_bank_by_num(cmd_ctx, args[0], &p);
826         if (ERROR_OK != retval)
827                 return retval;
828
829         COMMAND_PARSE_NUMBER(u32, args[2], offset);
830
831         if (fileio_open(&fileio, args[1], FILEIO_READ, FILEIO_BINARY) != ERROR_OK)
832         {
833                 return ERROR_OK;
834         }
835
836         buffer = malloc(fileio.size);
837         if (fileio_read(&fileio, fileio.size, buffer, &buf_cnt) != ERROR_OK)
838         {
839                 free(buffer);
840                 fileio_close(&fileio);
841                 return ERROR_OK;
842         }
843
844         retval = flash_driver_write(p, buffer, offset, buf_cnt);
845
846         free(buffer);
847         buffer = NULL;
848
849         if ((ERROR_OK == retval) && (duration_measure(&bench) == ERROR_OK))
850         {
851                 command_print(cmd_ctx, "wrote %lld byte from file %s to flash bank %u"
852                                 " at offset 0x%8.8" PRIx32 " in %fs (%0.3f kb/s)",
853                                 fileio.size, args[1], p->bank_number, offset,
854                                 duration_elapsed(&bench), duration_kbps(&bench, fileio.size));
855         }
856
857         fileio_close(&fileio);
858
859         return retval;
860 }
861
862 void flash_set_dirty(void)
863 {
864         flash_bank_t *c;
865         int i;
866
867         /* set all flash to require erasing */
868         for (c = flash_banks; c; c = c->next)
869         {
870                 for (i = 0; i < c->num_sectors; i++)
871                 {
872                         c->sectors[i].is_erased = 0;
873                 }
874         }
875 }
876
877 /* lookup flash bank by address */
878 flash_bank_t *get_flash_bank_by_addr(target_t *target, uint32_t addr)
879 {
880         flash_bank_t *c;
881
882         /* cycle through bank list */
883         for (c = flash_banks; c; c = c->next)
884         {
885                 int retval;
886                 retval = c->driver->auto_probe(c);
887
888                 if (retval != ERROR_OK)
889                 {
890                         LOG_ERROR("auto_probe failed %d\n", retval);
891                         return NULL;
892                 }
893                 /* check whether address belongs to this flash bank */
894                 if ((addr >= c->base) && (addr <= c->base + (c->size - 1)) && target == c->target)
895                         return c;
896         }
897         LOG_ERROR("No flash at address 0x%08" PRIx32 "\n", addr);
898         return NULL;
899 }
900
901 /* erase given flash region, selects proper bank according to target and address */
902 static int flash_iterate_address_range(target_t *target, uint32_t addr, uint32_t length,
903                 int (*callback)(struct flash_bank_s *bank, int first, int last))
904 {
905         flash_bank_t *c;
906         int first = -1;
907         int last = -1;
908         int i;
909
910         if ((c = get_flash_bank_by_addr(target, addr)) == NULL)
911                 return ERROR_FLASH_DST_OUT_OF_BANK; /* no corresponding bank found */
912
913         if (c->size == 0 || c->num_sectors == 0)
914         {
915                 LOG_ERROR("Bank is invalid");
916                 return ERROR_FLASH_BANK_INVALID;
917         }
918
919         if (length == 0)
920         {
921                 /* special case, erase whole bank when length is zero */
922                 if (addr != c->base)
923                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
924
925                 return callback(c, 0, c->num_sectors - 1);
926         }
927
928         /* check whether it fits */
929         if (addr + length - 1 > c->base + c->size - 1)
930                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
931
932         addr -= c->base;
933
934         for (i = 0; i < c->num_sectors; i++)
935         {
936                 /* check whether sector overlaps with the given range and is not yet erased */
937                 if (addr < c->sectors[i].offset + c->sectors[i].size && addr + length > c->sectors[i].offset && c->sectors[i].is_erased != 1) {
938                         /* if first is not set yet then this is the first sector */
939                         if (first == -1)
940                                 first = i;
941                         last = i; /* and it is the last one so far in any case */
942                 }
943         }
944
945         if (first == -1 || last == -1)
946                 return ERROR_OK;
947
948         return callback(c, first, last);
949 }
950
951
952
953 int flash_erase_address_range(target_t *target, uint32_t addr, uint32_t length)
954 {
955         return flash_iterate_address_range(target, addr, length, &flash_driver_erase);
956 }
957
958 static int flash_driver_unprotect(struct flash_bank_s *bank, int first, int last)
959 {
960         return flash_driver_protect(bank, 0, first, last);
961 }
962
963 static int flash_unlock_address_range(target_t *target, uint32_t addr, uint32_t length)
964 {
965         return flash_iterate_address_range(target, addr, length, &flash_driver_unprotect);
966 }
967
968
969 /* write (optional verify) an image to flash memory of the given target */
970 static int flash_write_unlock(target_t *target, image_t *image, uint32_t *written, int erase, bool unlock)
971 {
972         int retval = ERROR_OK;
973
974         int section;
975         uint32_t section_offset;
976         flash_bank_t *c;
977         int *padding;
978
979         section = 0;
980         section_offset = 0;
981
982         if (written)
983                 *written = 0;
984
985         if (erase)
986         {
987                 /* assume all sectors need erasing - stops any problems
988                  * when flash_write is called multiple times */
989
990                 flash_set_dirty();
991         }
992
993         /* allocate padding array */
994         padding = malloc(image->num_sections * sizeof(padding));
995
996         /* loop until we reach end of the image */
997         while (section < image->num_sections)
998         {
999                 uint32_t buffer_size;
1000                 uint8_t *buffer;
1001                 int section_first;
1002                 int section_last;
1003                 uint32_t run_address = image->sections[section].base_address + section_offset;
1004                 uint32_t run_size = image->sections[section].size - section_offset;
1005                 int pad_bytes = 0;
1006
1007                 if (image->sections[section].size ==  0)
1008                 {
1009                         LOG_WARNING("empty section %d", section);
1010                         section++;
1011                         section_offset = 0;
1012                         continue;
1013                 }
1014
1015                 /* find the corresponding flash bank */
1016                 if ((c = get_flash_bank_by_addr(target, run_address)) == NULL)
1017                 {
1018                         section++; /* and skip it */
1019                         section_offset = 0;
1020                         continue;
1021                 }
1022
1023                 /* collect consecutive sections which fall into the same bank */
1024                 section_first = section;
1025                 section_last = section;
1026                 padding[section] = 0;
1027                 while ((run_address + run_size - 1 < c->base + c->size - 1)
1028                                 && (section_last + 1 < image->num_sections))
1029                 {
1030                         if (image->sections[section_last + 1].base_address < (run_address + run_size))
1031                         {
1032                                 LOG_DEBUG("section %d out of order(very slightly surprising, but supported)", section_last + 1);
1033                                 break;
1034                         }
1035                         /* if we have multiple sections within our image, flash programming could fail due to alignment issues
1036                          * attempt to rebuild a consecutive buffer for the flash loader */
1037                         pad_bytes = (image->sections[section_last + 1].base_address) - (run_address + run_size);
1038                         if ((run_address + run_size + pad_bytes) > (c->base + c->size))
1039                                 break;
1040                         padding[section_last] = pad_bytes;
1041                         run_size += image->sections[++section_last].size;
1042                         run_size += pad_bytes;
1043                         padding[section_last] = 0;
1044
1045                         LOG_INFO("Padding image section %d with %d bytes", section_last-1, pad_bytes);
1046                 }
1047
1048                 /* fit the run into bank constraints */
1049                 if (run_address + run_size - 1 > c->base + c->size - 1)
1050                 {
1051                         LOG_WARNING("writing %d bytes only - as image section is %d bytes and bank is only %d bytes", \
1052                                     (int)(c->base + c->size - run_address), (int)(run_size), (int)(c->size));
1053                         run_size = c->base + c->size - run_address;
1054                 }
1055
1056                 /* allocate buffer */
1057                 buffer = malloc(run_size);
1058                 buffer_size = 0;
1059
1060                 /* read sections to the buffer */
1061                 while (buffer_size < run_size)
1062                 {
1063                         uint32_t size_read;
1064
1065                         size_read = run_size - buffer_size;
1066                         if (size_read > image->sections[section].size - section_offset)
1067                             size_read = image->sections[section].size - section_offset;
1068
1069                         if ((retval = image_read_section(image, section, section_offset,
1070                                         size_read, buffer + buffer_size, &size_read)) != ERROR_OK || size_read == 0)
1071                         {
1072                                 free(buffer);
1073                                 free(padding);
1074                                 return retval;
1075                         }
1076
1077                         /* see if we need to pad the section */
1078                         while (padding[section]--)
1079                                  (buffer + buffer_size)[size_read++] = 0xff;
1080
1081                         buffer_size += size_read;
1082                         section_offset += size_read;
1083
1084                         if (section_offset >= image->sections[section].size)
1085                         {
1086                                 section++;
1087                                 section_offset = 0;
1088                         }
1089                 }
1090
1091                 retval = ERROR_OK;
1092
1093                 if (unlock)
1094                 {
1095                         retval = flash_unlock_address_range(target, run_address, run_size);
1096                 }
1097                 if (retval == ERROR_OK)
1098                 {
1099                         if (erase)
1100                         {
1101                                 /* calculate and erase sectors */
1102                                 retval = flash_erase_address_range(target, run_address, run_size);
1103                         }
1104                 }
1105
1106                 if (retval == ERROR_OK)
1107                 {
1108                         /* write flash sectors */
1109                         retval = flash_driver_write(c, buffer, run_address - c->base, run_size);
1110                 }
1111
1112                 free(buffer);
1113
1114                 if (retval != ERROR_OK)
1115                 {
1116                         free(padding);
1117                         return retval; /* abort operation */
1118                 }
1119
1120                 if (written != NULL)
1121                         *written += run_size; /* add run size to total written counter */
1122         }
1123
1124         free(padding);
1125
1126         return retval;
1127 }
1128
1129 int flash_write(target_t *target, image_t *image, uint32_t *written, int erase)
1130 {
1131         return flash_write_unlock(target, image, written, erase, false);
1132 }
1133
1134 int default_flash_mem_blank_check(struct flash_bank_s *bank)
1135 {
1136         target_t *target = bank->target;
1137         uint8_t buffer[1024];
1138         int buffer_size = sizeof(buffer);
1139         int i;
1140         uint32_t nBytes;
1141
1142         if (bank->target->state != TARGET_HALTED)
1143         {
1144                 LOG_ERROR("Target not halted");
1145                 return ERROR_TARGET_NOT_HALTED;
1146         }
1147
1148         for (i = 0; i < bank->num_sectors; i++)
1149         {
1150                 uint32_t j;
1151                 bank->sectors[i].is_erased = 1;
1152
1153                 for (j = 0; j < bank->sectors[i].size; j += buffer_size)
1154                 {
1155                         uint32_t chunk;
1156                         int retval;
1157                         chunk = buffer_size;
1158                         if (chunk > (j - bank->sectors[i].size))
1159                         {
1160                                 chunk = (j - bank->sectors[i].size);
1161                         }
1162
1163                         retval = target_read_memory(target, bank->base + bank->sectors[i].offset + j, 4, chunk/4, buffer);
1164                         if (retval != ERROR_OK)
1165                                 return retval;
1166
1167                         for (nBytes = 0; nBytes < chunk; nBytes++)
1168                         {
1169                                 if (buffer[nBytes] != 0xFF)
1170                                 {
1171                                         bank->sectors[i].is_erased = 0;
1172                                         break;
1173                                 }
1174                         }
1175                 }
1176         }
1177
1178         return ERROR_OK;
1179 }
1180
1181 int default_flash_blank_check(struct flash_bank_s *bank)
1182 {
1183         target_t *target = bank->target;
1184         int i;
1185         int retval;
1186         int fast_check = 0;
1187         uint32_t blank;
1188
1189         if (bank->target->state != TARGET_HALTED)
1190         {
1191                 LOG_ERROR("Target not halted");
1192                 return ERROR_TARGET_NOT_HALTED;
1193         }
1194
1195         for (i = 0; i < bank->num_sectors; i++)
1196         {
1197                 uint32_t address = bank->base + bank->sectors[i].offset;
1198                 uint32_t size = bank->sectors[i].size;
1199
1200                 if ((retval = target_blank_check_memory(target, address, size, &blank)) != ERROR_OK)
1201                 {
1202                         fast_check = 0;
1203                         break;
1204                 }
1205                 if (blank == 0xFF)
1206                         bank->sectors[i].is_erased = 1;
1207                 else
1208                         bank->sectors[i].is_erased = 0;
1209                 fast_check = 1;
1210         }
1211
1212         if (!fast_check)
1213         {
1214                 LOG_USER("Running slow fallback erase check - add working memory");
1215                 return default_flash_mem_blank_check(bank);
1216         }
1217
1218         return ERROR_OK;
1219 }
1220
1221 int flash_init_drivers(struct command_context_s *cmd_ctx)
1222 {
1223         register_jim(cmd_ctx, "ocd_flash_banks",
1224                         jim_flash_banks, "return information about the flash banks");
1225
1226         if (!flash_banks)
1227                 return ERROR_OK;
1228
1229         register_command(cmd_ctx, flash_cmd, "info",
1230                         handle_flash_info_command, COMMAND_EXEC,
1231                         "print info about flash bank <num>");
1232         register_command(cmd_ctx, flash_cmd, "probe",
1233                         handle_flash_probe_command, COMMAND_EXEC,
1234                         "identify flash bank <num>");
1235         register_command(cmd_ctx, flash_cmd, "erase_check",
1236                         handle_flash_erase_check_command, COMMAND_EXEC,
1237                         "check erase state of sectors in flash bank <num>");
1238         register_command(cmd_ctx, flash_cmd, "protect_check",
1239                         handle_flash_protect_check_command, COMMAND_EXEC,
1240                         "check protection state of sectors in flash bank <num>");
1241         register_command(cmd_ctx, flash_cmd, "erase_sector",
1242                         handle_flash_erase_command, COMMAND_EXEC,
1243                         "erase sectors at <bank> <first> <last>");
1244         register_command(cmd_ctx, flash_cmd, "erase_address",
1245                         handle_flash_erase_address_command, COMMAND_EXEC,
1246                         "erase address range <address> <length>");
1247
1248         register_command(cmd_ctx, flash_cmd, "fillw",
1249                         handle_flash_fill_command, COMMAND_EXEC,
1250                         "fill with pattern (no autoerase) <address> <word_pattern> <count>");
1251         register_command(cmd_ctx, flash_cmd, "fillh",
1252                         handle_flash_fill_command, COMMAND_EXEC,
1253                         "fill with pattern <address> <halfword_pattern> <count>");
1254         register_command(cmd_ctx, flash_cmd, "fillb",
1255                         handle_flash_fill_command, COMMAND_EXEC,
1256                         "fill with pattern <address> <byte_pattern> <count>");
1257
1258         register_command(cmd_ctx, flash_cmd, "write_bank",
1259                         handle_flash_write_bank_command, COMMAND_EXEC,
1260                         "write binary data to <bank> <file> <offset>");
1261         register_command(cmd_ctx, flash_cmd, "write_image",
1262                         handle_flash_write_image_command, COMMAND_EXEC,
1263                         "write_image [erase] [unlock] <file> [offset] [type]");
1264         register_command(cmd_ctx, flash_cmd, "protect",
1265                         handle_flash_protect_command, COMMAND_EXEC,
1266                         "set protection of sectors at <bank> <first> <last> <on | off>");
1267
1268         return ERROR_OK;
1269 }
1270
1271 int flash_register_commands(struct command_context_s *cmd_ctx)
1272 {
1273         flash_cmd = register_command(cmd_ctx, NULL, "flash",
1274                         NULL, COMMAND_ANY, NULL);
1275
1276         register_command(cmd_ctx, flash_cmd, "bank",
1277                         handle_flash_bank_command, COMMAND_CONFIG,
1278                         "flash bank <driver> <base> <size> "
1279                         "<chip_width> <bus_width> <target> [driver_options ...]");
1280         return ERROR_OK;
1281 }