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