xref: /btstack/platform/embedded/btstack_tlv_flash_bank.c (revision 9b112178fd109e1643278953cdedb54dd6f3f84b)
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_BANK_HEADER_LEN  8
75 #define BTSTACK_TLV_ENTRY_HEADER_LEN 8
76 
77 #ifndef BTSTACK_FLASH_ALIGNMENT_MAX
78 #define BTSTACK_FLASH_ALIGNMENT_MAX 8
79 #endif
80 
81 static const char * btstack_tlv_header_magic = "BTstack";
82 
83 // TLV Iterator
84 typedef struct {
85 	int 	 bank;
86 	uint32_t offset;
87     uint32_t size;
88 	uint32_t tag;
89 	uint32_t len;
90 } tlv_iterator_t;
91 
92 static uint32_t btstack_tlv_flash_bank_align_size(btstack_tlv_flash_bank_t * self, uint32_t size){
93 	uint32_t alignment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
94 	return (size + alignment - 1) & ~(alignment - 1);
95 }
96 
97 // support unaligned flash read/writes
98 // strategy: increase size to meet alignment, perform unaligned read/write of last chunk with helper buffer
99 
100 static void btstack_tlv_flash_bank_read(btstack_tlv_flash_bank_t * self, int bank, uint32_t offset, uint8_t * buffer, uint32_t size){
101 
102 	// read main data
103 	uint32_t alignment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
104 	uint32_t lower_bits = size & (alignment - 1);
105 	uint32_t size_aligned = size - lower_bits;
106 	if (size_aligned){
107 		self->hal_flash_bank_impl->read(self->hal_flash_bank_context, bank, offset, buffer, size_aligned);
108 		buffer += size_aligned;
109 		offset += size_aligned;
110 		size   -= size_aligned;
111 	}
112 
113 	// read last part
114 	if (size == 0) return;
115 	uint8_t alignment_block[BTSTACK_FLASH_ALIGNMENT_MAX];
116 	self->hal_flash_bank_impl->read(self->hal_flash_bank_context, bank, offset, alignment_block, alignment);
117 	uint32_t bytes_to_copy = btstack_min(alignment - lower_bits, size);
118 	memcpy(buffer, alignment_block, bytes_to_copy);
119 }
120 
121 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){
122 
123 	// write main data
124 	uint32_t alignment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
125 	uint32_t lower_bits = size & (alignment - 1);
126 	uint32_t size_aligned = size - lower_bits;
127 	if (size_aligned){
128 		self->hal_flash_bank_impl->write(self->hal_flash_bank_context, bank, offset, buffer, size_aligned);
129 		buffer += size_aligned;
130 		offset += size_aligned;
131 		size   -= size_aligned;
132 	}
133 
134 	// write last part
135 	if (size == 0) return;
136 	uint8_t alignment_block[BTSTACK_FLASH_ALIGNMENT_MAX];
137 	memset(alignment_block, 0xff, alignment);
138 	memcpy(alignment_block, buffer, lower_bits);
139 	self->hal_flash_bank_impl->write(self->hal_flash_bank_context, bank, offset, alignment_block, alignment);
140 }
141 
142 
143 // iterator
144 
145 static void btstack_tlv_flash_bank_iterator_fetch_tag_len(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it){
146     // abort if header doesn't fit into remaining space
147     if (it->offset + BTSTACK_TLV_ENTRY_HEADER_LEN + self->delete_tag_len >= self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
148         it->tag = 0xffffffff;
149         return;
150     }
151 
152 	uint8_t entry[BTSTACK_TLV_ENTRY_HEADER_LEN];
153 	btstack_tlv_flash_bank_read(self, it->bank, it->offset, entry, BTSTACK_TLV_ENTRY_HEADER_LEN);
154 	it->tag = big_endian_read_32(entry, 0);
155 	it->len = big_endian_read_32(entry, 4);
156 
157 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
158 	// clear tag, if delete field is set
159 	uint32_t delete_tag;
160 	btstack_tlv_flash_bank_read(self, it->bank, it->offset + BTSTACK_TLV_ENTRY_HEADER_LEN, (uint8_t *) &delete_tag, 4);
161 	if (delete_tag == 0){
162 		it->tag = 0;
163 	}
164 #endif
165 }
166 
167 static void btstack_tlv_flash_bank_iterator_init(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it, int bank){
168 	memset(it, 0, sizeof(tlv_iterator_t));
169 	it->bank = bank;
170 	it->offset = BTSTACK_TLV_BANK_HEADER_LEN;
171     it->size = self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context);
172 	btstack_tlv_flash_bank_iterator_fetch_tag_len(self, it);
173 }
174 
175 static bool btstack_tlv_flash_bank_iterator_has_next(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it){
176 	UNUSED(self);
177 	return it->tag != 0xffffffff;
178 }
179 
180 static void tlv_iterator_fetch_next(btstack_tlv_flash_bank_t * self, tlv_iterator_t * it){
181 	it->offset += BTSTACK_TLV_ENTRY_HEADER_LEN + btstack_tlv_flash_bank_align_size(self, it->len);
182 
183 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
184 	// skip delete field
185 	it->offset += self->delete_tag_len;
186 #endif
187 
188 	if (it->offset >= it->size) {
189 		it->tag = 0xffffffff;
190 		it->len = 0;
191 		return;
192 	}
193 	btstack_tlv_flash_bank_iterator_fetch_tag_len(self, it);
194 }
195 
196 //
197 
198 // check both banks for headers and pick the one with the higher epoch % 4
199 // @returns bank or -1 if something is invalid
200 static int btstack_tlv_flash_bank_get_latest_bank(btstack_tlv_flash_bank_t * self){
201  	uint8_t header0[BTSTACK_TLV_BANK_HEADER_LEN];
202  	uint8_t header1[BTSTACK_TLV_BANK_HEADER_LEN];
203  	btstack_tlv_flash_bank_read(self, 0, 0, &header0[0], BTSTACK_TLV_BANK_HEADER_LEN);
204  	btstack_tlv_flash_bank_read(self, 1, 0, &header1[0], BTSTACK_TLV_BANK_HEADER_LEN);
205  	int valid0 = memcmp(header0, btstack_tlv_header_magic, BTSTACK_TLV_BANK_HEADER_LEN-1) == 0;
206  	int valid1 = memcmp(header1, btstack_tlv_header_magic, BTSTACK_TLV_BANK_HEADER_LEN-1) == 0;
207 	if (!valid0 && !valid1) return -1;
208 	if ( valid0 && !valid1) return 0;
209 	if (!valid0 &&  valid1) return 1;
210 	int epoch0 = header0[BTSTACK_TLV_BANK_HEADER_LEN-1] & 0x03;
211 	int epoch1 = header1[BTSTACK_TLV_BANK_HEADER_LEN-1] & 0x03;
212 	if (epoch0 == ((epoch1 + 1) & 0x03)) return 0;
213 	if (epoch1 == ((epoch0 + 1) & 0x03)) return 1;
214 	return -1;	// invalid, must not happen
215 }
216 
217 static void btstack_tlv_flash_bank_write_header(btstack_tlv_flash_bank_t * self, int bank, int epoch){
218 	uint8_t header[BTSTACK_TLV_BANK_HEADER_LEN];
219 	memcpy(&header[0], btstack_tlv_header_magic, BTSTACK_TLV_BANK_HEADER_LEN-1);
220 	header[BTSTACK_TLV_BANK_HEADER_LEN-1] = epoch;
221 	btstack_tlv_flash_bank_write(self, bank, 0, header, BTSTACK_TLV_BANK_HEADER_LEN);
222 }
223 
224 /**
225  * @brief Check if erased from offset
226  */
227 static int btstack_tlv_flash_bank_test_erased(btstack_tlv_flash_bank_t * self, int bank, uint32_t offset){
228 	log_info("test erased: bank %u, offset %u", bank, (unsigned int) offset);
229 	uint32_t size = self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context);
230 	uint8_t buffer[16];
231 	uint8_t empty16[16];
232 	memset(empty16, 0xff, sizeof(empty16));
233 	while (offset < size){
234 		uint32_t copy_size = (offset + sizeof(empty16) < size) ? sizeof(empty16) : (size - offset);
235 		btstack_tlv_flash_bank_read(self, bank, offset, buffer, copy_size);
236 		if (memcmp(buffer, empty16, copy_size) != 0) {
237 			log_info("not erased %x - %x", (unsigned int) offset, (unsigned int) (offset + copy_size));
238 			return 0;
239 		}
240 		offset += copy_size;
241 	}
242 	return 1;
243 }
244 
245 /**
246  * @brief erase bank (only if not already erased)
247  */
248 static void btstack_tlv_flash_bank_erase_bank(btstack_tlv_flash_bank_t * self, int bank){
249 	if (btstack_tlv_flash_bank_test_erased(self, bank, 0)){
250 		log_info("bank %u already erased", bank);
251 	} else {
252 		log_info("bank %u not empty, erase bank", bank);
253 		self->hal_flash_bank_impl->erase(self->hal_flash_bank_context, bank);
254 	}
255 }
256 
257 static void btstack_tlv_flash_bank_migrate(btstack_tlv_flash_bank_t * self){
258 
259 	int next_bank = 1 - self->current_bank;
260 	log_info("migrate bank %u -> bank %u", self->current_bank, next_bank);
261 	// erase bank (if needed)
262 	btstack_tlv_flash_bank_erase_bank(self, next_bank);
263 	int next_write_pos = BTSTACK_TLV_BANK_HEADER_LEN;
264 
265 	tlv_iterator_t it;
266 	btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
267 	while (btstack_tlv_flash_bank_iterator_has_next(self, &it)){
268 		// skip deleted entries
269 		if (it.tag) {
270 			uint32_t tag_len = it.len;
271 			uint32_t tag_index = it.offset;
272 
273             bool tag_valid = true;
274 
275 #ifdef ENABLE_TLV_FLASH_WRITE_ONCE
276             // search until end for newer entry of same tag
277             tlv_iterator_t it2;
278             memcpy(&it2, &it, sizeof(tlv_iterator_t));
279             while (btstack_tlv_flash_bank_iterator_has_next(self, &it2)){
280                 if ((it2.offset != it.offset) && (it2.tag == it.tag)){
281                     tag_valid = false;
282                     break;
283                 }
284                 tlv_iterator_fetch_next(self, &it2);
285             }
286             if (tag_valid == false){
287 			    log_info("skip pos %u, tag '%x' as newer entry found at %u", (unsigned int) tag_index, (unsigned int) it.tag,
288                     (unsigned int) it2.offset);
289             }
290 #endif
291 
292             if (tag_valid) {
293 
294                 log_info("migrate pos %u, tag '%x' len %u -> new pos %u",
295                          (unsigned int) tag_index, (unsigned int) it.tag, (unsigned int) tag_len, next_write_pos);
296 
297                 // copy header
298                 uint8_t header_buffer[BTSTACK_TLV_ENTRY_HEADER_LEN];
299                 btstack_tlv_flash_bank_read(self, self->current_bank, tag_index, header_buffer, BTSTACK_TLV_ENTRY_HEADER_LEN);
300                 btstack_tlv_flash_bank_write(self, next_bank, next_write_pos, header_buffer, BTSTACK_TLV_ENTRY_HEADER_LEN);
301                 tag_index      += BTSTACK_TLV_ENTRY_HEADER_LEN;
302                 next_write_pos += BTSTACK_TLV_ENTRY_HEADER_LEN;
303 
304 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
305                 // skip delete field
306                 tag_index      += self->delete_tag_len;
307                 next_write_pos += self->delete_tag_len;
308 #endif
309                 // copy value
310                 int bytes_to_copy = tag_len;
311                 uint8_t copy_buffer[32];
312                 while (bytes_to_copy) {
313                     int bytes_this_iteration = btstack_min(bytes_to_copy, sizeof(copy_buffer));
314                     btstack_tlv_flash_bank_read(self, self->current_bank, tag_index, copy_buffer, bytes_this_iteration);
315                     btstack_tlv_flash_bank_write(self, next_bank, next_write_pos, copy_buffer, bytes_this_iteration);
316                     tag_index += bytes_this_iteration;
317                     next_write_pos += bytes_this_iteration;
318                     bytes_to_copy -= bytes_this_iteration;
319                 }
320             }
321 		}
322 		tlv_iterator_fetch_next(self, &it);
323 	}
324 
325 	// prepare new one
326 	uint8_t epoch_buffer;
327 	btstack_tlv_flash_bank_read(self, self->current_bank, BTSTACK_TLV_BANK_HEADER_LEN-1, &epoch_buffer, 1);
328 	btstack_tlv_flash_bank_write_header(self, next_bank, (epoch_buffer + 1) & 3);
329 	self->current_bank = next_bank;
330 	self->write_offset = next_write_pos;
331 }
332 
333 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
334 static void btstack_tlv_flash_bank_delete_tag_until_offset(btstack_tlv_flash_bank_t * self, uint32_t tag, uint32_t offset){
335 	tlv_iterator_t it;
336 	btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
337 	while (btstack_tlv_flash_bank_iterator_has_next(self, &it) && it.offset < offset){
338 		if (it.tag == tag){
339 			log_info("Erase tag '%x' at position %u", (unsigned int) tag, (unsigned int) it.offset);
340 
341 			// mark entry as invalid
342 			uint32_t zero_value = 0;
343 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
344 			// write delete field after entry header
345 			btstack_tlv_flash_bank_write(self, self->current_bank, it.offset+BTSTACK_TLV_ENTRY_HEADER_LEN, (uint8_t*) &zero_value, sizeof(zero_value));
346 #else
347 			// overwrite tag with zero value
348 			btstack_tlv_flash_bank_write(self, self->current_bank, it.offset, (uint8_t*) &zero_value, sizeof(zero_value));
349 #endif
350 
351 		}
352 		tlv_iterator_fetch_next(self, &it);
353 	}
354 }
355 #endif
356 
357 /**
358  * Get Value for Tag
359  * @param tag
360  * @param buffer
361  * @param buffer_size
362  * @returns size of value
363  */
364 static int btstack_tlv_flash_bank_get_tag(void * context, uint32_t tag, uint8_t * buffer, uint32_t buffer_size){
365 
366 	btstack_tlv_flash_bank_t * self = (btstack_tlv_flash_bank_t *) context;
367 
368 	uint32_t tag_index = 0;
369 	uint32_t tag_len   = 0;
370 	tlv_iterator_t it;
371 	btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
372 	while (btstack_tlv_flash_bank_iterator_has_next(self, &it)){
373 		if (it.tag == tag){
374 			log_info("Found tag '%x' at position %u", (unsigned int) tag, (unsigned int) it.offset);
375 			tag_index = it.offset;
376 			tag_len   = it.len;
377 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
378 			break;
379 #endif
380 		}
381 		tlv_iterator_fetch_next(self, &it);
382 	}
383 	if (tag_index == 0) return 0;
384 	if (!buffer) return tag_len;
385 	int copy_size = btstack_min(buffer_size, tag_len);
386 	uint32_t value_offset = tag_index + BTSTACK_TLV_ENTRY_HEADER_LEN;
387 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
388 	// skip delete field
389 	value_offset += self->delete_tag_len;
390 #endif
391 	btstack_tlv_flash_bank_read(self, self->current_bank, value_offset, buffer, copy_size);
392 	return copy_size;
393 }
394 
395 /**
396  * Store Tag
397  * @param tag
398  * @param data
399  * @param data_size
400  */
401 static int btstack_tlv_flash_bank_store_tag(void * context, uint32_t tag, const uint8_t * data, uint32_t data_size){
402 
403 	btstack_tlv_flash_bank_t * self = (btstack_tlv_flash_bank_t *) context;
404 
405 	// trigger migration if not enough space
406 	uint32_t required_space = BTSTACK_TLV_ENTRY_HEADER_LEN + self->delete_tag_len + data_size;
407 	if (self->write_offset + required_space > self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
408 		btstack_tlv_flash_bank_migrate(self);
409 	}
410 
411 	if (self->write_offset + required_space > self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
412 		log_error("couldn't write entry, not enough space left");
413 		return 2;
414 	}
415 
416 	// prepare entry
417 	uint8_t entry[BTSTACK_TLV_ENTRY_HEADER_LEN];
418 	big_endian_store_32(entry, 0, tag);
419 	big_endian_store_32(entry, 4, data_size);
420 
421 	log_info("write '%" PRIx32 "', len %" PRIu32 " at %" PRIx32, tag, data_size, self->write_offset);
422 
423 	uint32_t value_offset = self->write_offset + BTSTACK_TLV_ENTRY_HEADER_LEN;
424 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
425 	// skip delete field
426 	value_offset += self->delete_tag_len;
427 #endif
428 
429 	// write value first
430 	btstack_tlv_flash_bank_write(self, self->current_bank, value_offset, data, data_size);
431 
432 	// then entry
433 	btstack_tlv_flash_bank_write(self, self->current_bank, self->write_offset, entry, sizeof(entry));
434 
435 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
436 	// overwrite old entries (if exists)
437 	btstack_tlv_flash_bank_delete_tag_until_offset(self, tag, self->write_offset);
438 #endif
439 
440 	// done
441 	self->write_offset += sizeof(entry) + btstack_tlv_flash_bank_align_size(self, data_size);
442 
443 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
444 	// skip delete field
445 	self->write_offset += self->delete_tag_len;
446 #endif
447 
448 	return 0;
449 }
450 
451 /**
452  * Delete Tag
453  * @param tag
454  */
455 static void btstack_tlv_flash_bank_delete_tag(void * context, uint32_t tag){
456 #ifdef ENABLE_TLV_FLASH_WRITE_ONCE
457     btstack_tlv_flash_bank_store_tag(context, tag, NULL, 0);
458 #else
459     btstack_tlv_flash_bank_t * self = (btstack_tlv_flash_bank_t *) context;
460 	btstack_tlv_flash_bank_delete_tag_until_offset(self, tag, self->write_offset);
461 #endif
462 }
463 
464 static const btstack_tlv_t btstack_tlv_flash_bank = {
465 	/* int  (*get_tag)(..);     */ &btstack_tlv_flash_bank_get_tag,
466 	/* int (*store_tag)(..);    */ &btstack_tlv_flash_bank_store_tag,
467 	/* void (*delete_tag)(v..); */ &btstack_tlv_flash_bank_delete_tag,
468 };
469 
470 /**
471  * Init Tag Length Value Store
472  */
473 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){
474 
475 	self->hal_flash_bank_impl    = hal_flash_bank_impl;
476 	self->hal_flash_bank_context = hal_flash_bank_context;
477 	self->delete_tag_len = 0;
478 
479 #ifdef ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD
480 	if (hal_flash_bank_impl->get_alignment(hal_flash_bank_context) > 8){
481 		log_error("Flash alignment > 8 with ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD not supported");
482 		return NULL;
483 	}
484 	// set delete tag len
485 	uint32_t alignment = self->hal_flash_bank_impl->get_alignment(self->hal_flash_bank_context);
486 	self->delete_tag_len = (uint8_t) btstack_max(4, alignment);
487 	log_info("delete tag len %u", self->delete_tag_len);
488 #endif
489 
490 	// try to find current bank
491 	self->current_bank = btstack_tlv_flash_bank_get_latest_bank(self);
492 	log_info("found bank %d", self->current_bank);
493 	if (self->current_bank >= 0){
494 
495 		// find last entry and write offset
496 		tlv_iterator_t it;
497 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
498 		uint32_t last_tag = 0;
499 		uint32_t last_offset = 0;
500 #endif
501         btstack_tlv_flash_bank_iterator_init(self, &it, self->current_bank);
502 		while (btstack_tlv_flash_bank_iterator_has_next(self, &it)){
503 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
504 			last_tag = it.tag;
505 			last_offset = it.offset;
506 #endif
507 			tlv_iterator_fetch_next(self, &it);
508 		}
509 		self->write_offset = it.offset;
510 
511 		if (self->write_offset <= self->hal_flash_bank_impl->get_size(self->hal_flash_bank_context)){
512 
513 #ifndef ENABLE_TLV_FLASH_WRITE_ONCE
514 			// delete older instances of last_tag
515 			// this handles the unlikely case where MCU did reset after new value + header was written but before delete did complete
516 			if (last_tag){
517 				btstack_tlv_flash_bank_delete_tag_until_offset(self, last_tag, last_offset);
518 			}
519 #endif
520 
521 			// verify that rest of bank is empty
522 			// this handles the unlikely case where MCU did reset after new value was written, but not the tag
523 			if (!btstack_tlv_flash_bank_test_erased(self, self->current_bank, self->write_offset)){
524 				log_info("Flash not empty after last found tag -> migrate");
525 				btstack_tlv_flash_bank_migrate(self);
526 			} else {
527 				log_info("Flash clean after last found tag");
528 			}
529 		} else {
530 			// failure!
531 			self->current_bank = -1;
532 		}
533 	}
534 
535 	if (self->current_bank < 0) {
536 		btstack_tlv_flash_bank_erase_bank(self, 0);
537 		self->current_bank = 0;
538 		btstack_tlv_flash_bank_write_header(self, self->current_bank, 0);	// epoch = 0;
539 		self->write_offset = BTSTACK_TLV_BANK_HEADER_LEN;
540 	}
541 
542 	log_info("write offset %" PRIx32, self->write_offset);
543 	return &btstack_tlv_flash_bank;
544 }
545 
546