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