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