xref: /btstack/platform/embedded/btstack_tlv_flash_bank.c (revision 4c7f527567df738efde5d6ff06565624d5b138f6)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
21  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 #define BTSTACK_FILE__ "btstack_tlv_flash_bank.c"
33 
34 #include "btstack_tlv.h"
35 #include "btstack_tlv_flash_bank.h"
36 #include "btstack_debug.h"
37 #include "btstack_util.h"
38 #include "btstack_debug.h"
39 
40 #include <string.h>
41 #include <inttypes.h>
42 
43 // Header:
44 // - Magic: 'BTstack'
45 // - Status:
46 //   - bits 765432: reserved
47 //	 - bits 10:     epoch
48 
49 // Entries
50 // - Tag: 32 bit
51 // - Len: 32 bit
52 // - Delete: 32 delete field - only used with ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
53 // - Value: Len in bytes
54 
55 // ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
56 //
57 // Most Flash implementations allow to:
58 // - erase sector -> all values are 0xff
59 // - write value (1s -> 0s)
60 // - overwrite value with zero (remaining 1s -> 0s)
61 //
62 // We use the ability to overwrite a value with zeros to mark deleted enttries (by writing zero into the tag field).
63 // Some targets, E.g. Kinetix K64F, do enot allow for that.
64 //
65 // With ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD an extra field is reserved to indicate a deleted tag, while keeping main logic
66 //
67 // With ENABLE_TLV_FLASH_WRITE_ONCE, tags are never marked as deleted. Instead, an emtpy tag will be written instead.
68 //     Also, lookup and migrate requires to always search until the end of the valid bank
69 
70 #if defined (ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD) && defined (ENABLE_TLV_FLASH_WRITE_ONCE)
71 #error "Please define either ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD or ENABLE_TLV_FLASH_WRITE_ONCE"
72 #endif
73 
74 #define BTSTACK_TLV_HEADER_LEN 8
75 
76 #ifndef BTSTACK_FLASH_ALIGNMENT_MAX
77 #define BTSTACK_FLASH_ALIGNMENT_MAX 8
78 #endif
79 
80 static const char * btstack_tlv_header_magic = "BTstack";
81 
82 // TLV Iterator
83 typedef struct {
84 	int 	 bank;
85 	uint32_t offset;
86     uint32_t size;
87 	uint32_t tag;
88 	uint32_t len;
89 } tlv_iterator_t;
90 
91 static uint32_t btstack_tlv_flash_bank_align_size(btstack_tlv_flash_bank_t * self, uint32_t size){
92 	uint32_t alignment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
93 	return (size + alignment - 1) & ~(alignment - 1);
94 }
95 
96 // support unaligned flash read/writes
97 // strategy: increase size to meet alignment, perform unaligned read/write of last chunk with helper buffer
98 
99 static void btstack_tlv_flash_bank_read(btstack_tlv_flash_bank_t * self, int bank, uint32_t offset, uint8_t * buffer, uint32_t size){
100 
101 	// read main data
102 	uint32_t aligment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
103 	uint32_t lower_bits = size & (aligment - 1);
104 	uint32_t size_aligned = size - lower_bits;
105 	if (size_aligned){
106 		self->hal_flash_bank_impl->read(self->hal_flash_bank_context, bank, offset, buffer, size_aligned);
107 		buffer += size_aligned;
108 		offset += size_aligned;
109 		size   -= size_aligned;
110 	}
111 
112 	// read last part
113 	if (size == 0) return;
114 	uint8_t aligment_block[BTSTACK_FLASH_ALIGNMENT_MAX];
115 	self->hal_flash_bank_impl->read(self->hal_flash_bank_context, bank, offset, aligment_block, aligment);
116 	uint32_t bytes_to_copy = btstack_min(aligment - lower_bits, size);
117 	memcpy(buffer, aligment_block, bytes_to_copy);
118 }
119 
120 static void btstack_tlv_flash_bank_write(btstack_tlv_flash_bank_t * self, int bank, uint32_t offset, const uint8_t * buffer, uint32_t size){
121 
122 	// write main data
123 	uint32_t aligment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
124 	uint32_t lower_bits = size & (aligment - 1);
125 	uint32_t size_aligned = size - lower_bits;
126 	if (size_aligned){
127 		self->hal_flash_bank_impl->write(self->hal_flash_bank_context, bank, offset, buffer, size_aligned);
128 		buffer += size_aligned;
129 		offset += size_aligned;
130 		size   -= size_aligned;
131 	}
132 
133 	// write last part
134 	if (size == 0) return;
135 	uint8_t aligment_block[BTSTACK_FLASH_ALIGNMENT_MAX];
136 	memset(aligment_block, 0xff, aligment);
137 	memcpy(aligment_block, buffer, lower_bits);
138 	self->hal_flash_bank_impl->write(self->hal_flash_bank_context, bank, offset, aligment_block, aligment);
139 }
140 
141 
142 // iterator
143 
144 static void btstack_tlv_flash_bank_iterator_fetch_tag_len(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it){
145     // abort if header doesn't fit into remaining space
146     if (it->offset + 8 + self->delete_tag_len >= self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
147         it->tag = 0xffffffff;
148         return;
149     }
150 
151 	uint8_t entry[8];
152 	btstack_tlv_flash_bank_read(self, it->bank, it->offset, entry, 8);
153 	it->tag = big_endian_read_32(entry, 0);
154 	it->len = big_endian_read_32(entry, 4);
155 
156 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
157 	// clear tag, if delete field is set
158 	uint32_t delete_tag;
159 	btstack_tlv_flash_bank_read(self, it->bank, it->offset + 8, (uint8_t *) &delete_tag, 4);
160 	if (delete_tag == 0){
161 		it->tag = 0;
162 	}
163 #endif
164 }
165 
166 static void btstack_tlv_flash_bank_iterator_init(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it, int bank){
167 	memset(it, 0, sizeof(tlv_iterator_t));
168 	it->bank = bank;
169 	it->offset = BTSTACK_TLV_HEADER_LEN;
170     it->size = self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context);
171 	btstack_tlv_flash_bank_iterator_fetch_tag_len(self, it);
172 }
173 
174 static bool btstack_tlv_flash_bank_iterator_has_next(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it){
175 	UNUSED(self);
176 	return it->tag != 0xffffffff;
177 }
178 
179 static void tlv_iterator_fetch_next(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it){
180 	it->offset += 8 + btstack_tlv_flash_bank_align_size(self, it->len);
181 
182 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
183 	// skip delete field
184 	it->offset += self->delete_tag_len;
185 #endif
186 
187 	if (it->offset >= it->size) {
188 		it->tag = 0xffffffff;
189 		it->len = 0;
190 		return;
191 	}
192 	btstack_tlv_flash_bank_iterator_fetch_tag_len(self, it);
193 }
194 
195 //
196 
197 // check both banks for headers and pick the one with the higher epoch % 4
198 // @returns bank or -1 if something is invalid
199 static int btstack_tlv_flash_bank_get_latest_bank(btstack_tlv_flash_bank_t * self){
200  	uint8_t header0[BTSTACK_TLV_HEADER_LEN];
201  	uint8_t header1[BTSTACK_TLV_HEADER_LEN];
202  	btstack_tlv_flash_bank_read(self, 0, 0, &header0[0], BTSTACK_TLV_HEADER_LEN);
203  	btstack_tlv_flash_bank_read(self, 1, 0, &header1[0], BTSTACK_TLV_HEADER_LEN);
204  	int valid0 = memcmp(header0, btstack_tlv_header_magic, BTSTACK_TLV_HEADER_LEN-1) == 0;
205  	int valid1 = memcmp(header1, btstack_tlv_header_magic, BTSTACK_TLV_HEADER_LEN-1) == 0;
206 	if (!valid0 && !valid1) return -1;
207 	if ( valid0 && !valid1) return 0;
208 	if (!valid0 &&  valid1) return 1;
209 	int epoch0 = header0[BTSTACK_TLV_HEADER_LEN-1] & 0x03;
210 	int epoch1 = header1[BTSTACK_TLV_HEADER_LEN-1] & 0x03;
211 	if (epoch0 == ((epoch1 + 1) & 0x03)) return 0;
212 	if (epoch1 == ((epoch0 + 1) & 0x03)) return 1;
213 	return -1;	// invalid, must not happen
214 }
215 
216 static void btstack_tlv_flash_bank_write_header(btstack_tlv_flash_bank_t * self, int bank, int epoch){
217 	uint8_t header[BTSTACK_TLV_HEADER_LEN];
218 	memcpy(&header[0], btstack_tlv_header_magic, BTSTACK_TLV_HEADER_LEN-1);
219 	header[BTSTACK_TLV_HEADER_LEN-1] = epoch;
220 	btstack_tlv_flash_bank_write(self, bank, 0, header, BTSTACK_TLV_HEADER_LEN);
221 }
222 
223 /**
224  * @brief Check if erased from offset
225  */
226 static int btstack_tlv_flash_bank_test_erased(btstack_tlv_flash_bank_t * self, int bank, uint32_t offset){
227 	log_info("test erased: bank %u, offset %u", bank, (unsigned int) offset);
228 	uint32_t size = self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context);
229 	uint8_t buffer[16];
230 	uint8_t empty16[16];
231 	memset(empty16, 0xff, sizeof(empty16));
232 	while (offset < size){
233 		uint32_t copy_size = (offset + sizeof(empty16) < size) ? sizeof(empty16) : (size - offset);
234 		btstack_tlv_flash_bank_read(self, bank, offset, buffer, copy_size);
235 		if (memcmp(buffer, empty16, copy_size) != 0) {
236 			log_info("not erased %x - %x", (unsigned int) offset, (unsigned int) (offset + copy_size));
237 			return 0;
238 		}
239 		offset += copy_size;
240 	}
241 	return 1;
242 }
243 
244 /**
245  * @brief erase bank (only if not already erased)
246  */
247 static void btstack_tlv_flash_bank_erase_bank(btstack_tlv_flash_bank_t * self, int bank){
248 	if (btstack_tlv_flash_bank_test_erased(self, bank, 0)){
249 		log_info("bank %u already erased", bank);
250 	} else {
251 		log_info("bank %u not empty, erase bank", bank);
252 		self->hal_flash_bank_impl->erase(self->hal_flash_bank_context, bank);
253 	}
254 }
255 
256 static void btstack_tlv_flash_bank_migrate(btstack_tlv_flash_bank_t * self){
257 
258 	int next_bank = 1 - self->current_bank;
259 	log_info("migrate bank %u -> bank %u", self->current_bank, next_bank);
260 	// erase bank (if needed)
261 	btstack_tlv_flash_bank_erase_bank(self, next_bank);
262 	int next_write_pos = 8;
263 
264 	tlv_iterator_t it;
265 	btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
266 	while (btstack_tlv_flash_bank_iterator_has_next(self, &it)){
267 		// skip deleted entries
268 		if (it.tag) {
269 			uint32_t tag_len = it.len;
270 			uint32_t tag_index = it.offset;
271 
272             bool tag_valid = true;
273 
274 #ifdef ENABLE_TLV_FLASH_WRITE_ONCE
275             // search until end for newer entry of same tag
276             tlv_iterator_t it2;
277             memcpy(&it2, &it, sizeof(tlv_iterator_t));
278             while (btstack_tlv_flash_bank_iterator_has_next(self, &it2)){
279                 if ((it2.offset != it.offset) && (it2.tag == it.tag)){
280                     tag_valid = false;
281                     break;
282                 }
283                 tlv_iterator_fetch_next(self, &it2);
284             }
285             if (tag_valid == false){
286 			    log_info("skip pos %u, tag '%x' as newer entry found at %u", (unsigned int) tag_index, (unsigned int) it.tag,
287                     (unsigned int) it2.offset);
288             }
289 #endif
290 
291             if (tag_valid) {
292 
293                 log_info("migrate pos %u, tag '%x' len %u -> new pos %u",
294                          (unsigned int) tag_index, (unsigned int) it.tag, (unsigned int) tag_len, next_write_pos);
295 
296                 // copy header
297                 uint8_t header_buffer[8];
298                 btstack_tlv_flash_bank_read(self, self->current_bank, tag_index, header_buffer, 8);
299                 btstack_tlv_flash_bank_write(self, next_bank, next_write_pos, header_buffer, 8);
300                 tag_index += 8;
301                 next_write_pos += 8;
302 
303 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
304                 // skip delete field
305                 tag_index      += self->delete_tag_len;
306                 next_write_pos += self->delete_tag_len;
307 #endif
308                 // copy value
309                 int bytes_to_copy = tag_len;
310                 uint8_t copy_buffer[32];
311                 while (bytes_to_copy) {
312                     int bytes_this_iteration = btstack_min(bytes_to_copy, sizeof(copy_buffer));
313                     btstack_tlv_flash_bank_read(self, self->current_bank, tag_index, copy_buffer, bytes_this_iteration);
314                     btstack_tlv_flash_bank_write(self, next_bank, next_write_pos, copy_buffer, bytes_this_iteration);
315                     tag_index += bytes_this_iteration;
316                     next_write_pos += bytes_this_iteration;
317                     bytes_to_copy -= bytes_this_iteration;
318                 }
319             }
320 		}
321 		tlv_iterator_fetch_next(self, &it);
322 	}
323 
324 	// prepare new one
325 	uint8_t epoch_buffer;
326 	btstack_tlv_flash_bank_read(self, self->current_bank, BTSTACK_TLV_HEADER_LEN-1, &epoch_buffer, 1);
327 	btstack_tlv_flash_bank_write_header(self, next_bank, (epoch_buffer + 1) & 3);
328 	self->current_bank = next_bank;
329 	self->write_offset = next_write_pos;
330 }
331 
332 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
333 static void btstack_tlv_flash_bank_delete_tag_until_offset(btstack_tlv_flash_bank_t * self, uint32_t tag, uint32_t offset){
334 	tlv_iterator_t it;
335 	btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
336 	while (btstack_tlv_flash_bank_iterator_has_next(self, &it) && it.offset < offset){
337 		if (it.tag == tag){
338 			log_info("Erase tag '%x' at position %u", (unsigned int) tag, (unsigned int) it.offset);
339 
340 			// mark entry as invalid
341 			uint32_t zero_value = 0;
342 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
343 			// write delete field at offset 8
344 			btstack_tlv_flash_bank_write(self, self->current_bank, it.offset+8, (uint8_t*) &zero_value, sizeof(zero_value));
345 #else
346 			// overwrite tag with zero value
347 			btstack_tlv_flash_bank_write(self, self->current_bank, it.offset, (uint8_t*) &zero_value, sizeof(zero_value));
348 #endif
349 
350 		}
351 		tlv_iterator_fetch_next(self, &it);
352 	}
353 }
354 #endif
355 
356 /**
357  * Get Value for Tag
358  * @param tag
359  * @param buffer
360  * @param buffer_size
361  * @returns size of value
362  */
363 static int btstack_tlv_flash_bank_get_tag(void * context, uint32_t tag, uint8_t * buffer, uint32_t buffer_size){
364 
365 	btstack_tlv_flash_bank_t * self = (btstack_tlv_flash_bank_t *) context;
366 
367 	uint32_t tag_index = 0;
368 	uint32_t tag_len   = 0;
369 	tlv_iterator_t it;
370 	btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
371 	while (btstack_tlv_flash_bank_iterator_has_next(self, &it)){
372 		if (it.tag == tag){
373 			log_info("Found tag '%x' at position %u", (unsigned int) tag, (unsigned int) it.offset);
374 			tag_index = it.offset;
375 			tag_len   = it.len;
376 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
377 			break;
378 #endif
379 		}
380 		tlv_iterator_fetch_next(self, &it);
381 	}
382 	if (tag_index == 0) return 0;
383 	if (!buffer) return tag_len;
384 	int copy_size = btstack_min(buffer_size, tag_len);
385 	uint32_t value_offset = tag_index + 8;
386 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
387 	// skip delete field
388 	value_offset += self->delete_tag_len;
389 #endif
390 	btstack_tlv_flash_bank_read(self, self->current_bank, value_offset, buffer, copy_size);
391 	return copy_size;
392 }
393 
394 /**
395  * Store Tag
396  * @param tag
397  * @param data
398  * @param data_size
399  */
400 static int btstack_tlv_flash_bank_store_tag(void * context, uint32_t tag, const uint8_t * data, uint32_t data_size){
401 
402 	btstack_tlv_flash_bank_t * self = (btstack_tlv_flash_bank_t *) context;
403 
404 	// trigger migration if not enough space
405 	uint32_t required_space = 8 + self->delete_tag_len + data_size;
406 	if (self->write_offset + required_space > self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
407 		btstack_tlv_flash_bank_migrate(self);
408 	}
409 
410 	if (self->write_offset + required_space > self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
411 		log_error("couldn't write entry, not enough space left");
412 		return 2;
413 	}
414 
415 	// prepare entry
416 	uint8_t entry[8];
417 	big_endian_store_32(entry, 0, tag);
418 	big_endian_store_32(entry, 4, data_size);
419 
420 	log_info("write '%" PRIx32 "', len %" PRIu32 " at %" PRIx32, tag, data_size, self->write_offset);
421 
422 	uint32_t value_offset = self->write_offset + 8;
423 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
424 	// skip delete field
425 	value_offset += self->delete_tag_len;
426 #endif
427 
428 	// write value first
429 	btstack_tlv_flash_bank_write(self, self->current_bank, value_offset, data, data_size);
430 
431 	// then entry
432 	btstack_tlv_flash_bank_write(self, self->current_bank, self->write_offset, entry, sizeof(entry));
433 
434 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
435 	// overwrite old entries (if exists)
436 	btstack_tlv_flash_bank_delete_tag_until_offset(self, tag, self->write_offset);
437 #endif
438 
439 	// done
440 	self->write_offset += sizeof(entry) + btstack_tlv_flash_bank_align_size(self, data_size);
441 
442 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
443 	// skip delete field
444 	self->write_offset += self->delete_tag_len;
445 #endif
446 
447 	return 0;
448 }
449 
450 /**
451  * Delete Tag
452  * @param tag
453  */
454 static void btstack_tlv_flash_bank_delete_tag(void * context, uint32_t tag){
455 #ifdef ENABLE_TLV_FLASH_WRITE_ONCE
456     btstack_tlv_flash_bank_store_tag(context, tag, NULL, 0);
457 #else
458     btstack_tlv_flash_bank_t * self = (btstack_tlv_flash_bank_t *) context;
459 	btstack_tlv_flash_bank_delete_tag_until_offset(self, tag, self->write_offset);
460 #endif
461 }
462 
463 static const btstack_tlv_t btstack_tlv_flash_bank = {
464 	/* int  (*get_tag)(..);     */ &btstack_tlv_flash_bank_get_tag,
465 	/* int (*store_tag)(..);    */ &btstack_tlv_flash_bank_store_tag,
466 	/* void (*delete_tag)(v..); */ &btstack_tlv_flash_bank_delete_tag,
467 };
468 
469 /**
470  * Init Tag Length Value Store
471  */
472 const btstack_tlv_t * btstack_tlv_flash_bank_init_instance(btstack_tlv_flash_bank_t * self, const hal_flash_bank_t * hal_flash_bank_impl, void * hal_flash_bank_context){
473 
474 	self->hal_flash_bank_impl    = hal_flash_bank_impl;
475 	self->hal_flash_bank_context = hal_flash_bank_context;
476 	self->delete_tag_len = 0;
477 
478 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
479 	if (hal_flash_bank_impl->get_alignment(hal_flash_bank_context) > 8){
480 		log_error("Flash alignment > 8 with ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD not supported");
481 		return NULL;
482 	}
483 	// set delete tag len
484 	uint32_t aligment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
485 	self->delete_tag_len = (uint8_t) btstack_max(4, aligment);
486 	log_info("delete tag len %u", self->delete_tag_len);
487 #endif
488 
489 	// try to find current bank
490 	self->current_bank = btstack_tlv_flash_bank_get_latest_bank(self);
491 	log_info("found bank %d", self->current_bank);
492 	if (self->current_bank >= 0){
493 
494 		// find last entry and write offset
495 		tlv_iterator_t it;
496 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
497 		uint32_t last_tag = 0;
498 		uint32_t last_offset = 0;
499 #endif
500         btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
501 		while (btstack_tlv_flash_bank_iterator_has_next(self, &it)){
502 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
503 			last_tag = it.tag;
504 			last_offset = it.offset;
505 #endif
506 			tlv_iterator_fetch_next(self, &it);
507 		}
508 		self->write_offset = it.offset;
509 
510 		if (self->write_offset <= self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
511 
512 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
513 			// delete older instances of last_tag
514 			// this handles the unlikely case where MCU did reset after new value + header was written but before delete did complete
515 			if (last_tag){
516 				btstack_tlv_flash_bank_delete_tag_until_offset(self, last_tag, last_offset);
517 			}
518 #endif
519 
520 			// verify that rest of bank is empty
521 			// this handles the unlikely case where MCU did reset after new value was written, but not the tag
522 			if (!btstack_tlv_flash_bank_test_erased(self, self->current_bank, self->write_offset)){
523 				log_info("Flash not empty after last found tag -> migrate");
524 				btstack_tlv_flash_bank_migrate(self);
525 			} else {
526 				log_info("Flash clean after last found tag");
527 			}
528 		} else {
529 			// failure!
530 			self->current_bank = -1;
531 		}
532 	}
533 
534 	if (self->current_bank < 0) {
535 		btstack_tlv_flash_bank_erase_bank(self, 0);
536 		self->current_bank = 0;
537 		btstack_tlv_flash_bank_write_header(self, self->current_bank, 0);	// epoch = 0;
538 		self->write_offset = 8;
539 	}
540 
541 	log_info("write offset %" PRIx32, self->write_offset);
542 	return &btstack_tlv_flash_bank;
543 }
544 
545