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 #include "fcb_test.h"
9 
ZTEST(fcb_test_with_2sectors_set,test_fcb_append_too_big)10 ZTEST(fcb_test_with_2sectors_set, test_fcb_append_too_big)
11 {
12 		struct fcb *fcb;
13 		int rc;
14 		int overhead;
15 		uint32_t len;
16 		struct fcb_entry elem_loc;
17 		const uint8_t max_length_field_len = 2;
18 
19 		fcb = &test_fcb;
20 
21 		/*
22 		 * An entry in the FCB has the following structure:
23 		 * | fcb_disk_area | length | data | CRC |
24 		 *
25 		 * The length is encoded in 1-2 bytes. All these entries
26 		 * have to abide flash alignment constraints.
27 		 *
28 		 * Thus, the max element which fits inside sector is
29 		 * (M / fcb->f_align) * fcb->f_align, where / is integer
30 		 * division and M = sector size - O, with O being the sum
31 		 * of all overhead elements' lengths in flash, i.e.
32 		 *
33 		 * O = fcb_len_in_flash(fcb, FCB_CRC_SZ)
34 		 *    + fcb_len_in_flash(fcb, max_length_field_len)
35 		 *    + fcb_len_in_flash(fcb, sizeof(struct fcb_disk_area))
36 		 */
37 		len = MIN(FCB_MAX_LEN
38 			     + fcb_len_in_flash(fcb, sizeof(struct fcb_disk_area))
39 			     + fcb_len_in_flash(fcb, FCB_CRC_SZ)
40 			     + fcb_len_in_flash(fcb, max_length_field_len)
41 			, fcb->f_active.fe_sector->fs_size);
42 
43 
44 		rc = fcb_append(fcb, len, &elem_loc);
45 		zassert_true(rc != 0,
46 			     "fcb_append call should fail for too big entry");
47 
48 		len--;
49 		rc = fcb_append(fcb, len, &elem_loc);
50 		zassert_true(rc != 0,
51 			     "fcb_append call should fail for too big entry");
52 
53 		len -=  fcb_len_in_flash(fcb, sizeof(struct fcb_disk_area));
54 		rc = fcb_append(fcb, len, &elem_loc);
55 		zassert_true(rc != 0,
56 			     "fcb_append call should fail for too big entry");
57 
58 		overhead = fcb_len_in_flash(fcb, sizeof(struct fcb_disk_area))
59 			   + fcb_len_in_flash(fcb, max_length_field_len)
60 			   + fcb_len_in_flash(fcb, FCB_CRC_SZ);
61 
62 		len = MIN(FCB_MAX_LEN, fcb->f_active.fe_sector->fs_size - overhead);
63 		len = fcb->f_align * (len / fcb->f_align);
64 
65 		rc = fcb_append(fcb, len, &elem_loc);
66 		zassert_true(rc == 0, "fcb_append call failure");
67 
68 		rc = fcb_append_finish(fcb, &elem_loc);
69 		zassert_true(rc == 0, "fcb_append call failure");
70 
71 		rc = fcb_elem_info(fcb, &elem_loc);
72 		zassert_true(rc == 0, "fcb_elem_info call failure");
73 		zassert_true(elem_loc.fe_data_len == len,
74 		"entry length fetched should match length of appended entry");
75 }
76