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