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