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