summaryrefslogtreecommitdiff
path: root/common/nvmem_vars.c
blob: 92da5d2981edb76a2c2f3979e763bfe4152f2e53 (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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
 * Copyright 2016 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "common.h"
#include "nvmem.h"
#include "nvmem_vars.h"
#include "printf.h"
#include "util.h"

/****************************************************************************/
/* Obtain/release a RAM copy of the persistent variable store */

/*
 * NOTE: It would be nice to allocate this at need, but shared memory is
 * currently all or nothing and it's used elsewhere when writing to flash, so
 * we have to allocate it statically until/unless that changes.
 */
static uint8_t rbuf[CONFIG_FLASH_NVMEM_VARS_USER_SIZE];
static int rbuf_in_use;

test_mockable_static
void release_local_copy(void)
{
	rbuf_in_use = 0;
}

test_mockable_static
int get_local_copy(void)
{
	int rv;

	if (rbuf_in_use)
		return EC_SUCCESS;

	rbuf_in_use = 1;

	rv = nvmem_read(0, CONFIG_FLASH_NVMEM_VARS_USER_SIZE,
			rbuf, CONFIG_FLASH_NVMEM_VARS_USER_NUM);
	if (rv)
		release_local_copy();

	return rv;
}

/****************************************************************************/
/* Implementation notes
 *
 * The data_ member of struct tuple is simply the key and val blobs
 * concatenated together.
 *
 * We store the variable entries in flash (and RAM) using the struct tuple
 * defined in nvmem_vars.h. The entries are written sequentially with no
 * padding, starting at offset 0 of the CONFIG_FLASH_NVMEM_VARS_USER_NUM user
 * region. A single uint8_t zero byte will ALWAYS follow the valid entries.
 * Since valid entries have nonzero key_len, we can always detect the presence
 * of valid entries.
 *
 * A valid entry has both key_len and val_len between 1 and 255. The following
 * bytes represent these tuples: <"A","ab">, <"B","cde">:
 *
 *   Offset  Content   Meaning
 *    0      0x01      length of key
 *    1      0x02      length of val
 *    2      0x00      variable flags (unused at present)
 *    3      0x41      'A' (key)
 *    4      0x61      'a' (val byte 1)
 *    5      0x62      'b' (val byte 2)
 *    6      0x01      length of key
 *    7      0x03      length of val
 *    8      0x00      variable flags (unused at present)
 *    9      0x42      'B' (key)
 *    10     0x63      'c' (val byte 1)
 *    11     0x64      'd' (val byte 2)
 *    12     0x65      'e' (val byte 3)
 *    13     0x00      End of variables
 *
 * Note that the keys and values are not null-terminated since they're not
 * strings, just binary blobs. The length of each entry is the size of the
 * struct tuple header, plus the length of its key and value blobs.
 *
 * The .flags field is not currently used (and so is set to zero). It could be
 * used in the future to for per-variable attributes, such as read-only,
 * clear-on-reset, extended-length value, etc.
 */

/****************************************************************************/
/* Helper functions */

/* Return true if the tuple at rbuf+idx matches the key */
static int match_key_at(uint32_t idx, const uint8_t *key, uint8_t key_len)
{
	struct tuple *tuple = (struct tuple *)(rbuf + idx);
	uint32_t i, max_len;
	uint8_t diffs;

	/* Don't try to look past the 0 at the end of the user region */
	max_len = MIN(key_len, CONFIG_FLASH_NVMEM_VARS_USER_SIZE - idx - 1);

	/* Do constant-time comparision, since AP sets key_len to look for */
	diffs = max_len ^ key_len;
	diffs |= tuple->key_len ^ key_len;
	for (i = 0; i < max_len; i++)
		diffs |=  tuple->data_[i] ^ key[i];

	return !diffs;
}

/*
 * Find the start of the next tuple in rbuf. Return false if there isn't one.
 * The idx arg tracks where to start looking and where the next tuple was
 * expected to be found.
 */
static int next_tuple(uint32_t *idx)
{
	struct tuple *tuple = (struct tuple *)(rbuf + *idx);

	/* Not at a valid tuple now, so there aren't any more */
	if (!tuple->key_len)
		return 0;

	/* Advance to the next one */
	*idx += sizeof(struct tuple) + tuple->key_len + tuple->val_len;
	tuple = (struct tuple *)(rbuf + *idx);

	/* Do we have one or not? */
	return tuple->key_len;
}

/*
 * Look for the key in rbuf. If a match is found, set the index to the start of
 * the tuple and return true. If the key is not found, set the index to the
 * location where a new tuple should be added (0 if no tuples exist at all,
 * else at the '\0' at the end of the tuples) and return false.
 */
test_mockable_static
int getvar_idx(uint32_t *idx, const uint8_t *key, uint8_t key_len)
{
	uint32_t i = *idx;

	do {
		if (match_key_at(i, key, key_len)) {
			*idx = i;
			return 1;
		}
	} while (next_tuple(&i));

	*idx = i;
	return 0;
}

static inline int bogus_blob(const uint8_t *blob, uint8_t blob_len)
{
	return !blob || !blob_len;
}

/****************************************************************************/
/* API functions */

/* This MUST be called first. The internal functions assume valid entries */
int initvars(void)
{
	struct tuple *tuple;
	int rv, i, len;

	rv = get_local_copy();
	if (rv != EC_SUCCESS)
		return rv;

	for (i = len = 0; /* FOREVER */ 1; i += len) {
		tuple = (struct tuple *)(rbuf + i);

		/* Zero key_len indicates end of tuples, we're done */
		if (!tuple->key_len)
			break;

		/* Empty values are not allowed */
		if (!tuple->val_len)
			goto fixit;

		/* See how big the tuple is */
		len = sizeof(struct tuple) + tuple->key_len + tuple->val_len;

		/* Oops, it's off the end (leave one byte for final 0) */
		if (i + len >= CONFIG_FLASH_NVMEM_VARS_USER_SIZE)
			goto fixit;
	}

	/* Found the end of variables. Now make sure the rest is all 0xff. */
	for (i++ ; i < CONFIG_FLASH_NVMEM_VARS_USER_SIZE; i++)
		if (rbuf[i] != 0xff)
			goto fixit;

	release_local_copy();
	return EC_SUCCESS;

fixit:
	/* No variables */
	rbuf[0] = 0;
	/* Everything else is 0xff */
	memset(rbuf + 1, 0xff, CONFIG_FLASH_NVMEM_VARS_USER_SIZE - 1);

	return writevars();
}

const struct tuple *getvar(const uint8_t *key, uint8_t key_len)
{
	uint32_t i = 0;

	if (bogus_blob(key, key_len))
		return 0;

	if (get_local_copy() != EC_SUCCESS)
		return 0;

	if (!getvar_idx(&i, key, key_len))
		return 0;

	return (const struct tuple *)(rbuf + i);
}

const uint8_t *tuple_key(const struct tuple *t)
{
	return t->data_;
}

const uint8_t *tuple_val(const struct tuple *t)
{
	return t->data_ + t->key_len;
}

int setvar(const uint8_t *key, uint8_t key_len,
	   const uint8_t *val, uint8_t val_len)
{
	struct tuple *tuple;
	int rv, i, j;

	if (bogus_blob(key, key_len))
		return EC_ERROR_INVAL;

	rv = get_local_copy();
	if (rv != EC_SUCCESS)
		return rv;

	i = 0;
	if (getvar_idx(&i, key, key_len)) {
		/* Found the match at position i */
		j = i;
		if (next_tuple(&j)) {
			/*
			 * Now j is the start of the tuple after ours. Delete
			 * our entry by shifting left from there to the end of
			 * rbuf, so that it covers ours up.
			 *
			 * Before:
			 *            i        j
			 *   <foo,bar><KEY,VAL><hey,splat>0
			 *
			 * After:
			 *            i
			 *   <foo,bar><hey,splat>0...
			 */
			memmove(rbuf + i, rbuf + j,
				CONFIG_FLASH_NVMEM_VARS_USER_SIZE - j);
			/* Advance i to point to the end of all tuples */
			while (next_tuple(&i))
				;
		}
		/* Whether we found a match or not, it's not there now */
	}
	/*
	 * Now i is where the new tuple should be written.
	 *
	 * Either this:
	 *                       i
	 *   <foo,bar><hey,splat>0
	 *
	 * or there are no tuples at all and i == 0
	 *
	 */

	/* If there's no value to save, we're done. */
	if (bogus_blob(val, val_len))
		goto done;

	/*
	 * We'll always write the updated entry at the end of any existing
	 * tuples, and we mark the end with an additional 0. Make sure all that
	 * will all fit. If it doesn't, we've already removed the previous
	 * entry but we still need to mark the end.
	 */
	if (i + sizeof(struct tuple) + key_len + val_len + 1 >
	    CONFIG_FLASH_NVMEM_VARS_USER_SIZE) {
		rv = EC_ERROR_OVERFLOW;
		goto done;
	}

	/* write the tuple */
	tuple = (struct tuple *)(rbuf + i);
	tuple->key_len = key_len;
	tuple->val_len = val_len;
	tuple->flags = 0;			/* UNUSED, set to zero */
	memcpy(tuple->data_, key, key_len);
	memcpy(tuple->data_ + key_len, val, val_len);
	/* move past it */
	next_tuple(&i);

done:
	/* mark the end */
	rbuf[i++] = 0;
	/* erase the rest */
	memset(rbuf + i, 0xff, CONFIG_FLASH_NVMEM_VARS_USER_SIZE - i);

	return rv;
}

int writevars(void)
{
	int rv;

	if (!rbuf_in_use)
		return EC_SUCCESS;

	rv = nvmem_write(0, CONFIG_FLASH_NVMEM_VARS_USER_SIZE,
			 rbuf, CONFIG_FLASH_NVMEM_VARS_USER_NUM);
	if (rv != EC_SUCCESS)
		return rv;

	rv = nvmem_commit();
	if (rv != EC_SUCCESS)
		return rv;

	release_local_copy();

	return rv;
}

/****************************************************************************/
#ifdef TEST_BUILD
#include "console.h"

static void print_blob(const uint8_t *blob, int blob_len)
{
	int i;

	for (i = 0; i < blob_len; i++)
		ccprintf("%c", isprint(blob[i]) ? blob[i] : '.');
}

static int command_get(int argc, char **argv)
{
	const struct tuple *tuple;

	if (argc != 2)
		return EC_ERROR_PARAM_COUNT;

	tuple = getvar(argv[1], strlen(argv[1]));
	if (!tuple)
		return EC_SUCCESS;

	print_blob(tuple_val(tuple), tuple->val_len);
	ccprintf("\n");
	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(get, command_get,
			"VARIABLE",
			"Show the value of the specified variable");

static int command_set(int argc, char **argv)
{
	int rc;

	if (argc != 2 && argc != 3)
		return EC_ERROR_PARAM_COUNT;

	if (argc == 2)
		rc =  setvar(argv[1], strlen(argv[1]), 0, 0);
	else
		rc =  setvar(argv[1], strlen(argv[1]),
			     argv[2], strlen(argv[2]));
	if (rc)
		return rc;

	return writevars();
}
DECLARE_CONSOLE_COMMAND(set, command_set,
			"VARIABLE [VALUE]",
			"Set/clear the value of the specified variable");

static int command_print(int argc, char **argv)
{
	const struct tuple *tuple;
	int rv, i = 0;

	rv = get_local_copy();
	if (rv)
		return rv;

	tuple = (const struct tuple *)(rbuf + i);
	if (!tuple->key_len)
		return EC_SUCCESS;

	do {
		tuple = (const struct tuple *)(rbuf + i);
		print_blob(tuple_key(tuple), tuple->key_len);
		ccprintf("=");
		print_blob(tuple_val(tuple), tuple->val_len);
		ccprintf("\n");
	} while (next_tuple(&i));

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(print, command_print,
			"",
			"Print all defined variables");

static int command_dump(int argc, char **argv)
{
	int i, rv;

	rv = get_local_copy();
	if (rv)
		return rv;

	for (i = 0; i < CONFIG_FLASH_NVMEM_VARS_USER_SIZE; i++)
		ccprintf(" %02x", rbuf[i]);
	ccprintf("\n");

	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(dump, command_dump,
			"",
			"Dump the variable memory");
#endif