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