1 /*
2  * Copyright (c) 2017-2023 Nordic Semiconductor ASA
3  * Copyright (c) 2015 Runtime Inc
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #ifndef __FCB_PRIV_H_
9 #define __FCB_PRIV_H_
10 
11 #ifdef __cplusplus
12 extern "C" {
13 #endif
14 
15 #define FCB_CRC_SZ	sizeof(uint8_t)
16 #define FCB_TMP_BUF_SZ	32
17 
18 #define FCB_ID_GT(a, b) (((int16_t)(a) - (int16_t)(b)) > 0)
19 
20 #define MK32(val) ((((uint32_t)(val)) << 24) |			\
21 		   (((uint32_t)((val) & 0xff)) << 16) |		\
22 		   (((uint32_t)((val) & 0xff)) << 8) |		\
23 		   (((uint32_t)((val) & 0xff))))
24 
25 
26 /* @brief Gets magic value in flash formatted version
27  *
28  * Magic, the fcb->f_magic, prior to being written to flash, is xored with
29  * binary inversion of fcb->f_erase_value to avoid it matching a 4 consecutive
30  * bytes of flash erase value, which is used to recognize end of records,
31  * by accident. Only the value of 0xFFFFFFFF will be always written as
32  * 4 bytes of erase value.
33  *
34  * @param fcb pointer to initialized fcb structure
35  *
36  * @return uin32_t formatted magic value
37  */
fcb_flash_magic(const struct fcb * fcb)38 static inline uint32_t fcb_flash_magic(const struct fcb *fcb)
39 {
40 	const uint8_t ev = fcb->f_erase_value;
41 
42 	return (fcb->f_magic ^ ~MK32(ev));
43 }
44 
45 struct fcb_disk_area {
46 	uint32_t fd_magic;
47 	uint8_t fd_ver;
48 	uint8_t _pad;
49 	uint16_t fd_id;
50 };
51 
52 int fcb_put_len(const struct fcb *fcb, uint8_t *buf, uint16_t len);
53 int fcb_get_len(const struct fcb *fcb, uint8_t *buf, uint16_t *len);
54 
fcb_len_in_flash(struct fcb * fcb,uint16_t len)55 static inline int fcb_len_in_flash(struct fcb *fcb, uint16_t len)
56 {
57 	if (fcb->f_align <= 1U) {
58 		return len;
59 	}
60 	return (len + (fcb->f_align - 1U)) & ~(fcb->f_align - 1U);
61 }
62 
63 const struct flash_area *fcb_open_flash(const struct fcb *fcb);
64 uint8_t fcb_get_align(const struct fcb *fcb);
65 int fcb_erase_sector(const struct fcb *fcb, const struct flash_sector *sector);
66 
67 int fcb_getnext_in_sector(struct fcb *fcb, struct fcb_entry *loc);
68 struct flash_sector *fcb_getnext_sector(struct fcb *fcb,
69 					struct flash_sector *sector);
70 int fcb_getnext_nolock(struct fcb *fcb, struct fcb_entry *loc);
71 
72 int fcb_elem_info(struct fcb *fcb, struct fcb_entry *loc);
73 int fcb_elem_endmarker(struct fcb *fcb, struct fcb_entry *loc, uint8_t *crc8p);
74 
75 int fcb_sector_hdr_init(struct fcb *fcb, struct flash_sector *sector, uint16_t id);
76 int fcb_sector_hdr_read(struct fcb *fcb, struct flash_sector *sector,
77 			struct fcb_disk_area *fdap);
78 
79 #ifdef __cplusplus
80 }
81 #endif
82 
83 #endif /* __FCB_PRIV_H_ */
84