flash/nor/core: adjust flash_iterate_address_range_inner() for 64-bit
[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, int first, int last)
41 {
42         int retval;
43
44         retval = bank->driver->erase(bank, first, last);
45         if (retval != ERROR_OK)
46                 LOG_ERROR("failed erasing sectors %d to %d", first, last);
47
48         return retval;
49 }
50
51 int flash_driver_protect(struct flash_bank *bank, int set, int first, int last)
52 {
53         int retval;
54         int num_blocks;
55
56         if (bank->num_prot_blocks)
57                 num_blocks = bank->num_prot_blocks;
58         else
59                 num_blocks = bank->num_sectors;
60
61
62         /* callers may not supply illegal parameters ... */
63         if (first < 0 || first > last || last >= num_blocks) {
64                 LOG_ERROR("illegal protection block range");
65                 return ERROR_FAIL;
66         }
67
68         /* force "set" to 0/1 */
69         set = !!set;
70
71         if (bank->driver->protect == NULL) {
72                 LOG_ERROR("Flash protection is not supported.");
73                 return ERROR_FLASH_OPER_UNSUPPORTED;
74         }
75
76         /* DANGER!
77          *
78          * We must not use any cached information about protection state!!!!
79          *
80          * There are a million things that could change the protect state:
81          *
82          * the target could have reset, power cycled, been hot plugged,
83          * the application could have run, etc.
84          *
85          * Drivers only receive valid protection block range.
86          */
87         retval = bank->driver->protect(bank, set, first, last);
88         if (retval != ERROR_OK)
89                 LOG_ERROR("failed setting protection for blocks %d to %d", first, last);
90
91         return retval;
92 }
93
94 int flash_driver_write(struct flash_bank *bank,
95         uint8_t *buffer, uint32_t offset, uint32_t count)
96 {
97         int retval;
98
99         retval = bank->driver->write(bank, buffer, offset, count);
100         if (retval != ERROR_OK) {
101                 LOG_ERROR(
102                         "error writing to flash at address " TARGET_ADDR_FMT
103                         " at offset 0x%8.8" PRIx32,
104                         bank->base,
105                         offset);
106         }
107
108         return retval;
109 }
110
111 int flash_driver_read(struct flash_bank *bank,
112         uint8_t *buffer, uint32_t offset, uint32_t count)
113 {
114         int retval;
115
116         LOG_DEBUG("call flash_driver_read()");
117
118         retval = bank->driver->read(bank, buffer, offset, count);
119         if (retval != ERROR_OK) {
120                 LOG_ERROR(
121                         "error reading to flash at address " TARGET_ADDR_FMT
122                         " at offset 0x%8.8" PRIx32,
123                         bank->base,
124                         offset);
125         }
126
127         return retval;
128 }
129
130 int default_flash_read(struct flash_bank *bank,
131         uint8_t *buffer, uint32_t offset, uint32_t count)
132 {
133         return target_read_buffer(bank->target, offset + bank->base, count, buffer);
134 }
135
136 void flash_bank_add(struct flash_bank *bank)
137 {
138         /* put flash bank in linked list */
139         unsigned bank_num = 0;
140         if (flash_banks) {
141                 /* find last flash bank */
142                 struct flash_bank *p = flash_banks;
143                 while (NULL != p->next) {
144                         bank_num += 1;
145                         p = p->next;
146                 }
147                 p->next = bank;
148                 bank_num += 1;
149         } else
150                 flash_banks = bank;
151
152         bank->bank_number = bank_num;
153 }
154
155 struct flash_bank *flash_bank_list(void)
156 {
157         return flash_banks;
158 }
159
160 struct flash_bank *get_flash_bank_by_num_noprobe(int num)
161 {
162         struct flash_bank *p;
163         int i = 0;
164
165         for (p = flash_banks; p; p = p->next) {
166                 if (i++ == num)
167                         return p;
168         }
169         LOG_ERROR("flash bank %d does not exist", num);
170         return NULL;
171 }
172
173 int flash_get_bank_count(void)
174 {
175         struct flash_bank *p;
176         int i = 0;
177         for (p = flash_banks; p; p = p->next)
178                 i++;
179         return i;
180 }
181
182 void default_flash_free_driver_priv(struct flash_bank *bank)
183 {
184         free(bank->driver_priv);
185         bank->driver_priv = NULL;
186 }
187
188 void flash_free_all_banks(void)
189 {
190         struct flash_bank *bank = flash_banks;
191         while (bank) {
192                 struct flash_bank *next = bank->next;
193                 if (bank->driver->free_driver_priv)
194                         bank->driver->free_driver_priv(bank);
195                 else
196                         LOG_WARNING("Flash driver of %s does not support free_driver_priv()", bank->name);
197
198                 /* For 'virtual' flash driver bank->sectors and bank->prot_blocks pointers are copied from
199                  * master flash_bank structure. They point to memory locations allocated by master flash driver
200                  * so master driver is responsible for releasing them.
201                  * Avoid UB caused by double-free memory corruption if flash bank is 'virtual'. */
202
203                 if (strcmp(bank->driver->name, "virtual") != 0) {
204                         free(bank->sectors);
205                         free(bank->prot_blocks);
206                 }
207
208                 free(bank->name);
209                 free(bank);
210                 bank = next;
211         }
212         flash_banks = NULL;
213 }
214
215 struct flash_bank *get_flash_bank_by_name_noprobe(const char *name)
216 {
217         unsigned requested = get_flash_name_index(name);
218         unsigned found = 0;
219
220         struct flash_bank *bank;
221         for (bank = flash_banks; NULL != bank; bank = bank->next) {
222                 if (strcmp(bank->name, name) == 0)
223                         return bank;
224                 if (!flash_driver_name_matches(bank->driver->name, name))
225                         continue;
226                 if (++found < requested)
227                         continue;
228                 return bank;
229         }
230         return NULL;
231 }
232
233 int get_flash_bank_by_name(const char *name, struct flash_bank **bank_result)
234 {
235         struct flash_bank *bank;
236         int retval;
237
238         bank = get_flash_bank_by_name_noprobe(name);
239         if (bank != NULL) {
240                 retval = bank->driver->auto_probe(bank);
241
242                 if (retval != ERROR_OK) {
243                         LOG_ERROR("auto_probe failed");
244                         return retval;
245                 }
246         }
247
248         *bank_result = bank;
249         return ERROR_OK;
250 }
251
252 int get_flash_bank_by_num(int num, struct flash_bank **bank)
253 {
254         struct flash_bank *p = get_flash_bank_by_num_noprobe(num);
255         int retval;
256
257         if (p == NULL)
258                 return ERROR_FAIL;
259
260         retval = p->driver->auto_probe(p);
261
262         if (retval != ERROR_OK) {
263                 LOG_ERROR("auto_probe failed");
264                 return retval;
265         }
266         *bank = p;
267         return ERROR_OK;
268 }
269
270 /* lookup flash bank by address, bank not found is success, but
271  * result_bank is set to NULL. */
272 int get_flash_bank_by_addr(struct target *target,
273         target_addr_t addr,
274         bool check,
275         struct flash_bank **result_bank)
276 {
277         struct flash_bank *c;
278
279         /* cycle through bank list */
280         for (c = flash_banks; c; c = c->next) {
281                 if (c->target != target)
282                         continue;
283
284                 int retval;
285                 retval = c->driver->auto_probe(c);
286
287                 if (retval != ERROR_OK) {
288                         LOG_ERROR("auto_probe failed");
289                         return retval;
290                 }
291                 /* check whether address belongs to this flash bank */
292                 if ((addr >= c->base) && (addr <= c->base + (c->size - 1))) {
293                         *result_bank = c;
294                         return ERROR_OK;
295                 }
296         }
297         *result_bank = NULL;
298         if (check) {
299                 LOG_ERROR("No flash at address " TARGET_ADDR_FMT, addr);
300                 return ERROR_FAIL;
301         }
302         return ERROR_OK;
303 }
304
305 static int default_flash_mem_blank_check(struct flash_bank *bank)
306 {
307         struct target *target = bank->target;
308         const int buffer_size = 1024;
309         int i;
310         uint32_t nBytes;
311         int retval = ERROR_OK;
312
313         if (bank->target->state != TARGET_HALTED) {
314                 LOG_ERROR("Target not halted");
315                 return ERROR_TARGET_NOT_HALTED;
316         }
317
318         uint8_t *buffer = malloc(buffer_size);
319
320         for (i = 0; i < bank->num_sectors; i++) {
321                 uint32_t j;
322                 bank->sectors[i].is_erased = 1;
323
324                 for (j = 0; j < bank->sectors[i].size; j += buffer_size) {
325                         uint32_t chunk;
326                         chunk = buffer_size;
327                         if (chunk > (bank->sectors[i].size - j))
328                                 chunk = (bank->sectors[i].size - j);
329
330                         retval = target_read_memory(target,
331                                         bank->base + bank->sectors[i].offset + j,
332                                         4,
333                                         chunk/4,
334                                         buffer);
335                         if (retval != ERROR_OK)
336                                 goto done;
337
338                         for (nBytes = 0; nBytes < chunk; nBytes++) {
339                                 if (buffer[nBytes] != bank->erased_value) {
340                                         bank->sectors[i].is_erased = 0;
341                                         break;
342                                 }
343                         }
344                 }
345         }
346
347 done:
348         free(buffer);
349
350         return retval;
351 }
352
353 int default_flash_blank_check(struct flash_bank *bank)
354 {
355         struct target *target = bank->target;
356         int i;
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 (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 (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 (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, int first, int last))
422 {
423         struct flash_bank *c;
424         struct flash_sector *block_array;
425         target_addr_t last_addr = addr + length - 1;    /* the last address of range */
426         int first = -1;
427         int last = -1;
428         int i;
429         int num_blocks;
430
431         int retval = get_flash_bank_by_addr(target, addr, true, &c);
432         if (retval != ERROR_OK)
433                 return retval;
434
435         if (c->size == 0 || c->num_sectors == 0) {
436                 LOG_ERROR("Bank is invalid");
437                 return ERROR_FLASH_BANK_INVALID;
438         }
439
440         if (length == 0) {
441                 /* special case, erase whole bank when length is zero */
442                 if (addr != c->base) {
443                         LOG_ERROR("Whole bank access must start at beginning of bank.");
444                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
445                 }
446
447                 return callback(c, 0, c->num_sectors - 1);
448         }
449
450         /* check whether it all fits in this bank */
451         if (last_addr > c->base + c->size - 1) {
452                 LOG_ERROR("Flash access does not fit into bank.");
453                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
454         }
455
456         if (c->prot_blocks == NULL || c->num_prot_blocks == 0) {
457                 /* flash driver does not define protect blocks, use sectors instead */
458                 iterate_protect_blocks = false;
459         }
460
461         if (iterate_protect_blocks) {
462                 block_array = c->prot_blocks;
463                 num_blocks = c->num_prot_blocks;
464         } else {
465                 block_array = c->sectors;
466                 num_blocks = c->num_sectors;
467         }
468
469         for (i = 0; i < num_blocks; i++) {
470                 struct flash_sector *f = &block_array[i];
471                 target_addr_t sector_addr = c->base + f->offset;
472                 target_addr_t sector_last_addr = sector_addr + f->size - 1;
473
474                 /* start only on a sector boundary */
475                 if (first < 0) {
476                         /* scanned past the first sector? */
477                         if (addr < sector_addr)
478                                 break;
479
480                         /* is this the first sector? */
481                         if (addr == sector_addr)
482                                 first = i;
483
484                         /* Does this need head-padding?  If so, pad and warn;
485                          * or else force an error.
486                          *
487                          * Such padding can make trouble, since *WE* can't
488                          * ever know if that data was in use.  The warning
489                          * should help users sort out messes later.
490                          */
491                         else if (addr <= sector_last_addr && pad_reason) {
492                                 /* FIXME say how many bytes (e.g. 80 KB) */
493                                 LOG_WARNING("Adding extra %s range, "
494                                         TARGET_ADDR_FMT " .. " TARGET_ADDR_FMT,
495                                         pad_reason,
496                                         sector_addr,
497                                         addr - 1);
498                                 first = i;
499                         } else
500                                 continue;
501                 }
502
503                 /* is this (also?) the last sector? */
504                 if (last_addr == sector_last_addr) {
505                         last = i;
506                         break;
507                 }
508
509                 /* Does this need tail-padding?  If so, pad and warn;
510                  * or else force an error.
511                  */
512                 if (last_addr < sector_last_addr && pad_reason) {
513                         /* FIXME say how many bytes (e.g. 80 KB) */
514                         LOG_WARNING("Adding extra %s range, "
515                                 TARGET_ADDR_FMT " .. " TARGET_ADDR_FMT,
516                                 pad_reason,
517                                 last_addr + 1,
518                                 sector_last_addr);
519                         last = i;
520                         break;
521                 }
522
523                 /* MUST finish on a sector boundary */
524                 if (last_addr < sector_addr)
525                         break;
526         }
527
528         /* invalid start or end address? */
529         if (first == -1 || last == -1) {
530                 LOG_ERROR("address range " TARGET_ADDR_FMT " .. " TARGET_ADDR_FMT
531                         " is not sector-aligned",
532                         addr,
533                         last_addr);
534                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
535         }
536
537         /* The NOR driver may trim this range down, based on what
538          * sectors are already erased/unprotected.  GDB currently
539          * blocks such optimizations.
540          */
541         return callback(c, first, last);
542 }
543
544 /* The inner fn only handles a single bank, we could be spanning
545  * multiple chips.
546  */
547 static int flash_iterate_address_range(struct target *target,
548         char *pad_reason, target_addr_t addr, uint32_t length,
549         bool iterate_protect_blocks,
550         int (*callback)(struct flash_bank *bank, int first, int last))
551 {
552         struct flash_bank *c;
553         int retval = ERROR_OK;
554
555         /* Danger! zero-length iterations means entire bank! */
556         do {
557                 retval = get_flash_bank_by_addr(target, addr, true, &c);
558                 if (retval != ERROR_OK)
559                         return retval;
560
561                 uint32_t cur_length = length;
562                 /* check whether it all fits in this bank */
563                 if (addr + length - 1 > c->base + c->size - 1) {
564                         LOG_DEBUG("iterating over more than one flash bank.");
565                         cur_length = c->base + c->size - addr;
566                 }
567                 retval = flash_iterate_address_range_inner(target,
568                                 pad_reason, addr, cur_length,
569                                 iterate_protect_blocks,
570                                 callback);
571                 if (retval != ERROR_OK)
572                         break;
573
574                 length -= cur_length;
575                 addr += cur_length;
576         } while (length > 0);
577
578         return retval;
579 }
580
581 int flash_erase_address_range(struct target *target,
582         bool pad, target_addr_t addr, uint32_t length)
583 {
584         return flash_iterate_address_range(target, pad ? "erase" : NULL,
585                 addr, length, false, &flash_driver_erase);
586 }
587
588 static int flash_driver_unprotect(struct flash_bank *bank, int first, int last)
589 {
590         return flash_driver_protect(bank, 0, first, last);
591 }
592
593 int flash_unlock_address_range(struct target *target, target_addr_t addr,
594                 uint32_t length)
595 {
596         /* By default, pad to sector boundaries ... the real issue here
597          * is that our (only) caller *permanently* removes protection,
598          * and doesn't restore it.
599          */
600         return flash_iterate_address_range(target, "unprotect",
601                 addr, length, true, &flash_driver_unprotect);
602 }
603
604 static int compare_section(const void *a, const void *b)
605 {
606         struct imagesection *b1, *b2;
607         b1 = *((struct imagesection **)a);
608         b2 = *((struct imagesection **)b);
609
610         if (b1->base_address == b2->base_address)
611                 return 0;
612         else if (b1->base_address > b2->base_address)
613                 return 1;
614         else
615                 return -1;
616 }
617
618 /**
619  * Get aligned start address of a flash write region
620  */
621 target_addr_t flash_write_align_start(struct flash_bank *bank, target_addr_t addr)
622 {
623         if (addr < bank->base || addr >= bank->base + bank->size
624                         || bank->write_start_alignment <= 1)
625                 return addr;
626
627         if (bank->write_start_alignment == FLASH_WRITE_ALIGN_SECTOR) {
628                 uint32_t offset = addr - bank->base;
629                 uint32_t aligned = 0;
630                 int sect;
631                 for (sect = 0; sect < bank->num_sectors; sect++) {
632                         if (bank->sectors[sect].offset > offset)
633                                 break;
634
635                         aligned = bank->sectors[sect].offset;
636                 }
637                 return bank->base + aligned;
638         }
639
640         return addr & ~(bank->write_start_alignment - 1);
641 }
642
643 /**
644  * Get aligned end address of a flash write region
645  */
646 target_addr_t flash_write_align_end(struct flash_bank *bank, target_addr_t addr)
647 {
648         if (addr < bank->base || addr >= bank->base + bank->size
649                         || bank->write_end_alignment <= 1)
650                 return addr;
651
652         if (bank->write_end_alignment == FLASH_WRITE_ALIGN_SECTOR) {
653                 uint32_t offset = addr - bank->base;
654                 uint32_t aligned = 0;
655                 int sect;
656                 for (sect = 0; sect < bank->num_sectors; sect++) {
657                         aligned = bank->sectors[sect].offset + bank->sectors[sect].size - 1;
658                         if (aligned >= offset)
659                                 break;
660                 }
661                 return bank->base + aligned;
662         }
663
664         return addr | (bank->write_end_alignment - 1);
665 }
666
667 /**
668  * Check if gap between sections is bigger than minimum required to discontinue flash write
669  */
670 static bool flash_write_check_gap(struct flash_bank *bank,
671                                 target_addr_t addr1, target_addr_t addr2)
672 {
673         if (bank->minimal_write_gap == FLASH_WRITE_CONTINUOUS
674                         || addr1 < bank->base || addr1 >= bank->base + bank->size
675                         || addr2 < bank->base || addr2 >= bank->base + bank->size)
676                 return false;
677
678         if (bank->minimal_write_gap == FLASH_WRITE_GAP_SECTOR) {
679                 int sect;
680                 uint32_t offset1 = addr1 - bank->base;
681                 /* find the sector following the one containing addr1 */
682                 for (sect = 0; sect < bank->num_sectors; sect++) {
683                         if (bank->sectors[sect].offset > offset1)
684                                 break;
685                 }
686                 if (sect >= bank->num_sectors)
687                         return false;
688
689                 uint32_t offset2 = addr2 - bank->base;
690                 return bank->sectors[sect].offset + bank->sectors[sect].size <= offset2;
691         }
692
693         target_addr_t aligned1 = flash_write_align_end(bank, addr1);
694         target_addr_t aligned2 = flash_write_align_start(bank, addr2);
695         return aligned1 + bank->minimal_write_gap < aligned2;
696 }
697
698
699 int flash_write_unlock(struct target *target, struct image *image,
700         uint32_t *written, int erase, bool unlock)
701 {
702         int retval = ERROR_OK;
703
704         int section;
705         uint32_t section_offset;
706         struct flash_bank *c;
707         int *padding;
708
709         section = 0;
710         section_offset = 0;
711
712         if (written)
713                 *written = 0;
714
715         if (erase) {
716                 /* assume all sectors need erasing - stops any problems
717                  * when flash_write is called multiple times */
718
719                 flash_set_dirty();
720         }
721
722         /* allocate padding array */
723         padding = calloc(image->num_sections, sizeof(*padding));
724
725         /* This fn requires all sections to be in ascending order of addresses,
726          * whereas an image can have sections out of order. */
727         struct imagesection **sections = malloc(sizeof(struct imagesection *) *
728                         image->num_sections);
729         int i;
730         for (i = 0; i < image->num_sections; i++)
731                 sections[i] = &image->sections[i];
732
733         qsort(sections, image->num_sections, sizeof(struct imagesection *),
734                 compare_section);
735
736         /* loop until we reach end of the image */
737         while (section < image->num_sections) {
738                 uint32_t buffer_idx;
739                 uint8_t *buffer;
740                 int section_last;
741                 target_addr_t run_address = sections[section]->base_address + section_offset;
742                 uint32_t run_size = sections[section]->size - section_offset;
743                 int pad_bytes = 0;
744
745                 if (sections[section]->size ==  0) {
746                         LOG_WARNING("empty section %d", section);
747                         section++;
748                         section_offset = 0;
749                         continue;
750                 }
751
752                 /* find the corresponding flash bank */
753                 retval = get_flash_bank_by_addr(target, run_address, false, &c);
754                 if (retval != ERROR_OK)
755                         goto done;
756                 if (c == NULL) {
757                         LOG_WARNING("no flash bank found for address " TARGET_ADDR_FMT, run_address);
758                         section++;      /* and skip it */
759                         section_offset = 0;
760                         continue;
761                 }
762
763                 /* collect consecutive sections which fall into the same bank */
764                 section_last = section;
765                 padding[section] = 0;
766                 while ((run_address + run_size - 1 < c->base + c->size - 1) &&
767                                 (section_last + 1 < image->num_sections)) {
768                         /* sections are sorted */
769                         assert(sections[section_last + 1]->base_address >= c->base);
770                         if (sections[section_last + 1]->base_address >= (c->base + c->size)) {
771                                 /* Done with this bank */
772                                 break;
773                         }
774
775                         /* if we have multiple sections within our image,
776                          * flash programming could fail due to alignment issues
777                          * attempt to rebuild a consecutive buffer for the flash loader */
778                         target_addr_t run_next_addr = run_address + run_size;
779                         target_addr_t next_section_base = sections[section_last + 1]->base_address;
780                         if (next_section_base < run_next_addr) {
781                                 LOG_ERROR("Section at " TARGET_ADDR_FMT
782                                         " overlaps section ending at " TARGET_ADDR_FMT,
783                                         next_section_base, run_next_addr);
784                                 LOG_ERROR("Flash write aborted.");
785                                 retval = ERROR_FAIL;
786                                 goto done;
787                         }
788
789                         pad_bytes = next_section_base - run_next_addr;
790                         if (pad_bytes) {
791                                 if (flash_write_check_gap(c, run_next_addr - 1, next_section_base)) {
792                                         LOG_INFO("Flash write discontinued at " TARGET_ADDR_FMT
793                                                 ", next section at " TARGET_ADDR_FMT,
794                                                 run_next_addr, next_section_base);
795                                         break;
796                                 }
797                         }
798                         if (pad_bytes > 0)
799                                 LOG_INFO("Padding image section %d at " TARGET_ADDR_FMT
800                                         " with %d bytes",
801                                         section_last, run_next_addr, pad_bytes);
802
803                         padding[section_last] = pad_bytes;
804                         run_size += pad_bytes;
805                         run_size += sections[++section_last]->size;
806                 }
807
808                 if (run_address + run_size - 1 > c->base + c->size - 1) {
809                         /* If we have more than one flash chip back to back, then we limit
810                          * the current write operation to the current chip.
811                          */
812                         LOG_DEBUG("Truncate flash run size to the current flash chip.");
813
814                         run_size = c->base + c->size - run_address;
815                         assert(run_size > 0);
816                 }
817
818                 uint32_t padding_at_start = 0;
819                 if (c->write_start_alignment || c->write_end_alignment) {
820                         /* align write region according to bank requirements */
821                         target_addr_t aligned_start = flash_write_align_start(c, run_address);
822                         padding_at_start = run_address - aligned_start;
823                         if (padding_at_start > 0) {
824                                 LOG_WARNING("Section start address " TARGET_ADDR_FMT
825                                         " breaks the required alignment of flash bank %s",
826                                         run_address, c->name);
827                                 LOG_WARNING("Padding %d bytes from " TARGET_ADDR_FMT,
828                                         padding_at_start, aligned_start);
829
830                                 run_address -= padding_at_start;
831                                 run_size += padding_at_start;
832                         }
833
834                         target_addr_t run_end = run_address + run_size - 1;
835                         target_addr_t aligned_end = flash_write_align_end(c, run_end);
836                         pad_bytes = aligned_end - run_end;
837                         if (pad_bytes > 0) {
838                                 LOG_INFO("Padding image section %d at " TARGET_ADDR_FMT
839                                         " with %d bytes (bank write end alignment)",
840                                         section_last, run_end + 1, pad_bytes);
841
842                                 padding[section_last] += pad_bytes;
843                                 run_size += pad_bytes;
844                         }
845
846                 } else if (unlock || erase) {
847                         /* If we're applying any sector automagic, then pad this
848                          * (maybe-combined) segment to the end of its last sector.
849                          */
850                         int sector;
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 (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, int 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, int num_blocks)
964 {
965         int i;
966
967         struct flash_sector *array = calloc(num_blocks, sizeof(struct flash_sector));
968         if (array == NULL)
969                 return NULL;
970
971         for (i = 0; i < num_blocks; i++) {
972                 array[i].offset = offset;
973                 array[i].size = size;
974                 array[i].is_erased = -1;
975                 array[i].is_protected = -1;
976                 offset += size;
977         }
978
979         return array;
980 }