NOR: add read() callback to struct flash_driver
[fw/openocd] / src / flash / nor / core.c
1 /***************************************************************************
2  *   Copyright (C) 2005 by Dominic Rath <Dominic.Rath@gmx.de>              *
3  *   Copyright (C) 2007-2010 Øyvind Harboe <oyvind.harboe@zylin.com>       *
4  *   Copyright (C) 2008 by Spencer Oliver <spen@spen-soft.co.uk>           *
5  *   Copyright (C) 2009 Zachary T Welch <zw@superlucidity.net>             *
6  *   Copyright (C) 2010 by Antonio Borneo <borneo.antonio@gmail.com>       *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program is distributed in the hope that it will be useful,       *
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
22  ***************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27 #include <flash/common.h>
28 #include <flash/nor/core.h>
29 #include <flash/nor/imp.h>
30 #include <target/image.h>
31
32
33 /**
34  * @file
35  * Upper level of NOR flash framework.
36  * The lower level interfaces are to drivers.  These upper level ones
37  * primarily support access from Tcl scripts or from GDB.
38  */
39
40 static struct flash_bank *flash_banks;
41
42 int flash_driver_erase(struct flash_bank *bank, int first, int last)
43 {
44         int retval;
45
46         retval = bank->driver->erase(bank, first, last);
47         if (retval != ERROR_OK)
48         {
49                 LOG_ERROR("failed erasing sectors %d to %d (%d)", first, last, retval);
50         }
51
52         return retval;
53 }
54
55 int flash_driver_protect(struct flash_bank *bank, int set, int first, int last)
56 {
57         int retval;
58
59         /* callers may not supply illegal parameters ... */
60         if (first < 0 || first > last || last >= bank->num_sectors)
61         {
62                 LOG_ERROR("illegal sector range");
63                 return ERROR_FAIL;
64         }
65
66         /* force "set" to 0/1 */
67         set = !!set;
68
69         /* DANGER!
70          *
71          * We must not use any cached information about protection state!!!!
72          *
73          * There are a million things that could change the protect state:
74          *
75          * the target could have reset, power cycled, been hot plugged,
76          * the application could have run, etc.
77          *
78          * Drivers only receive valid sector range.
79          */
80         retval = bank->driver->protect(bank, set, first, last);
81         if (retval != ERROR_OK)
82         {
83                 LOG_ERROR("failed setting protection for areas %d to %d (%d)", first, last, retval);
84         }
85
86         return retval;
87 }
88
89 int flash_driver_write(struct flash_bank *bank,
90                 uint8_t *buffer, uint32_t offset, uint32_t count)
91 {
92         int retval;
93
94         retval = bank->driver->write(bank, buffer, offset, count);
95         if (retval != ERROR_OK)
96         {
97                 LOG_ERROR("error writing to flash at address 0x%08" PRIx32 " at offset 0x%8.8" PRIx32 " (%d)",
98                           bank->base, offset, retval);
99         }
100
101         return retval;
102 }
103
104 int flash_driver_read(struct flash_bank *bank,
105                 uint8_t *buffer, uint32_t offset, uint32_t count)
106 {
107         int retval;
108
109         LOG_DEBUG("call flash_driver_read()");
110
111         retval = bank->driver->read(bank, buffer, offset, count);
112         if (retval != ERROR_OK)
113         {
114                 LOG_ERROR("error reading to flash at address 0x%08" PRIx32 " at offset 0x%8.8" PRIx32 " (%d)",
115                           bank->base, offset, retval);
116         }
117
118         return retval;
119 }
120
121 int default_flash_read(struct flash_bank *bank,
122                 uint8_t *buffer, uint32_t offset, uint32_t count)
123 {
124         return target_read_buffer(bank->target, offset + bank->base, count, buffer);
125 }
126
127 void flash_bank_add(struct flash_bank *bank)
128 {
129         /* put flash bank in linked list */
130         unsigned bank_num = 0;
131         if (flash_banks)
132         {
133                 /* find last flash bank */
134                 struct flash_bank *p = flash_banks;
135                 while (NULL != p->next)
136                 {
137                         bank_num += 1;
138                         p = p->next;
139                 }
140                 p->next = bank;
141                 bank_num += 1;
142         }
143         else
144                 flash_banks = bank;
145
146         bank->bank_number = bank_num;
147 }
148
149 struct flash_bank *flash_bank_list(void)
150 {
151         return flash_banks;
152 }
153
154 struct flash_bank *get_flash_bank_by_num_noprobe(int num)
155 {
156         struct flash_bank *p;
157         int i = 0;
158
159         for (p = flash_banks; p; p = p->next)
160         {
161                 if (i++ == num)
162                 {
163                         return p;
164                 }
165         }
166         LOG_ERROR("flash bank %d does not exist", num);
167         return NULL;
168 }
169
170 int flash_get_bank_count(void)
171 {
172         struct flash_bank *p;
173         int i = 0;
174         for (p = flash_banks; p; p = p->next)
175         {
176                 i++;
177         }
178         return i;
179 }
180
181 struct flash_bank *get_flash_bank_by_name(const char *name)
182 {
183         unsigned requested = get_flash_name_index(name);
184         unsigned found = 0;
185
186         struct flash_bank *bank;
187         for (bank = flash_banks; NULL != bank; bank = bank->next)
188         {
189                 if (strcmp(bank->name, name) == 0)
190                         return bank;
191                 if (!flash_driver_name_matches(bank->driver->name, name))
192                         continue;
193                 if (++found < requested)
194                         continue;
195                 return bank;
196         }
197         return NULL;
198 }
199
200 int get_flash_bank_by_num(int num, struct flash_bank **bank)
201 {
202         struct flash_bank *p = get_flash_bank_by_num_noprobe(num);
203         int retval;
204
205         if (p == NULL)
206         {
207                 return ERROR_FAIL;
208         }
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 retval;
216         }
217         *bank = p;
218         return ERROR_OK;
219 }
220
221 /* lookup flash bank by address */
222 struct flash_bank *get_flash_bank_by_addr(struct target *target, uint32_t addr)
223 {
224         struct flash_bank *c;
225
226         /* cycle through bank list */
227         for (c = flash_banks; c; c = c->next)
228         {
229                 int retval;
230                 retval = c->driver->auto_probe(c);
231
232                 if (retval != ERROR_OK)
233                 {
234                         LOG_ERROR("auto_probe failed %d\n", retval);
235                         return NULL;
236                 }
237                 /* check whether address belongs to this flash bank */
238                 if ((addr >= c->base) && (addr <= c->base + (c->size - 1)) && target == c->target)
239                         return c;
240         }
241         LOG_ERROR("No flash at address 0x%08" PRIx32 "\n", addr);
242         return NULL;
243 }
244
245 int default_flash_mem_blank_check(struct flash_bank *bank)
246 {
247         struct target *target = bank->target;
248         const int buffer_size = 1024;
249         int i;
250         uint32_t nBytes;
251         int retval = ERROR_OK;
252
253         if (bank->target->state != TARGET_HALTED)
254         {
255                 LOG_ERROR("Target not halted");
256                 return ERROR_TARGET_NOT_HALTED;
257         }
258
259         uint8_t *buffer = malloc(buffer_size);
260
261         for (i = 0; i < bank->num_sectors; i++)
262         {
263                 uint32_t j;
264                 bank->sectors[i].is_erased = 1;
265
266                 for (j = 0; j < bank->sectors[i].size; j += buffer_size)
267                 {
268                         uint32_t chunk;
269                         chunk = buffer_size;
270                         if (chunk > (j - bank->sectors[i].size))
271                         {
272                                 chunk = (j - bank->sectors[i].size);
273                         }
274
275                         retval = target_read_memory(target, bank->base + bank->sectors[i].offset + j, 4, chunk/4, buffer);
276                         if (retval != ERROR_OK)
277                         {
278                                 goto done;
279                         }
280
281                         for (nBytes = 0; nBytes < chunk; nBytes++)
282                         {
283                                 if (buffer[nBytes] != 0xFF)
284                                 {
285                                         bank->sectors[i].is_erased = 0;
286                                         break;
287                                 }
288                         }
289                 }
290         }
291
292         done:
293         free(buffer);
294
295         return retval;
296 }
297
298 int default_flash_blank_check(struct flash_bank *bank)
299 {
300         struct target *target = bank->target;
301         int i;
302         int retval;
303         int fast_check = 0;
304         uint32_t blank;
305
306         if (bank->target->state != TARGET_HALTED)
307         {
308                 LOG_ERROR("Target not halted");
309                 return ERROR_TARGET_NOT_HALTED;
310         }
311
312         for (i = 0; i < bank->num_sectors; i++)
313         {
314                 uint32_t address = bank->base + bank->sectors[i].offset;
315                 uint32_t size = bank->sectors[i].size;
316
317                 if ((retval = target_blank_check_memory(target, address, size, &blank)) != ERROR_OK)
318                 {
319                         fast_check = 0;
320                         break;
321                 }
322                 if (blank == 0xFF)
323                         bank->sectors[i].is_erased = 1;
324                 else
325                         bank->sectors[i].is_erased = 0;
326                 fast_check = 1;
327         }
328
329         if (!fast_check)
330         {
331                 LOG_USER("Running slow fallback erase check - add working memory");
332                 return default_flash_mem_blank_check(bank);
333         }
334
335         return ERROR_OK;
336 }
337
338 /* Manipulate given flash region, selecting the bank according to target
339  * and address.  Maps an address range to a set of sectors, and issues
340  * the callback() on that set ... e.g. to erase or unprotect its members.
341  *
342  * (Note a current bad assumption:  that protection operates on the same
343  * size sectors as erase operations use.)
344  *
345  * The "pad_reason" parameter is a kind of boolean:  when it's NULL, the
346  * range must fit those sectors exactly.  This is clearly safe; it can't
347  * erase data which the caller said to leave alone, for example.  If it's
348  * non-NULL, rather than failing, extra data in the first and/or last
349  * sectors will be added to the range, and that reason string is used when
350  * warning about those additions.
351  */
352 static int flash_iterate_address_range(struct target *target,
353                 char *pad_reason, uint32_t addr, uint32_t length,
354                 int (*callback)(struct flash_bank *bank, int first, int last))
355 {
356         struct flash_bank *c;
357         uint32_t last_addr = addr + length;     /* first address AFTER end */
358         int first = -1;
359         int last = -1;
360         int i;
361
362         if ((c = get_flash_bank_by_addr(target, addr)) == NULL)
363                 return ERROR_FLASH_DST_OUT_OF_BANK; /* no corresponding bank found */
364
365         if (c->size == 0 || c->num_sectors == 0)
366         {
367                 LOG_ERROR("Bank is invalid");
368                 return ERROR_FLASH_BANK_INVALID;
369         }
370
371         if (length == 0)
372         {
373                 /* special case, erase whole bank when length is zero */
374                 if (addr != c->base)
375                 {
376                         LOG_ERROR("Whole bank access must start at beginning of bank.");
377                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
378                 }
379
380                 return callback(c, 0, c->num_sectors - 1);
381         }
382
383         /* check whether it all fits in this bank */
384         if (addr + length - 1 > c->base + c->size - 1)
385         {
386                 LOG_ERROR("Flash access does not fit into bank.");
387                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
388         }
389
390         /** @todo: handle erasures that cross into adjacent banks */
391
392         addr -= c->base;
393         last_addr -= c->base;
394
395         for (i = 0; i < c->num_sectors; i++)
396         {
397                 struct flash_sector *f = c->sectors + i;
398                 uint32_t end = f->offset + f->size;
399
400                 /* start only on a sector boundary */
401                 if (first < 0) {
402                         /* scanned past the first sector? */
403                         if (addr < f->offset)
404                                 break;
405
406                         /* is this the first sector? */
407                         if (addr == f->offset)
408                                 first = i;
409
410                         /* Does this need head-padding?  If so, pad and warn;
411                          * or else force an error.
412                          *
413                          * Such padding can make trouble, since *WE* can't
414                          * ever know if that data was in use.  The warning
415                          * should help users sort out messes later.
416                          */
417                         else if (addr < end && pad_reason) {
418                                 /* FIXME say how many bytes (e.g. 80 KB) */
419                                 LOG_WARNING("Adding extra %s range, "
420                                                 "%#8.8x to %#8.8x",
421                                         pad_reason,
422                                         (unsigned) f->offset,
423                                         (unsigned) addr - 1);
424                                 first = i;
425                         } else
426                                 continue;
427                 }
428
429                 /* is this (also?) the last sector? */
430                 if (last_addr == end) {
431                         last = i;
432                         break;
433                 }
434
435                 /* Does this need tail-padding?  If so, pad and warn;
436                  * or else force an error.
437                  */
438                 if (last_addr < end && pad_reason) {
439                         /* FIXME say how many bytes (e.g. 80 KB) */
440                         LOG_WARNING("Adding extra %s range, "
441                                         "%#8.8x to %#8.8x",
442                                 pad_reason,
443                                 (unsigned) last_addr,
444                                 (unsigned) end - 1);
445                         last = i;
446                         break;
447                 }
448
449                 /* MUST finish on a sector boundary */
450                 if (last_addr <= f->offset)
451                         break;
452         }
453
454         /* invalid start or end address? */
455         if (first == -1 || last == -1) {
456                 LOG_ERROR("address range 0x%8.8x .. 0x%8.8x "
457                                 "is not sector-aligned",
458                                 (unsigned) (c->base + addr),
459                                 (unsigned) (c->base + last_addr - 1));
460                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
461         }
462
463         /* The NOR driver may trim this range down, based on what
464          * sectors are already erased/unprotected.  GDB currently
465          * blocks such optimizations.
466          */
467         return callback(c, first, last);
468 }
469
470 int flash_erase_address_range(struct target *target,
471                 bool pad, uint32_t addr, uint32_t length)
472 {
473         return flash_iterate_address_range(target, pad ? "erase" : NULL,
474                         addr, length, &flash_driver_erase);
475 }
476
477 static int flash_driver_unprotect(struct flash_bank *bank, int first, int last)
478 {
479         return flash_driver_protect(bank, 0, first, last);
480 }
481
482 int flash_unlock_address_range(struct target *target, uint32_t addr, uint32_t length)
483 {
484         /* By default, pad to sector boundaries ... the real issue here
485          * is that our (only) caller *permanently* removes protection,
486          * and doesn't restore it.
487          */
488         return flash_iterate_address_range(target, "unprotect",
489                         addr, length, &flash_driver_unprotect);
490 }
491
492 static int compare_section (const void * a, const void * b)
493 {
494         struct imageection *b1, *b2;
495         b1=*((struct imageection **)a);
496         b2=*((struct imageection **)b);
497
498         if (b1->base_address == b2->base_address)
499         {
500                 return 0;
501         } else if (b1->base_address > b2->base_address)
502         {
503                 return 1;
504         } else
505         {
506                 return -1;
507         }
508 }
509
510
511 int flash_write_unlock(struct target *target, struct image *image,
512                 uint32_t *written, int erase, bool unlock)
513 {
514         int retval = ERROR_OK;
515
516         int section;
517         uint32_t section_offset;
518         struct flash_bank *c;
519         int *padding;
520
521         section = 0;
522         section_offset = 0;
523
524         if (written)
525                 *written = 0;
526
527         if (erase)
528         {
529                 /* assume all sectors need erasing - stops any problems
530                  * when flash_write is called multiple times */
531
532                 flash_set_dirty();
533         }
534
535         /* allocate padding array */
536         padding = calloc(image->num_sections, sizeof(*padding));
537
538         /* This fn requires all sections to be in ascending order of addresses,
539          * whereas an image can have sections out of order. */
540         struct imageection **sections = malloc(sizeof(struct imageection *) *
541                         image->num_sections);
542         int i;
543         for (i = 0; i < image->num_sections; i++)
544         {
545                 sections[i] = &image->sections[i];
546         }
547
548         qsort(sections, image->num_sections, sizeof(struct imageection *),
549                         compare_section);
550
551         /* loop until we reach end of the image */
552         while (section < image->num_sections)
553         {
554                 uint32_t buffer_size;
555                 uint8_t *buffer;
556                 int section_first;
557                 int section_last;
558                 uint32_t run_address = sections[section]->base_address + section_offset;
559                 uint32_t run_size = sections[section]->size - section_offset;
560                 int pad_bytes = 0;
561
562                 if (sections[section]->size ==  0)
563                 {
564                         LOG_WARNING("empty section %d", section);
565                         section++;
566                         section_offset = 0;
567                         continue;
568                 }
569
570                 /* find the corresponding flash bank */
571                 if ((c = get_flash_bank_by_addr(target, run_address)) == NULL)
572                 {
573                         section++; /* and skip it */
574                         section_offset = 0;
575                         continue;
576                 }
577
578                 /* collect consecutive sections which fall into the same bank */
579                 section_first = section;
580                 section_last = section;
581                 padding[section] = 0;
582                 while ((run_address + run_size - 1 < c->base + c->size - 1)
583                                 && (section_last + 1 < image->num_sections))
584                 {
585                         /* sections are sorted */
586                         assert(sections[section_last + 1]->base_address >= c->base);
587                         if (sections[section_last + 1]->base_address >= (c->base + c->size))
588                         {
589                           /* Done with this bank */
590                           break;
591                         }
592
593                         /* FIXME This needlessly touches sectors BETWEEN the
594                          * sections it's writing.  Without auto erase, it just
595                          * writes ones.  That WILL INVALIDATE data in cases
596                          * like Stellaris Tempest chips, corrupting internal
597                          * ECC codes; and at least FreeScale suggests issues
598                          * with that approach (in HC11 documentation).
599                          *
600                          * With auto erase enabled, data in those sectors will
601                          * be needlessly destroyed; and some of the limited
602                          * number of flash erase cycles will be wasted...
603                          *
604                          * In both cases, the extra writes slow things down.
605                          */
606
607                         /* if we have multiple sections within our image,
608                          * flash programming could fail due to alignment issues
609                          * attempt to rebuild a consecutive buffer for the flash loader */
610                         pad_bytes = (sections[section_last + 1]->base_address) - (run_address + run_size);
611                         padding[section_last] = pad_bytes;
612                         run_size += sections[++section_last]->size;
613                         run_size += pad_bytes;
614
615                         if (pad_bytes > 0)
616                                 LOG_INFO("Padding image section %d with %d bytes", section_last-1, pad_bytes);
617                 }
618
619                 assert (run_address + run_size - 1 <= c->base + c->size - 1);
620
621                 /* If we're applying any sector automagic, then pad this
622                  * (maybe-combined) segment to the end of its last sector.
623                  */
624                 if (unlock || erase) {
625                         int sector;
626                         uint32_t offset_start = run_address - c->base;
627                         uint32_t offset_end = offset_start + run_size;
628                         uint32_t end = offset_end, delta;
629
630                         for (sector = 0; sector < c->num_sectors; sector++) {
631                                 end = c->sectors[sector].offset
632                                                 + c->sectors[sector].size;
633                                 if (offset_end <= end)
634                                         break;
635                         }
636
637                         delta = end - offset_end;
638                         padding[section_last] += delta;
639                         run_size += delta;
640                 }
641
642                 /* allocate buffer */
643                 buffer = malloc(run_size);
644                 buffer_size = 0;
645
646                 /* read sections to the buffer */
647                 while (buffer_size < run_size)
648                 {
649                         size_t size_read;
650
651                         size_read = run_size - buffer_size;
652                         if (size_read > sections[section]->size - section_offset)
653                             size_read = sections[section]->size - section_offset;
654
655                         /* KLUDGE!
656                          *
657                          * #¤%#"%¤% we have to figure out the section # from the sorted
658                          * list of pointers to sections to invoke image_read_section()...
659                          */
660                         intptr_t diff = (intptr_t)sections[section] - (intptr_t)image->sections;
661                         int t_section_num = diff / sizeof(struct imageection);
662
663                         LOG_DEBUG("image_read_section: section = %d, t_section_num = %d, section_offset = %d, buffer_size = %d, size_read = %d", 
664                                  (int)section,
665 (int)t_section_num, (int)section_offset, (int)buffer_size, (int)size_read);
666                         if ((retval = image_read_section(image, t_section_num, section_offset,
667                                         size_read, buffer + buffer_size, &size_read)) != ERROR_OK || size_read == 0)
668                         {
669                                 free(buffer);
670                                 goto done;
671                         }
672
673                         /* see if we need to pad the section */
674                         while (padding[section]--)
675                                  (buffer + buffer_size)[size_read++] = 0xff;
676
677                         buffer_size += size_read;
678                         section_offset += size_read;
679
680                         if (section_offset >= sections[section]->size)
681                         {
682                                 section++;
683                                 section_offset = 0;
684                         }
685                 }
686
687                 retval = ERROR_OK;
688
689                 if (unlock)
690                 {
691                         retval = flash_unlock_address_range(target, run_address, run_size);
692                 }
693                 if (retval == ERROR_OK)
694                 {
695                         if (erase)
696                         {
697                                 /* calculate and erase sectors */
698                                 retval = flash_erase_address_range(target,
699                                                 true, run_address, run_size);
700                         }
701                 }
702
703                 if (retval == ERROR_OK)
704                 {
705                         /* write flash sectors */
706                         retval = flash_driver_write(c, buffer, run_address - c->base, run_size);
707                 }
708
709                 free(buffer);
710
711                 if (retval != ERROR_OK)
712                 {
713                         /* abort operation */
714                         goto done;
715                 }
716
717                 if (written != NULL)
718                         *written += run_size; /* add run size to total written counter */
719         }
720
721
722 done:
723         free(sections);
724         free(padding);
725
726         return retval;
727 }
728
729 int flash_write(struct target *target, struct image *image,
730                 uint32_t *written, int erase)
731 {
732         return flash_write_unlock(target, image, written, erase, false);
733 }