flash/nor: implement flash bank deallocation on OpenOCD exit
[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, see <http://www.gnu.org/licenses/>. *
20  ***************************************************************************/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 #include <flash/common.h>
26 #include <flash/nor/core.h>
27 #include <flash/nor/imp.h>
28 #include <target/image.h>
29
30 /**
31  * @file
32  * Upper level of NOR flash framework.
33  * The lower level interfaces are to drivers.  These upper level ones
34  * primarily support access from Tcl scripts or from GDB.
35  */
36
37 static struct flash_bank *flash_banks;
38
39 int flash_driver_erase(struct flash_bank *bank, int first, int last)
40 {
41         int retval;
42
43         retval = bank->driver->erase(bank, first, last);
44         if (retval != ERROR_OK)
45                 LOG_ERROR("failed erasing sectors %d to %d", first, last);
46
47         return retval;
48 }
49
50 int flash_driver_protect(struct flash_bank *bank, int set, int first, int last)
51 {
52         int retval;
53         int num_blocks;
54
55         if (bank->num_prot_blocks)
56                 num_blocks = bank->num_prot_blocks;
57         else
58                 num_blocks = bank->num_sectors;
59
60
61         /* callers may not supply illegal parameters ... */
62         if (first < 0 || first > last || last >= num_blocks) {
63                 LOG_ERROR("illegal protection block range");
64                 return ERROR_FAIL;
65         }
66
67         /* force "set" to 0/1 */
68         set = !!set;
69
70         /* DANGER!
71          *
72          * We must not use any cached information about protection state!!!!
73          *
74          * There are a million things that could change the protect state:
75          *
76          * the target could have reset, power cycled, been hot plugged,
77          * the application could have run, etc.
78          *
79          * Drivers only receive valid protection block range.
80          */
81         retval = bank->driver->protect(bank, set, first, last);
82         if (retval != ERROR_OK)
83                 LOG_ERROR("failed setting protection for blocks %d to %d", first, last);
84
85         return retval;
86 }
87
88 int flash_driver_write(struct flash_bank *bank,
89         uint8_t *buffer, uint32_t offset, uint32_t count)
90 {
91         int retval;
92
93         retval = bank->driver->write(bank, buffer, offset, count);
94         if (retval != ERROR_OK) {
95                 LOG_ERROR(
96                         "error writing to flash at address 0x%08" PRIx32 " at offset 0x%8.8" PRIx32,
97                         bank->base,
98                         offset);
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                 LOG_ERROR(
114                         "error reading to flash at address 0x%08" PRIx32 " at offset 0x%8.8" PRIx32,
115                         bank->base,
116                         offset);
117         }
118
119         return retval;
120 }
121
122 int default_flash_read(struct flash_bank *bank,
123         uint8_t *buffer, uint32_t offset, uint32_t count)
124 {
125         return target_read_buffer(bank->target, offset + bank->base, count, buffer);
126 }
127
128 void flash_bank_add(struct flash_bank *bank)
129 {
130         /* put flash bank in linked list */
131         unsigned bank_num = 0;
132         if (flash_banks) {
133                 /* find last flash bank */
134                 struct flash_bank *p = flash_banks;
135                 while (NULL != p->next) {
136                         bank_num += 1;
137                         p = p->next;
138                 }
139                 p->next = bank;
140                 bank_num += 1;
141         } else
142                 flash_banks = bank;
143
144         bank->bank_number = bank_num;
145 }
146
147 struct flash_bank *flash_bank_list(void)
148 {
149         return flash_banks;
150 }
151
152 struct flash_bank *get_flash_bank_by_num_noprobe(int num)
153 {
154         struct flash_bank *p;
155         int i = 0;
156
157         for (p = flash_banks; p; p = p->next) {
158                 if (i++ == num)
159                         return p;
160         }
161         LOG_ERROR("flash bank %d does not exist", num);
162         return NULL;
163 }
164
165 int flash_get_bank_count(void)
166 {
167         struct flash_bank *p;
168         int i = 0;
169         for (p = flash_banks; p; p = p->next)
170                 i++;
171         return i;
172 }
173
174 void default_flash_free_driver_priv(struct flash_bank *bank)
175 {
176         free(bank->driver_priv);
177         bank->driver_priv = NULL;
178 }
179
180 void flash_free_all_banks(void)
181 {
182         struct flash_bank *bank = flash_banks;
183         while (bank) {
184                 struct flash_bank *next = bank->next;
185                 if (bank->driver->free_driver_priv)
186                         bank->driver->free_driver_priv(bank);
187                 else
188                         LOG_WARNING("Flash driver of %s does not support free_driver_priv()", bank->name);
189
190                 free(bank->name);
191                 free(bank->sectors);
192                 free(bank->prot_blocks);
193                 free(bank);
194                 bank = next;
195         }
196         flash_banks = NULL;
197 }
198
199 struct flash_bank *get_flash_bank_by_name_noprobe(const char *name)
200 {
201         unsigned requested = get_flash_name_index(name);
202         unsigned found = 0;
203
204         struct flash_bank *bank;
205         for (bank = flash_banks; NULL != bank; bank = bank->next) {
206                 if (strcmp(bank->name, name) == 0)
207                         return bank;
208                 if (!flash_driver_name_matches(bank->driver->name, name))
209                         continue;
210                 if (++found < requested)
211                         continue;
212                 return bank;
213         }
214         return NULL;
215 }
216
217 int get_flash_bank_by_name(const char *name, struct flash_bank **bank_result)
218 {
219         struct flash_bank *bank;
220         int retval;
221
222         bank = get_flash_bank_by_name_noprobe(name);
223         if (bank != NULL) {
224                 retval = bank->driver->auto_probe(bank);
225
226                 if (retval != ERROR_OK) {
227                         LOG_ERROR("auto_probe failed");
228                         return retval;
229                 }
230         }
231
232         *bank_result = bank;
233         return ERROR_OK;
234 }
235
236 int get_flash_bank_by_num(int num, struct flash_bank **bank)
237 {
238         struct flash_bank *p = get_flash_bank_by_num_noprobe(num);
239         int retval;
240
241         if (p == NULL)
242                 return ERROR_FAIL;
243
244         retval = p->driver->auto_probe(p);
245
246         if (retval != ERROR_OK) {
247                 LOG_ERROR("auto_probe failed");
248                 return retval;
249         }
250         *bank = p;
251         return ERROR_OK;
252 }
253
254 /* lookup flash bank by address, bank not found is success, but
255  * result_bank is set to NULL. */
256 int get_flash_bank_by_addr(struct target *target,
257         uint32_t addr,
258         bool check,
259         struct flash_bank **result_bank)
260 {
261         struct flash_bank *c;
262
263         /* cycle through bank list */
264         for (c = flash_banks; c; c = c->next) {
265                 if (c->target != target)
266                         continue;
267
268                 int retval;
269                 retval = c->driver->auto_probe(c);
270
271                 if (retval != ERROR_OK) {
272                         LOG_ERROR("auto_probe failed");
273                         return retval;
274                 }
275                 /* check whether address belongs to this flash bank */
276                 if ((addr >= c->base) && (addr <= c->base + (c->size - 1))) {
277                         *result_bank = c;
278                         return ERROR_OK;
279                 }
280         }
281         *result_bank = NULL;
282         if (check) {
283                 LOG_ERROR("No flash at address 0x%08" PRIx32, addr);
284                 return ERROR_FAIL;
285         }
286         return ERROR_OK;
287 }
288
289 static int default_flash_mem_blank_check(struct flash_bank *bank)
290 {
291         struct target *target = bank->target;
292         const int buffer_size = 1024;
293         int i;
294         uint32_t nBytes;
295         int retval = ERROR_OK;
296
297         if (bank->target->state != TARGET_HALTED) {
298                 LOG_ERROR("Target not halted");
299                 return ERROR_TARGET_NOT_HALTED;
300         }
301
302         uint8_t *buffer = malloc(buffer_size);
303
304         for (i = 0; i < bank->num_sectors; i++) {
305                 uint32_t j;
306                 bank->sectors[i].is_erased = 1;
307
308                 for (j = 0; j < bank->sectors[i].size; j += buffer_size) {
309                         uint32_t chunk;
310                         chunk = buffer_size;
311                         if (chunk > (j - bank->sectors[i].size))
312                                 chunk = (j - bank->sectors[i].size);
313
314                         retval = target_read_memory(target,
315                                         bank->base + bank->sectors[i].offset + j,
316                                         4,
317                                         chunk/4,
318                                         buffer);
319                         if (retval != ERROR_OK)
320                                 goto done;
321
322                         for (nBytes = 0; nBytes < chunk; nBytes++) {
323                                 if (buffer[nBytes] != bank->erased_value) {
324                                         bank->sectors[i].is_erased = 0;
325                                         break;
326                                 }
327                         }
328                 }
329         }
330
331 done:
332         free(buffer);
333
334         return retval;
335 }
336
337 int default_flash_blank_check(struct flash_bank *bank)
338 {
339         struct target *target = bank->target;
340         int i;
341         int retval;
342         int fast_check = 0;
343         uint32_t blank;
344
345         if (bank->target->state != TARGET_HALTED) {
346                 LOG_ERROR("Target not halted");
347                 return ERROR_TARGET_NOT_HALTED;
348         }
349
350         for (i = 0; i < bank->num_sectors; i++) {
351                 uint32_t address = bank->base + bank->sectors[i].offset;
352                 uint32_t size = bank->sectors[i].size;
353
354                 retval = target_blank_check_memory(target, address, size, &blank, bank->erased_value);
355                 if (retval != ERROR_OK) {
356                         fast_check = 0;
357                         break;
358                 }
359                 if (blank == bank->erased_value)
360                         bank->sectors[i].is_erased = 1;
361                 else
362                         bank->sectors[i].is_erased = 0;
363                 fast_check = 1;
364         }
365
366         if (!fast_check) {
367                 LOG_USER("Running slow fallback erase check - add working memory");
368                 return default_flash_mem_blank_check(bank);
369         }
370
371         return ERROR_OK;
372 }
373
374 /* Manipulate given flash region, selecting the bank according to target
375  * and address.  Maps an address range to a set of sectors, and issues
376  * the callback() on that set ... e.g. to erase or unprotect its members.
377  *
378  * Parameter iterate_protect_blocks switches iteration of protect block
379  * instead of erase sectors. If there is no protect blocks array, sectors
380  * are used in iteration, so compatibility for old flash drivers is retained.
381  *
382  * The "pad_reason" parameter is a kind of boolean:  when it's NULL, the
383  * range must fit those sectors exactly.  This is clearly safe; it can't
384  * erase data which the caller said to leave alone, for example.  If it's
385  * non-NULL, rather than failing, extra data in the first and/or last
386  * sectors will be added to the range, and that reason string is used when
387  * warning about those additions.
388  */
389 static int flash_iterate_address_range_inner(struct target *target,
390         char *pad_reason, uint32_t addr, uint32_t length,
391         bool iterate_protect_blocks,
392         int (*callback)(struct flash_bank *bank, int first, int last))
393 {
394         struct flash_bank *c;
395         struct flash_sector *block_array;
396         uint32_t last_addr = addr + length;     /* first address AFTER end */
397         int first = -1;
398         int last = -1;
399         int i;
400         int num_blocks;
401
402         int retval = get_flash_bank_by_addr(target, addr, true, &c);
403         if (retval != ERROR_OK)
404                 return retval;
405
406         if (c->size == 0 || c->num_sectors == 0) {
407                 LOG_ERROR("Bank is invalid");
408                 return ERROR_FLASH_BANK_INVALID;
409         }
410
411         if (length == 0) {
412                 /* special case, erase whole bank when length is zero */
413                 if (addr != c->base) {
414                         LOG_ERROR("Whole bank access must start at beginning of bank.");
415                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
416                 }
417
418                 return callback(c, 0, c->num_sectors - 1);
419         }
420
421         /* check whether it all fits in this bank */
422         if (addr + length - 1 > c->base + c->size - 1) {
423                 LOG_ERROR("Flash access does not fit into bank.");
424                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
425         }
426
427         if (c->prot_blocks == NULL || c->num_prot_blocks == 0) {
428                 /* flash driver does not define protect blocks, use sectors instead */
429                 iterate_protect_blocks = false;
430         }
431
432         if (iterate_protect_blocks) {
433                 block_array = c->prot_blocks;
434                 num_blocks = c->num_prot_blocks;
435         } else {
436                 block_array = c->sectors;
437                 num_blocks = c->num_sectors;
438         }
439
440         addr -= c->base;
441         last_addr -= c->base;
442
443         for (i = 0; i < num_blocks; i++) {
444                 struct flash_sector *f = &block_array[i];
445                 uint32_t end = f->offset + f->size;
446
447                 /* start only on a sector boundary */
448                 if (first < 0) {
449                         /* scanned past the first sector? */
450                         if (addr < f->offset)
451                                 break;
452
453                         /* is this the first sector? */
454                         if (addr == f->offset)
455                                 first = i;
456
457                         /* Does this need head-padding?  If so, pad and warn;
458                          * or else force an error.
459                          *
460                          * Such padding can make trouble, since *WE* can't
461                          * ever know if that data was in use.  The warning
462                          * should help users sort out messes later.
463                          */
464                         else if (addr < end && pad_reason) {
465                                 /* FIXME say how many bytes (e.g. 80 KB) */
466                                 LOG_WARNING("Adding extra %s range, "
467                                         "%#8.8x to %#8.8x",
468                                         pad_reason,
469                                         (unsigned) f->offset,
470                                         (unsigned) addr - 1);
471                                 first = i;
472                         } else
473                                 continue;
474                 }
475
476                 /* is this (also?) the last sector? */
477                 if (last_addr == end) {
478                         last = i;
479                         break;
480                 }
481
482                 /* Does this need tail-padding?  If so, pad and warn;
483                  * or else force an error.
484                  */
485                 if (last_addr < end && pad_reason) {
486                         /* FIXME say how many bytes (e.g. 80 KB) */
487                         LOG_WARNING("Adding extra %s range, "
488                                 "%#8.8x to %#8.8x",
489                                 pad_reason,
490                                 (unsigned) last_addr,
491                                 (unsigned) end - 1);
492                         last = i;
493                         break;
494                 }
495
496                 /* MUST finish on a sector boundary */
497                 if (last_addr <= f->offset)
498                         break;
499         }
500
501         /* invalid start or end address? */
502         if (first == -1 || last == -1) {
503                 LOG_ERROR("address range 0x%8.8x .. 0x%8.8x "
504                         "is not sector-aligned",
505                         (unsigned) (c->base + addr),
506                         (unsigned) (c->base + last_addr - 1));
507                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
508         }
509
510         /* The NOR driver may trim this range down, based on what
511          * sectors are already erased/unprotected.  GDB currently
512          * blocks such optimizations.
513          */
514         return callback(c, first, last);
515 }
516
517 /* The inner fn only handles a single bank, we could be spanning
518  * multiple chips.
519  */
520 static int flash_iterate_address_range(struct target *target,
521         char *pad_reason, uint32_t addr, uint32_t length,
522         bool iterate_protect_blocks,
523         int (*callback)(struct flash_bank *bank, int first, int last))
524 {
525         struct flash_bank *c;
526         int retval = ERROR_OK;
527
528         /* Danger! zero-length iterations means entire bank! */
529         do {
530                 retval = get_flash_bank_by_addr(target, addr, true, &c);
531                 if (retval != ERROR_OK)
532                         return retval;
533
534                 uint32_t cur_length = length;
535                 /* check whether it all fits in this bank */
536                 if (addr + length - 1 > c->base + c->size - 1) {
537                         LOG_DEBUG("iterating over more than one flash bank.");
538                         cur_length = c->base + c->size - addr;
539                 }
540                 retval = flash_iterate_address_range_inner(target,
541                                 pad_reason, addr, cur_length,
542                                 iterate_protect_blocks,
543                                 callback);
544                 if (retval != ERROR_OK)
545                         break;
546
547                 length -= cur_length;
548                 addr += cur_length;
549         } while (length > 0);
550
551         return retval;
552 }
553
554 int flash_erase_address_range(struct target *target,
555         bool pad, uint32_t addr, uint32_t length)
556 {
557         return flash_iterate_address_range(target, pad ? "erase" : NULL,
558                 addr, length, false, &flash_driver_erase);
559 }
560
561 static int flash_driver_unprotect(struct flash_bank *bank, int first, int last)
562 {
563         return flash_driver_protect(bank, 0, first, last);
564 }
565
566 int flash_unlock_address_range(struct target *target, uint32_t addr, uint32_t length)
567 {
568         /* By default, pad to sector boundaries ... the real issue here
569          * is that our (only) caller *permanently* removes protection,
570          * and doesn't restore it.
571          */
572         return flash_iterate_address_range(target, "unprotect",
573                 addr, length, true, &flash_driver_unprotect);
574 }
575
576 static int compare_section(const void *a, const void *b)
577 {
578         struct imagesection *b1, *b2;
579         b1 = *((struct imagesection **)a);
580         b2 = *((struct imagesection **)b);
581
582         if (b1->base_address == b2->base_address)
583                 return 0;
584         else if (b1->base_address > b2->base_address)
585                 return 1;
586         else
587                 return -1;
588 }
589
590 int flash_write_unlock(struct target *target, struct image *image,
591         uint32_t *written, int erase, bool unlock)
592 {
593         int retval = ERROR_OK;
594
595         int section;
596         uint32_t section_offset;
597         struct flash_bank *c;
598         int *padding;
599
600         section = 0;
601         section_offset = 0;
602
603         if (written)
604                 *written = 0;
605
606         if (erase) {
607                 /* assume all sectors need erasing - stops any problems
608                  * when flash_write is called multiple times */
609
610                 flash_set_dirty();
611         }
612
613         /* allocate padding array */
614         padding = calloc(image->num_sections, sizeof(*padding));
615
616         /* This fn requires all sections to be in ascending order of addresses,
617          * whereas an image can have sections out of order. */
618         struct imagesection **sections = malloc(sizeof(struct imagesection *) *
619                         image->num_sections);
620         int i;
621         for (i = 0; i < image->num_sections; i++)
622                 sections[i] = &image->sections[i];
623
624         qsort(sections, image->num_sections, sizeof(struct imagesection *),
625                 compare_section);
626
627         /* loop until we reach end of the image */
628         while (section < image->num_sections) {
629                 uint32_t buffer_size;
630                 uint8_t *buffer;
631                 int section_last;
632                 target_addr_t run_address = sections[section]->base_address + section_offset;
633                 uint32_t run_size = sections[section]->size - section_offset;
634                 int pad_bytes = 0;
635
636                 if (sections[section]->size ==  0) {
637                         LOG_WARNING("empty section %d", section);
638                         section++;
639                         section_offset = 0;
640                         continue;
641                 }
642
643                 /* find the corresponding flash bank */
644                 retval = get_flash_bank_by_addr(target, run_address, false, &c);
645                 if (retval != ERROR_OK)
646                         goto done;
647                 if (c == NULL) {
648                         LOG_WARNING("no flash bank found for address " TARGET_ADDR_FMT, run_address);
649                         section++;      /* and skip it */
650                         section_offset = 0;
651                         continue;
652                 }
653
654                 /* collect consecutive sections which fall into the same bank */
655                 section_last = section;
656                 padding[section] = 0;
657                 while ((run_address + run_size - 1 < c->base + c->size - 1) &&
658                                 (section_last + 1 < image->num_sections)) {
659                         /* sections are sorted */
660                         assert(sections[section_last + 1]->base_address >= c->base);
661                         if (sections[section_last + 1]->base_address >= (c->base + c->size)) {
662                                 /* Done with this bank */
663                                 break;
664                         }
665
666                         /* FIXME This needlessly touches sectors BETWEEN the
667                          * sections it's writing.  Without auto erase, it just
668                          * writes ones.  That WILL INVALIDATE data in cases
669                          * like Stellaris Tempest chips, corrupting internal
670                          * ECC codes; and at least FreeScale suggests issues
671                          * with that approach (in HC11 documentation).
672                          *
673                          * With auto erase enabled, data in those sectors will
674                          * be needlessly destroyed; and some of the limited
675                          * number of flash erase cycles will be wasted...
676                          *
677                          * In both cases, the extra writes slow things down.
678                          */
679
680                         /* if we have multiple sections within our image,
681                          * flash programming could fail due to alignment issues
682                          * attempt to rebuild a consecutive buffer for the flash loader */
683                         target_addr_t run_next_addr = run_address + run_size;
684                         if (sections[section_last + 1]->base_address < run_next_addr) {
685                                 LOG_ERROR("Section at " TARGET_ADDR_FMT
686                                         " overlaps section ending at " TARGET_ADDR_FMT,
687                                         sections[section_last + 1]->base_address,
688                                         run_next_addr);
689                                 LOG_ERROR("Flash write aborted.");
690                                 retval = ERROR_FAIL;
691                                 goto done;
692                         }
693
694                         pad_bytes = sections[section_last + 1]->base_address - run_next_addr;
695                         padding[section_last] = pad_bytes;
696                         run_size += sections[++section_last]->size;
697                         run_size += pad_bytes;
698
699                         if (pad_bytes > 0)
700                                 LOG_INFO("Padding image section %d with %d bytes",
701                                         section_last-1,
702                                         pad_bytes);
703                 }
704
705                 if (run_address + run_size - 1 > c->base + c->size - 1) {
706                         /* If we have more than one flash chip back to back, then we limit
707                          * the current write operation to the current chip.
708                          */
709                         LOG_DEBUG("Truncate flash run size to the current flash chip.");
710
711                         run_size = c->base + c->size - run_address;
712                         assert(run_size > 0);
713                 }
714
715                 /* If we're applying any sector automagic, then pad this
716                  * (maybe-combined) segment to the end of its last sector.
717                  */
718                 if (unlock || erase) {
719                         int sector;
720                         uint32_t offset_start = run_address - c->base;
721                         uint32_t offset_end = offset_start + run_size;
722                         uint32_t end = offset_end, delta;
723
724                         for (sector = 0; sector < c->num_sectors; sector++) {
725                                 end = c->sectors[sector].offset
726                                         + c->sectors[sector].size;
727                                 if (offset_end <= end)
728                                         break;
729                         }
730
731                         delta = end - offset_end;
732                         padding[section_last] += delta;
733                         run_size += delta;
734                 }
735
736                 /* allocate buffer */
737                 buffer = malloc(run_size);
738                 if (buffer == NULL) {
739                         LOG_ERROR("Out of memory for flash bank buffer");
740                         retval = ERROR_FAIL;
741                         goto done;
742                 }
743                 buffer_size = 0;
744
745                 /* read sections to the buffer */
746                 while (buffer_size < run_size) {
747                         size_t size_read;
748
749                         size_read = run_size - buffer_size;
750                         if (size_read > sections[section]->size - section_offset)
751                                 size_read = sections[section]->size - section_offset;
752
753                         /* KLUDGE!
754                          *
755                          * #¤%#"%¤% we have to figure out the section # from the sorted
756                          * list of pointers to sections to invoke image_read_section()...
757                          */
758                         intptr_t diff = (intptr_t)sections[section] - (intptr_t)image->sections;
759                         int t_section_num = diff / sizeof(struct imagesection);
760
761                         LOG_DEBUG("image_read_section: section = %d, t_section_num = %d, "
762                                         "section_offset = %d, buffer_size = %d, size_read = %d",
763                                 (int)section, (int)t_section_num, (int)section_offset,
764                                 (int)buffer_size, (int)size_read);
765                         retval = image_read_section(image, t_section_num, section_offset,
766                                         size_read, buffer + buffer_size, &size_read);
767                         if (retval != ERROR_OK || size_read == 0) {
768                                 free(buffer);
769                                 goto done;
770                         }
771
772                         /* see if we need to pad the section */
773                         while (padding[section]--)
774                                 (buffer + buffer_size)[size_read++] = c->default_padded_value;
775
776                         buffer_size += size_read;
777                         section_offset += size_read;
778
779                         if (section_offset >= sections[section]->size) {
780                                 section++;
781                                 section_offset = 0;
782                         }
783                 }
784
785                 retval = ERROR_OK;
786
787                 if (unlock)
788                         retval = flash_unlock_address_range(target, run_address, run_size);
789                 if (retval == ERROR_OK) {
790                         if (erase) {
791                                 /* calculate and erase sectors */
792                                 retval = flash_erase_address_range(target,
793                                                 true, run_address, run_size);
794                         }
795                 }
796
797                 if (retval == ERROR_OK) {
798                         /* write flash sectors */
799                         retval = flash_driver_write(c, buffer, run_address - c->base, run_size);
800                 }
801
802                 free(buffer);
803
804                 if (retval != ERROR_OK) {
805                         /* abort operation */
806                         goto done;
807                 }
808
809                 if (written != NULL)
810                         *written += run_size;   /* add run size to total written counter */
811         }
812
813 done:
814         free(sections);
815         free(padding);
816
817         return retval;
818 }
819
820 int flash_write(struct target *target, struct image *image,
821         uint32_t *written, int erase)
822 {
823         return flash_write_unlock(target, image, written, erase, false);
824 }
825
826 struct flash_sector *alloc_block_array(uint32_t offset, uint32_t size, int num_blocks)
827 {
828         int i;
829
830         struct flash_sector *array = calloc(num_blocks, sizeof(struct flash_sector));
831         if (array == NULL)
832                 return NULL;
833
834         for (i = 0; i < num_blocks; i++) {
835                 array[i].offset = offset;
836                 array[i].size = size;
837                 array[i].is_erased = -1;
838                 array[i].is_protected = -1;
839                 offset += size;
840         }
841
842         return array;
843 }