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