6182a5f8207f73cd3e64754a761e846cc3a1579a
[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  *   Copyright (C) 2017-2018 Tomas Vanek <vanekt@fbl.cz>                   *
8  *                                                                         *
9  *   This program is free software; you can redistribute it and/or modify  *
10  *   it under the terms of the GNU General Public License as published by  *
11  *   the Free Software Foundation; either version 2 of the License, or     *
12  *   (at your option) any later version.                                   *
13  *                                                                         *
14  *   This program is distributed in the hope that it will be useful,       *
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
17  *   GNU General Public License for more details.                          *
18  *                                                                         *
19  *   You should have received a copy of the GNU General Public License     *
20  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
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  * @file
33  * Upper level of NOR flash framework.
34  * The lower level interfaces are to drivers.  These upper level ones
35  * primarily support access from Tcl scripts or from GDB.
36  */
37
38 static struct flash_bank *flash_banks;
39
40 int flash_driver_erase(struct flash_bank *bank, unsigned int first,
41                 unsigned int last)
42 {
43         int retval;
44
45         retval = bank->driver->erase(bank, first, last);
46         if (retval != ERROR_OK)
47                 LOG_ERROR("failed erasing sectors %u to %u", first, last);
48
49         return retval;
50 }
51
52 int flash_driver_protect(struct flash_bank *bank, int set, unsigned int first,
53                 unsigned int last)
54 {
55         int retval;
56         unsigned int num_blocks;
57
58         if (bank->num_prot_blocks)
59                 num_blocks = bank->num_prot_blocks;
60         else
61                 num_blocks = bank->num_sectors;
62
63
64         /* callers may not supply illegal parameters ... */
65         if (first > last || last >= num_blocks) {
66                 LOG_ERROR("illegal protection block range");
67                 return ERROR_FAIL;
68         }
69
70         /* force "set" to 0/1 */
71         set = !!set;
72
73         if (bank->driver->protect == NULL) {
74                 LOG_ERROR("Flash protection is not supported.");
75                 return ERROR_FLASH_OPER_UNSUPPORTED;
76         }
77
78         /* DANGER!
79          *
80          * We must not use any cached information about protection state!!!!
81          *
82          * There are a million things that could change the protect state:
83          *
84          * the target could have reset, power cycled, been hot plugged,
85          * the application could have run, etc.
86          *
87          * Drivers only receive valid protection block range.
88          */
89         retval = bank->driver->protect(bank, set, first, last);
90         if (retval != ERROR_OK)
91                 LOG_ERROR("failed setting protection for blocks %u to %u", first, last);
92
93         return retval;
94 }
95
96 int flash_driver_write(struct flash_bank *bank,
97         uint8_t *buffer, uint32_t offset, uint32_t count)
98 {
99         int retval;
100
101         retval = bank->driver->write(bank, buffer, offset, count);
102         if (retval != ERROR_OK) {
103                 LOG_ERROR(
104                         "error writing to flash at address " TARGET_ADDR_FMT
105                         " at offset 0x%8.8" PRIx32,
106                         bank->base,
107                         offset);
108         }
109
110         return retval;
111 }
112
113 int flash_driver_read(struct flash_bank *bank,
114         uint8_t *buffer, uint32_t offset, uint32_t count)
115 {
116         int retval;
117
118         LOG_DEBUG("call flash_driver_read()");
119
120         retval = bank->driver->read(bank, buffer, offset, count);
121         if (retval != ERROR_OK) {
122                 LOG_ERROR(
123                         "error reading to flash at address " TARGET_ADDR_FMT
124                         " at offset 0x%8.8" PRIx32,
125                         bank->base,
126                         offset);
127         }
128
129         return retval;
130 }
131
132 int default_flash_read(struct flash_bank *bank,
133         uint8_t *buffer, uint32_t offset, uint32_t count)
134 {
135         return target_read_buffer(bank->target, offset + bank->base, count, buffer);
136 }
137
138 void flash_bank_add(struct flash_bank *bank)
139 {
140         /* put flash bank in linked list */
141         unsigned bank_num = 0;
142         if (flash_banks) {
143                 /* find last flash bank */
144                 struct flash_bank *p = flash_banks;
145                 while (NULL != p->next) {
146                         bank_num += 1;
147                         p = p->next;
148                 }
149                 p->next = bank;
150                 bank_num += 1;
151         } else
152                 flash_banks = bank;
153
154         bank->bank_number = bank_num;
155 }
156
157 struct flash_bank *flash_bank_list(void)
158 {
159         return flash_banks;
160 }
161
162 struct flash_bank *get_flash_bank_by_num_noprobe(unsigned int num)
163 {
164         struct flash_bank *p;
165         unsigned int i = 0;
166
167         for (p = flash_banks; p; p = p->next) {
168                 if (i++ == num)
169                         return p;
170         }
171         LOG_ERROR("flash bank %d does not exist", num);
172         return NULL;
173 }
174
175 unsigned int flash_get_bank_count(void)
176 {
177         struct flash_bank *p;
178         unsigned int i = 0;
179         for (p = flash_banks; p; p = p->next)
180                 i++;
181         return i;
182 }
183
184 void default_flash_free_driver_priv(struct flash_bank *bank)
185 {
186         free(bank->driver_priv);
187         bank->driver_priv = NULL;
188 }
189
190 void flash_free_all_banks(void)
191 {
192         struct flash_bank *bank = flash_banks;
193         while (bank) {
194                 struct flash_bank *next = bank->next;
195                 if (bank->driver->free_driver_priv)
196                         bank->driver->free_driver_priv(bank);
197                 else
198                         LOG_WARNING("Flash driver of %s does not support free_driver_priv()", bank->name);
199
200                 /* For 'virtual' flash driver bank->sectors and bank->prot_blocks pointers are copied from
201                  * master flash_bank structure. They point to memory locations allocated by master flash driver
202                  * so master driver is responsible for releasing them.
203                  * Avoid UB caused by double-free memory corruption if flash bank is 'virtual'. */
204
205                 if (strcmp(bank->driver->name, "virtual") != 0) {
206                         free(bank->sectors);
207                         free(bank->prot_blocks);
208                 }
209
210                 free(bank->name);
211                 free(bank);
212                 bank = next;
213         }
214         flash_banks = NULL;
215 }
216
217 struct flash_bank *get_flash_bank_by_name_noprobe(const char *name)
218 {
219         unsigned requested = get_flash_name_index(name);
220         unsigned found = 0;
221
222         struct flash_bank *bank;
223         for (bank = flash_banks; NULL != bank; bank = bank->next) {
224                 if (strcmp(bank->name, name) == 0)
225                         return bank;
226                 if (!flash_driver_name_matches(bank->driver->name, name))
227                         continue;
228                 if (++found < requested)
229                         continue;
230                 return bank;
231         }
232         return NULL;
233 }
234
235 int get_flash_bank_by_name(const char *name, struct flash_bank **bank_result)
236 {
237         struct flash_bank *bank;
238         int retval;
239
240         bank = get_flash_bank_by_name_noprobe(name);
241         if (bank != NULL) {
242                 retval = bank->driver->auto_probe(bank);
243
244                 if (retval != ERROR_OK) {
245                         LOG_ERROR("auto_probe failed");
246                         return retval;
247                 }
248         }
249
250         *bank_result = bank;
251         return ERROR_OK;
252 }
253
254 int get_flash_bank_by_num(unsigned int num, struct flash_bank **bank)
255 {
256         struct flash_bank *p = get_flash_bank_by_num_noprobe(num);
257         int retval;
258
259         if (p == NULL)
260                 return ERROR_FAIL;
261
262         retval = p->driver->auto_probe(p);
263
264         if (retval != ERROR_OK) {
265                 LOG_ERROR("auto_probe failed");
266                 return retval;
267         }
268         *bank = p;
269         return ERROR_OK;
270 }
271
272 /* lookup flash bank by address, bank not found is success, but
273  * result_bank is set to NULL. */
274 int get_flash_bank_by_addr(struct target *target,
275         target_addr_t addr,
276         bool check,
277         struct flash_bank **result_bank)
278 {
279         struct flash_bank *c;
280
281         /* cycle through bank list */
282         for (c = flash_banks; c; c = c->next) {
283                 if (c->target != target)
284                         continue;
285
286                 int retval;
287                 retval = c->driver->auto_probe(c);
288
289                 if (retval != ERROR_OK) {
290                         LOG_ERROR("auto_probe failed");
291                         return retval;
292                 }
293                 /* check whether address belongs to this flash bank */
294                 if ((addr >= c->base) && (addr <= c->base + (c->size - 1))) {
295                         *result_bank = c;
296                         return ERROR_OK;
297                 }
298         }
299         *result_bank = NULL;
300         if (check) {
301                 LOG_ERROR("No flash at address " TARGET_ADDR_FMT, addr);
302                 return ERROR_FAIL;
303         }
304         return ERROR_OK;
305 }
306
307 static int default_flash_mem_blank_check(struct flash_bank *bank)
308 {
309         struct target *target = bank->target;
310         const int buffer_size = 1024;
311         uint32_t nBytes;
312         int retval = ERROR_OK;
313
314         if (bank->target->state != TARGET_HALTED) {
315                 LOG_ERROR("Target not halted");
316                 return ERROR_TARGET_NOT_HALTED;
317         }
318
319         uint8_t *buffer = malloc(buffer_size);
320
321         for (unsigned int i = 0; i < bank->num_sectors; i++) {
322                 uint32_t j;
323                 bank->sectors[i].is_erased = 1;
324
325                 for (j = 0; j < bank->sectors[i].size; j += buffer_size) {
326                         uint32_t chunk;
327                         chunk = buffer_size;
328                         if (chunk > (bank->sectors[i].size - j))
329                                 chunk = (bank->sectors[i].size - j);
330
331                         retval = target_read_memory(target,
332                                         bank->base + bank->sectors[i].offset + j,
333                                         4,
334                                         chunk/4,
335                                         buffer);
336                         if (retval != ERROR_OK)
337                                 goto done;
338
339                         for (nBytes = 0; nBytes < chunk; nBytes++) {
340                                 if (buffer[nBytes] != bank->erased_value) {
341                                         bank->sectors[i].is_erased = 0;
342                                         break;
343                                 }
344                         }
345                 }
346         }
347
348 done:
349         free(buffer);
350
351         return retval;
352 }
353
354 int default_flash_blank_check(struct flash_bank *bank)
355 {
356         struct target *target = bank->target;
357         int retval;
358
359         if (bank->target->state != TARGET_HALTED) {
360                 LOG_ERROR("Target not halted");
361                 return ERROR_TARGET_NOT_HALTED;
362         }
363
364         struct target_memory_check_block *block_array;
365         block_array = malloc(bank->num_sectors * sizeof(struct target_memory_check_block));
366         if (block_array == NULL)
367                 return default_flash_mem_blank_check(bank);
368
369         for (unsigned int i = 0; i < bank->num_sectors; i++) {
370                 block_array[i].address = bank->base + bank->sectors[i].offset;
371                 block_array[i].size = bank->sectors[i].size;
372                 block_array[i].result = UINT32_MAX; /* erase state unknown */
373         }
374
375         bool fast_check = true;
376         for (unsigned int i = 0; i < bank->num_sectors; ) {
377                 retval = target_blank_check_memory(target,
378                                 block_array + i, bank->num_sectors - i,
379                                 bank->erased_value);
380                 if (retval < 1) {
381                         /* Run slow fallback if the first run gives no result
382                          * otherwise use possibly incomplete results */
383                         if (i == 0)
384                                 fast_check = false;
385                         break;
386                 }
387                 i += retval; /* add number of blocks done this round */
388         }
389
390         if (fast_check) {
391                 for (unsigned int i = 0; i < bank->num_sectors; i++)
392                         bank->sectors[i].is_erased = block_array[i].result;
393                 retval = ERROR_OK;
394         } else {
395                 LOG_USER("Running slow fallback erase check - add working memory");
396                 retval = default_flash_mem_blank_check(bank);
397         }
398         free(block_array);
399
400         return retval;
401 }
402
403 /* Manipulate given flash region, selecting the bank according to target
404  * and address.  Maps an address range to a set of sectors, and issues
405  * the callback() on that set ... e.g. to erase or unprotect its members.
406  *
407  * Parameter iterate_protect_blocks switches iteration of protect block
408  * instead of erase sectors. If there is no protect blocks array, sectors
409  * are used in iteration, so compatibility for old flash drivers is retained.
410  *
411  * The "pad_reason" parameter is a kind of boolean:  when it's NULL, the
412  * range must fit those sectors exactly.  This is clearly safe; it can't
413  * erase data which the caller said to leave alone, for example.  If it's
414  * non-NULL, rather than failing, extra data in the first and/or last
415  * sectors will be added to the range, and that reason string is used when
416  * warning about those additions.
417  */
418 static int flash_iterate_address_range_inner(struct target *target,
419         char *pad_reason, target_addr_t addr, uint32_t length,
420         bool iterate_protect_blocks,
421         int (*callback)(struct flash_bank *bank, unsigned int first,
422                 unsigned int last))
423 {
424         struct flash_bank *c;
425         struct flash_sector *block_array;
426         target_addr_t last_addr = addr + length - 1;    /* the last address of range */
427         int first = -1;
428         int last = -1;
429         int i;
430         int num_blocks;
431
432         int retval = get_flash_bank_by_addr(target, addr, true, &c);
433         if (retval != ERROR_OK)
434                 return retval;
435
436         if (c->size == 0 || c->num_sectors == 0) {
437                 LOG_ERROR("Bank is invalid");
438                 return ERROR_FLASH_BANK_INVALID;
439         }
440
441         if (length == 0) {
442                 /* special case, erase whole bank when length is zero */
443                 if (addr != c->base) {
444                         LOG_ERROR("Whole bank access must start at beginning of bank.");
445                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
446                 }
447
448                 return callback(c, 0, c->num_sectors - 1);
449         }
450
451         /* check whether it all fits in this bank */
452         if (last_addr > c->base + c->size - 1) {
453                 LOG_ERROR("Flash access does not fit into bank.");
454                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
455         }
456
457         if (c->prot_blocks == NULL || c->num_prot_blocks == 0) {
458                 /* flash driver does not define protect blocks, use sectors instead */
459                 iterate_protect_blocks = false;
460         }
461
462         if (iterate_protect_blocks) {
463                 block_array = c->prot_blocks;
464                 num_blocks = c->num_prot_blocks;
465         } else {
466                 block_array = c->sectors;
467                 num_blocks = c->num_sectors;
468         }
469
470         for (i = 0; i < num_blocks; i++) {
471                 struct flash_sector *f = &block_array[i];
472                 target_addr_t sector_addr = c->base + f->offset;
473                 target_addr_t sector_last_addr = sector_addr + f->size - 1;
474
475                 /* start only on a sector boundary */
476                 if (first < 0) {
477                         /* scanned past the first sector? */
478                         if (addr < sector_addr)
479                                 break;
480
481                         /* is this the first sector? */
482                         if (addr == sector_addr)
483                                 first = i;
484
485                         /* Does this need head-padding?  If so, pad and warn;
486                          * or else force an error.
487                          *
488                          * Such padding can make trouble, since *WE* can't
489                          * ever know if that data was in use.  The warning
490                          * should help users sort out messes later.
491                          */
492                         else if (addr <= sector_last_addr && pad_reason) {
493                                 /* FIXME say how many bytes (e.g. 80 KB) */
494                                 LOG_WARNING("Adding extra %s range, "
495                                         TARGET_ADDR_FMT " .. " TARGET_ADDR_FMT,
496                                         pad_reason,
497                                         sector_addr,
498                                         addr - 1);
499                                 first = i;
500                         } else
501                                 continue;
502                 }
503
504                 /* is this (also?) the last sector? */
505                 if (last_addr == sector_last_addr) {
506                         last = i;
507                         break;
508                 }
509
510                 /* Does this need tail-padding?  If so, pad and warn;
511                  * or else force an error.
512                  */
513                 if (last_addr < sector_last_addr && pad_reason) {
514                         /* FIXME say how many bytes (e.g. 80 KB) */
515                         LOG_WARNING("Adding extra %s range, "
516                                 TARGET_ADDR_FMT " .. " TARGET_ADDR_FMT,
517                                 pad_reason,
518                                 last_addr + 1,
519                                 sector_last_addr);
520                         last = i;
521                         break;
522                 }
523
524                 /* MUST finish on a sector boundary */
525                 if (last_addr < sector_addr)
526                         break;
527         }
528
529         /* invalid start or end address? */
530         if (first == -1 || last == -1) {
531                 LOG_ERROR("address range " TARGET_ADDR_FMT " .. " TARGET_ADDR_FMT
532                         " is not sector-aligned",
533                         addr,
534                         last_addr);
535                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
536         }
537
538         /* The NOR driver may trim this range down, based on what
539          * sectors are already erased/unprotected.  GDB currently
540          * blocks such optimizations.
541          */
542         return callback(c, first, last);
543 }
544
545 /* The inner fn only handles a single bank, we could be spanning
546  * multiple chips.
547  */
548 static int flash_iterate_address_range(struct target *target,
549         char *pad_reason, target_addr_t addr, uint32_t length,
550         bool iterate_protect_blocks,
551         int (*callback)(struct flash_bank *bank, unsigned int first,
552                 unsigned int last))
553 {
554         struct flash_bank *c;
555         int retval = ERROR_OK;
556
557         /* Danger! zero-length iterations means entire bank! */
558         do {
559                 retval = get_flash_bank_by_addr(target, addr, true, &c);
560                 if (retval != ERROR_OK)
561                         return retval;
562
563                 uint32_t cur_length = length;
564                 /* check whether it all fits in this bank */
565                 if (addr + length - 1 > c->base + c->size - 1) {
566                         LOG_DEBUG("iterating over more than one flash bank.");
567                         cur_length = c->base + c->size - addr;
568                 }
569                 retval = flash_iterate_address_range_inner(target,
570                                 pad_reason, addr, cur_length,
571                                 iterate_protect_blocks,
572                                 callback);
573                 if (retval != ERROR_OK)
574                         break;
575
576                 length -= cur_length;
577                 addr += cur_length;
578         } while (length > 0);
579
580         return retval;
581 }
582
583 int flash_erase_address_range(struct target *target,
584         bool pad, target_addr_t addr, uint32_t length)
585 {
586         return flash_iterate_address_range(target, pad ? "erase" : NULL,
587                 addr, length, false, &flash_driver_erase);
588 }
589
590 static int flash_driver_unprotect(struct flash_bank *bank, unsigned int first,
591                 unsigned int last)
592 {
593         return flash_driver_protect(bank, 0, first, last);
594 }
595
596 int flash_unlock_address_range(struct target *target, target_addr_t addr,
597                 uint32_t length)
598 {
599         /* By default, pad to sector boundaries ... the real issue here
600          * is that our (only) caller *permanently* removes protection,
601          * and doesn't restore it.
602          */
603         return flash_iterate_address_range(target, "unprotect",
604                 addr, length, true, &flash_driver_unprotect);
605 }
606
607 static int compare_section(const void *a, const void *b)
608 {
609         struct imagesection *b1, *b2;
610         b1 = *((struct imagesection **)a);
611         b2 = *((struct imagesection **)b);
612
613         if (b1->base_address == b2->base_address)
614                 return 0;
615         else if (b1->base_address > b2->base_address)
616                 return 1;
617         else
618                 return -1;
619 }
620
621 /**
622  * Get aligned start address of a flash write region
623  */
624 target_addr_t flash_write_align_start(struct flash_bank *bank, target_addr_t addr)
625 {
626         if (addr < bank->base || addr >= bank->base + bank->size
627                         || bank->write_start_alignment <= 1)
628                 return addr;
629
630         if (bank->write_start_alignment == FLASH_WRITE_ALIGN_SECTOR) {
631                 uint32_t offset = addr - bank->base;
632                 uint32_t aligned = 0;
633                 for (unsigned int sect = 0; sect < bank->num_sectors; sect++) {
634                         if (bank->sectors[sect].offset > offset)
635                                 break;
636
637                         aligned = bank->sectors[sect].offset;
638                 }
639                 return bank->base + aligned;
640         }
641
642         return addr & ~(bank->write_start_alignment - 1);
643 }
644
645 /**
646  * Get aligned end address of a flash write region
647  */
648 target_addr_t flash_write_align_end(struct flash_bank *bank, target_addr_t addr)
649 {
650         if (addr < bank->base || addr >= bank->base + bank->size
651                         || bank->write_end_alignment <= 1)
652                 return addr;
653
654         if (bank->write_end_alignment == FLASH_WRITE_ALIGN_SECTOR) {
655                 uint32_t offset = addr - bank->base;
656                 uint32_t aligned = 0;
657                 for (unsigned int sect = 0; sect < bank->num_sectors; sect++) {
658                         aligned = bank->sectors[sect].offset + bank->sectors[sect].size - 1;
659                         if (aligned >= offset)
660                                 break;
661                 }
662                 return bank->base + aligned;
663         }
664
665         return addr | (bank->write_end_alignment - 1);
666 }
667
668 /**
669  * Check if gap between sections is bigger than minimum required to discontinue flash write
670  */
671 static bool flash_write_check_gap(struct flash_bank *bank,
672                                 target_addr_t addr1, target_addr_t addr2)
673 {
674         if (bank->minimal_write_gap == FLASH_WRITE_CONTINUOUS
675                         || addr1 < bank->base || addr1 >= bank->base + bank->size
676                         || addr2 < bank->base || addr2 >= bank->base + bank->size)
677                 return false;
678
679         if (bank->minimal_write_gap == FLASH_WRITE_GAP_SECTOR) {
680                 unsigned int sect;
681                 uint32_t offset1 = addr1 - bank->base;
682                 /* find the sector following the one containing addr1 */
683                 for (sect = 0; sect < bank->num_sectors; sect++) {
684                         if (bank->sectors[sect].offset > offset1)
685                                 break;
686                 }
687                 if (sect >= bank->num_sectors)
688                         return false;
689
690                 uint32_t offset2 = addr2 - bank->base;
691                 return bank->sectors[sect].offset + bank->sectors[sect].size <= offset2;
692         }
693
694         target_addr_t aligned1 = flash_write_align_end(bank, addr1);
695         target_addr_t aligned2 = flash_write_align_start(bank, addr2);
696         return aligned1 + bank->minimal_write_gap < aligned2;
697 }
698
699
700 int flash_write_unlock(struct target *target, struct image *image,
701         uint32_t *written, bool erase, bool unlock)
702 {
703         int retval = ERROR_OK;
704
705         unsigned int section;
706         uint32_t section_offset;
707         struct flash_bank *c;
708         int *padding;
709
710         section = 0;
711         section_offset = 0;
712
713         if (written)
714                 *written = 0;
715
716         if (erase) {
717                 /* assume all sectors need erasing - stops any problems
718                  * when flash_write is called multiple times */
719
720                 flash_set_dirty();
721         }
722
723         /* allocate padding array */
724         padding = calloc(image->num_sections, sizeof(*padding));
725
726         /* This fn requires all sections to be in ascending order of addresses,
727          * whereas an image can have sections out of order. */
728         struct imagesection **sections = malloc(sizeof(struct imagesection *) *
729                         image->num_sections);
730
731         for (unsigned int i = 0; i < image->num_sections; i++)
732                 sections[i] = &image->sections[i];
733
734         qsort(sections, image->num_sections, sizeof(struct imagesection *),
735                 compare_section);
736
737         /* loop until we reach end of the image */
738         while (section < image->num_sections) {
739                 uint32_t buffer_idx;
740                 uint8_t *buffer;
741                 unsigned int section_last;
742                 target_addr_t run_address = sections[section]->base_address + section_offset;
743                 uint32_t run_size = sections[section]->size - section_offset;
744                 int pad_bytes = 0;
745
746                 if (sections[section]->size ==  0) {
747                         LOG_WARNING("empty section %d", section);
748                         section++;
749                         section_offset = 0;
750                         continue;
751                 }
752
753                 /* find the corresponding flash bank */
754                 retval = get_flash_bank_by_addr(target, run_address, false, &c);
755                 if (retval != ERROR_OK)
756                         goto done;
757                 if (c == NULL) {
758                         LOG_WARNING("no flash bank found for address " TARGET_ADDR_FMT, run_address);
759                         section++;      /* and skip it */
760                         section_offset = 0;
761                         continue;
762                 }
763
764                 /* collect consecutive sections which fall into the same bank */
765                 section_last = section;
766                 padding[section] = 0;
767                 while ((run_address + run_size - 1 < c->base + c->size - 1) &&
768                                 (section_last + 1 < image->num_sections)) {
769                         /* sections are sorted */
770                         assert(sections[section_last + 1]->base_address >= c->base);
771                         if (sections[section_last + 1]->base_address >= (c->base + c->size)) {
772                                 /* Done with this bank */
773                                 break;
774                         }
775
776                         /* if we have multiple sections within our image,
777                          * flash programming could fail due to alignment issues
778                          * attempt to rebuild a consecutive buffer for the flash loader */
779                         target_addr_t run_next_addr = run_address + run_size;
780                         target_addr_t next_section_base = sections[section_last + 1]->base_address;
781                         if (next_section_base < run_next_addr) {
782                                 LOG_ERROR("Section at " TARGET_ADDR_FMT
783                                         " overlaps section ending at " TARGET_ADDR_FMT,
784                                         next_section_base, run_next_addr);
785                                 LOG_ERROR("Flash write aborted.");
786                                 retval = ERROR_FAIL;
787                                 goto done;
788                         }
789
790                         pad_bytes = next_section_base - run_next_addr;
791                         if (pad_bytes) {
792                                 if (flash_write_check_gap(c, run_next_addr - 1, next_section_base)) {
793                                         LOG_INFO("Flash write discontinued at " TARGET_ADDR_FMT
794                                                 ", next section at " TARGET_ADDR_FMT,
795                                                 run_next_addr, next_section_base);
796                                         break;
797                                 }
798                         }
799                         if (pad_bytes > 0)
800                                 LOG_INFO("Padding image section %d at " TARGET_ADDR_FMT
801                                         " with %d bytes",
802                                         section_last, run_next_addr, pad_bytes);
803
804                         padding[section_last] = pad_bytes;
805                         run_size += pad_bytes;
806                         run_size += sections[++section_last]->size;
807                 }
808
809                 if (run_address + run_size - 1 > c->base + c->size - 1) {
810                         /* If we have more than one flash chip back to back, then we limit
811                          * the current write operation to the current chip.
812                          */
813                         LOG_DEBUG("Truncate flash run size to the current flash chip.");
814
815                         run_size = c->base + c->size - run_address;
816                         assert(run_size > 0);
817                 }
818
819                 uint32_t padding_at_start = 0;
820                 if (c->write_start_alignment || c->write_end_alignment) {
821                         /* align write region according to bank requirements */
822                         target_addr_t aligned_start = flash_write_align_start(c, run_address);
823                         padding_at_start = run_address - aligned_start;
824                         if (padding_at_start > 0) {
825                                 LOG_WARNING("Section start address " TARGET_ADDR_FMT
826                                         " breaks the required alignment of flash bank %s",
827                                         run_address, c->name);
828                                 LOG_WARNING("Padding %" PRIu32 " bytes from " TARGET_ADDR_FMT,
829                                         padding_at_start, aligned_start);
830
831                                 run_address -= padding_at_start;
832                                 run_size += padding_at_start;
833                         }
834
835                         target_addr_t run_end = run_address + run_size - 1;
836                         target_addr_t aligned_end = flash_write_align_end(c, run_end);
837                         pad_bytes = aligned_end - run_end;
838                         if (pad_bytes > 0) {
839                                 LOG_INFO("Padding image section %d at " TARGET_ADDR_FMT
840                                         " with %d bytes (bank write end alignment)",
841                                         section_last, run_end + 1, pad_bytes);
842
843                                 padding[section_last] += pad_bytes;
844                                 run_size += pad_bytes;
845                         }
846
847                 } else if (unlock || erase) {
848                         /* If we're applying any sector automagic, then pad this
849                          * (maybe-combined) segment to the end of its last sector.
850                          */
851                         uint32_t offset_start = run_address - c->base;
852                         uint32_t offset_end = offset_start + run_size;
853                         uint32_t end = offset_end, delta;
854
855                         for (unsigned int sector = 0; sector < c->num_sectors; sector++) {
856                                 end = c->sectors[sector].offset
857                                         + c->sectors[sector].size;
858                                 if (offset_end <= end)
859                                         break;
860                         }
861
862                         delta = end - offset_end;
863                         padding[section_last] += delta;
864                         run_size += delta;
865                 }
866
867                 /* allocate buffer */
868                 buffer = malloc(run_size);
869                 if (buffer == NULL) {
870                         LOG_ERROR("Out of memory for flash bank buffer");
871                         retval = ERROR_FAIL;
872                         goto done;
873                 }
874
875                 if (padding_at_start)
876                         memset(buffer, c->default_padded_value, padding_at_start);
877
878                 buffer_idx = padding_at_start;
879
880                 /* read sections to the buffer */
881                 while (buffer_idx < run_size) {
882                         size_t size_read;
883
884                         size_read = run_size - buffer_idx;
885                         if (size_read > sections[section]->size - section_offset)
886                                 size_read = sections[section]->size - section_offset;
887
888                         /* KLUDGE!
889                          *
890                          * #¤%#"%¤% we have to figure out the section # from the sorted
891                          * list of pointers to sections to invoke image_read_section()...
892                          */
893                         intptr_t diff = (intptr_t)sections[section] - (intptr_t)image->sections;
894                         int t_section_num = diff / sizeof(struct imagesection);
895
896                         LOG_DEBUG("image_read_section: section = %d, t_section_num = %d, "
897                                         "section_offset = %"PRIu32", buffer_idx = %"PRIu32", size_read = %zu",
898                                 section, t_section_num, section_offset,
899                                 buffer_idx, size_read);
900                         retval = image_read_section(image, t_section_num, section_offset,
901                                         size_read, buffer + buffer_idx, &size_read);
902                         if (retval != ERROR_OK || size_read == 0) {
903                                 free(buffer);
904                                 goto done;
905                         }
906
907                         buffer_idx += size_read;
908                         section_offset += size_read;
909
910                         /* see if we need to pad the section */
911                         if (padding[section]) {
912                                 memset(buffer + buffer_idx, c->default_padded_value, padding[section]);
913                                 buffer_idx += padding[section];
914                         }
915
916                         if (section_offset >= sections[section]->size) {
917                                 section++;
918                                 section_offset = 0;
919                         }
920                 }
921
922                 retval = ERROR_OK;
923
924                 if (unlock)
925                         retval = flash_unlock_address_range(target, run_address, run_size);
926                 if (retval == ERROR_OK) {
927                         if (erase) {
928                                 /* calculate and erase sectors */
929                                 retval = flash_erase_address_range(target,
930                                                 true, run_address, run_size);
931                         }
932                 }
933
934                 if (retval == ERROR_OK) {
935                         /* write flash sectors */
936                         retval = flash_driver_write(c, buffer, run_address - c->base, run_size);
937                 }
938
939                 free(buffer);
940
941                 if (retval != ERROR_OK) {
942                         /* abort operation */
943                         goto done;
944                 }
945
946                 if (written != NULL)
947                         *written += run_size;   /* add run size to total written counter */
948         }
949
950 done:
951         free(sections);
952         free(padding);
953
954         return retval;
955 }
956
957 int flash_write(struct target *target, struct image *image,
958         uint32_t *written, bool erase)
959 {
960         return flash_write_unlock(target, image, written, erase, false);
961 }
962
963 struct flash_sector *alloc_block_array(uint32_t offset, uint32_t size,
964                 unsigned int num_blocks)
965 {
966         struct flash_sector *array = calloc(num_blocks, sizeof(struct flash_sector));
967         if (array == NULL)
968                 return NULL;
969
970         for (unsigned int i = 0; i < num_blocks; i++) {
971                 array[i].offset = offset;
972                 array[i].size = size;
973                 array[i].is_erased = -1;
974                 array[i].is_protected = -1;
975                 offset += size;
976         }
977
978         return array;
979 }