xref: /aosp_15_r20/external/coreboot/src/security/vboot/vbnv.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 
3 #include <assert.h>
4 #include <string.h>
5 #include <types.h>
6 #include <security/vboot/misc.h>
7 #include <security/vboot/vbnv.h>
8 #include <security/vboot/vbnv_layout.h>
9 #include <vb2_api.h>
10 
11 static bool vbnv_initialized;
12 
13 /* Return CRC-8 of the data, using x^8 + x^2 + x + 1 polynomial. */
crc8_vbnv(const uint8_t * data,int len)14 static uint8_t crc8_vbnv(const uint8_t *data, int len)
15 {
16 	unsigned int crc = 0;
17 	int i, j;
18 
19 	for (j = len; j; j--, data++) {
20 		crc ^= (*data << 8);
21 		for (i = 8; i; i--) {
22 			if (crc & 0x8000)
23 				crc ^= (0x1070 << 3);
24 			crc <<= 1;
25 		}
26 	}
27 
28 	return (uint8_t)(crc >> 8);
29 }
30 
vbnv_reset(uint8_t * vbnv_copy)31 void vbnv_reset(uint8_t *vbnv_copy)
32 {
33 	memset(vbnv_copy, 0, VBOOT_VBNV_BLOCK_SIZE);
34 }
35 
36 /* Verify VBNV header and checksum. */
verify_vbnv(uint8_t * vbnv_copy)37 int verify_vbnv(uint8_t *vbnv_copy)
38 {
39 	return (HEADER_SIGNATURE == (vbnv_copy[HEADER_OFFSET] & HEADER_MASK)) &&
40 		(crc8_vbnv(vbnv_copy, CRC_OFFSET) == vbnv_copy[CRC_OFFSET]);
41 }
42 
43 /* Re-generate VBNV checksum. */
regen_vbnv_crc(uint8_t * vbnv_copy)44 void regen_vbnv_crc(uint8_t *vbnv_copy)
45 {
46 	vbnv_copy[CRC_OFFSET] = crc8_vbnv(vbnv_copy, CRC_OFFSET);
47 }
48 
49 /*
50  * Read VBNV data from configured storage backend.
51  * If VBNV verification fails, reset the vbnv copy.
52  */
read_vbnv(uint8_t * vbnv_copy)53 void read_vbnv(uint8_t *vbnv_copy)
54 {
55 	if (CONFIG(VBOOT_VBNV_CMOS))
56 		read_vbnv_cmos(vbnv_copy);
57 	else if (CONFIG(VBOOT_VBNV_FLASH))
58 		read_vbnv_flash(vbnv_copy);
59 	else
60 		dead_code();
61 
62 	/* Check data for consistency */
63 	if (!verify_vbnv(vbnv_copy))
64 		vbnv_reset(vbnv_copy);
65 }
66 
67 /*
68  * Write VBNV data to configured storage backend.
69  * This assumes that the caller has updated the CRC already.
70  */
save_vbnv(const uint8_t * vbnv_copy)71 void save_vbnv(const uint8_t *vbnv_copy)
72 {
73 	if (CONFIG(VBOOT_VBNV_CMOS))
74 		save_vbnv_cmos(vbnv_copy);
75 	else if (CONFIG(VBOOT_VBNV_FLASH))
76 		save_vbnv_flash(vbnv_copy);
77 	else
78 		dead_code();
79 }
80 
81 /* Read the USB Device Controller(UDC) enable flag from VBNV. */
vbnv_udc_enable_flag(void)82 int vbnv_udc_enable_flag(void)
83 {
84 	struct vb2_context *ctx = vboot_get_context();
85 	return (ctx->nvdata[DEV_FLAGS_OFFSET] & DEV_ENABLE_UDC) ? 1 : 0;
86 }
87 
vbnv_init(void)88 void vbnv_init(void)
89 {
90 	struct vb2_context *ctx;
91 
92 	/* NV data already initialized and read */
93 	if (vbnv_initialized)
94 		return;
95 
96 	ctx = vboot_get_context();
97 	if (CONFIG(VBOOT_VBNV_CMOS))
98 		vbnv_init_cmos(ctx->nvdata);
99 	read_vbnv(ctx->nvdata);
100 	vbnv_initialized = true;
101 }
102