aboutsummaryrefslogtreecommitdiffstats
path: root/mpm/tools/tlv_eeprom/tlv_eeprom.c
blob: 8b2e2d9c0d78fcd7048268b9aa1c620f52f552ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Copyright 2019 Ettus Research, a National Instruments Brand
 */

#include <string.h>
#include "tlv_eeprom.h"

struct tlv_eeprom *tlv_eeprom_init(void *data)
{
	struct tlv_eeprom *e = data;

	return e;
}

void tlv_eeprom_seal(struct tlv_eeprom *e, uint32_t magic, size_t len)
{
	e->magic = magic;
	e->size = len;
	e->crc = tlv_eeprom_crc(e);
}

int tlv_eeprom_validate(const struct tlv_eeprom *e, uint32_t magic)
{
	uint32_t crc;

	if (e->magic != magic)
		return -1;

	if (e->size > TLV_EEPROM_SIZE)
		return -2;

	crc = tlv_eeprom_crc(e);
	if (e->crc != crc)
		return -3;

	return 0;
}

struct tlv {
	uint8_t tag;
	uint8_t len;
	uint8_t val[0];
};


static inline const struct tlv *tlv_next(const struct tlv *tlv, const void *end)
{
	const void *p = &tlv->val;

	p += tlv->len;
	if (p >= end)
		return NULL;
	return p;
}

static inline const struct tlv *tlv_find(const struct tlv *tlv,
					 const void *end, uint8_t tag)
{
	do {
		if (tlv->tag == tag)
			break;
	} while ((tlv = tlv_next(tlv, end)));

	return tlv;
}

void tlv_for_each(const void *buf, size_t bufsz,
		  void (*fn)(uint8_t tag, uint8_t len, const void *val))
{
	const struct tlv *tlv = buf;

	do {
		fn(tlv->tag, tlv->len, tlv->val);
	} while ((tlv = tlv_next(tlv, buf + bufsz)));
}

const void *tlv_lookup(const void *buf, size_t bufsz, uint8_t tag)
{
	const struct tlv *tlv;

	tlv = tlv_find(buf, buf + bufsz, tag);
	if (!tlv)
		return tlv;

	return tlv->val;
}

size_t tlv_write(void *buf, uint8_t tag, uint8_t len, const void *val)
{
	struct tlv *tlv = buf;

	tlv->tag = tag;
	tlv->len = len;
	memcpy(tlv->val, val, len);

	return sizeof(*tlv) + len;
}