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