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