1 /*-
2  * Copyright (c) 2015-2016 Landon Fuller <landonf@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  *
16  * NO WARRANTY
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGES.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/endian.h>
34 
35 #ifdef _KERNEL
36 #include <sys/param.h>
37 #include <sys/ctype.h>
38 #include <sys/malloc.h>
39 #include <sys/systm.h>
40 
41 #include <machine/_inttypes.h>
42 #else /* !_KERNEL */
43 #include <ctype.h>
44 #include <errno.h>
45 #include <inttypes.h>
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #endif /* _KERNEL */
51 
52 #include "bhnd_nvram_map.h"
53 
54 #include "bhnd_nvram_private.h"
55 #include "bhnd_nvram_datavar.h"
56 
57 #include "bhnd_nvram_data_spromvar.h"
58 
59 /*
60  * BHND SPROM NVRAM data class
61  *
62  * The SPROM data format is a fixed-layout, non-self-descriptive binary format,
63  * used on Broadcom wireless and wired adapters, that provides a subset of the
64  * variables defined by Broadcom SoC NVRAM formats.
65  */
66 
67 static const bhnd_sprom_layout  *bhnd_nvram_sprom_get_layout(uint8_t sromrev);
68 
69 static int			 bhnd_nvram_sprom_ident(
70 				     struct bhnd_nvram_io *io,
71 				     const bhnd_sprom_layout **ident);
72 
73 static int			 bhnd_nvram_sprom_write_var(
74 				     bhnd_sprom_opcode_state *state,
75 				     bhnd_sprom_opcode_idx_entry *entry,
76 				     bhnd_nvram_val *value,
77 				     struct bhnd_nvram_io *io);
78 
79 static int			 bhnd_nvram_sprom_read_var(
80 				     struct bhnd_sprom_opcode_state *state,
81 				     struct bhnd_sprom_opcode_idx_entry *entry,
82 				     struct bhnd_nvram_io *io,
83 				     union bhnd_nvram_sprom_storage *storage,
84 				     bhnd_nvram_val *val);
85 
86 static int			 bhnd_nvram_sprom_write_offset(
87 				     const struct bhnd_nvram_vardefn *var,
88 				     struct bhnd_nvram_io *data,
89 				     bhnd_nvram_type type, size_t offset,
90 				     uint32_t mask, int8_t shift,
91 				     uint32_t value);
92 
93 static int			 bhnd_nvram_sprom_read_offset(
94 				     const struct bhnd_nvram_vardefn *var,
95 				     struct bhnd_nvram_io *data,
96 				     bhnd_nvram_type type, size_t offset,
97 				     uint32_t mask, int8_t shift,
98 				     uint32_t *value);
99 
100 static bool			 bhnd_sprom_is_external_immutable(
101 				     const char *name);
102 
103 BHND_NVRAM_DATA_CLASS_DEFN(sprom, "Broadcom SPROM",
104     BHND_NVRAM_DATA_CAP_DEVPATHS, sizeof(struct bhnd_nvram_sprom))
105 
106 #define	SPROM_COOKIE_TO_VID(_cookie)	\
107 	(((struct bhnd_sprom_opcode_idx_entry *)(_cookie))->vid)
108 
109 #define	SPROM_COOKIE_TO_NVRAM_VAR(_cookie)	\
110 	bhnd_nvram_get_vardefn(SPROM_COOKIE_TO_VID(_cookie))
111 
112 /**
113  * Read the magic value from @p io, and verify that it matches
114  * the @p layout's expected magic value.
115  *
116  * If @p layout does not defined a magic value, @p magic is set to 0x0
117  * and success is returned.
118  *
119  * @param	io	An I/O context mapping the SPROM data to be identified.
120  * @param	layout	The SPROM layout against which @p io should be verified.
121  * @param[out]	magic	On success, the SPROM magic value.
122  *
123  * @retval 0		success
124  * @retval non-zero	If checking @p io otherwise fails, a regular unix
125  *			error code will be returned.
126  */
127 static int
128 bhnd_nvram_sprom_check_magic(struct bhnd_nvram_io *io,
129     const bhnd_sprom_layout *layout, uint16_t *magic)
130 {
131 	int error;
132 
133 	/* Skip if layout does not define a magic value */
134 	if (layout->flags & SPROM_LAYOUT_MAGIC_NONE)
135 		return (0);
136 
137 	/* Read the magic value */
138 	error = bhnd_nvram_io_read(io, layout->magic_offset, magic,
139 	    sizeof(*magic));
140 	if (error)
141 		return (error);
142 
143 	*magic = le16toh(*magic);
144 
145 	/* If the signature does not match, skip to next layout */
146 	if (*magic != layout->magic_value)
147 		return (ENXIO);
148 
149 	return (0);
150 }
151 
152 /**
153  * Attempt to identify the format of the SPROM data mapped by @p io.
154  *
155  * The SPROM data format does not provide any identifying information at a
156  * known offset, instead requiring that we iterate over the known SPROM image
157  * sizes until we are able to compute a valid checksum (and, for later
158  * revisions, validate a signature at a revision-specific offset).
159  *
160  * @param	io	An I/O context mapping the SPROM data to be identified.
161  * @param[out]	ident	On success, the identified SPROM layout.
162  *
163  * @retval 0		success
164  * @retval non-zero	If identifying @p io otherwise fails, a regular unix
165  *			error code will be returned.
166  */
167 static int
168 bhnd_nvram_sprom_ident(struct bhnd_nvram_io *io,
169     const bhnd_sprom_layout **ident)
170 {
171 	uint8_t	crc;
172 	size_t	crc_errors;
173 	size_t	nbytes;
174 	int	error;
175 
176 	crc = BHND_NVRAM_CRC8_INITIAL;
177 	crc_errors = 0;
178 	nbytes = 0;
179 
180 	/* We iterate the SPROM layouts smallest to largest, allowing us to
181 	 * perform incremental checksum calculation */
182 	for (size_t i = 0; i < bhnd_sprom_num_layouts; i++) {
183 		const bhnd_sprom_layout	*layout;
184 		u_char			 buf[512];
185 		size_t			 nread;
186 		uint16_t		 magic;
187 		uint8_t			 srevcrc[2];
188 		uint8_t			 srev;
189 		bool			 crc_valid;
190 		bool			 have_magic;
191 
192 		layout = &bhnd_sprom_layouts[i];
193 
194 		have_magic = true;
195 		if ((layout->flags & SPROM_LAYOUT_MAGIC_NONE))
196 			have_magic = false;
197 
198 		/*
199 		 * Read image data and update CRC (errors are reported
200 		 * after the signature check)
201 		 *
202 		 * Layout instances must be ordered from smallest to largest by
203 		 * the nvram_map compiler, allowing us to incrementally update
204 		 * our CRC.
205 		 */
206 		if (nbytes > layout->size)
207 			BHND_NV_PANIC("SPROM layout defined out-of-order");
208 
209 		nread = layout->size - nbytes;
210 
211 		while (nread > 0) {
212 			size_t nr;
213 
214 			nr = bhnd_nv_ummin(nread, sizeof(buf));
215 
216 			if ((error = bhnd_nvram_io_read(io, nbytes, buf, nr)))
217 				return (error);
218 
219 			crc = bhnd_nvram_crc8(buf, nr, crc);
220 			crc_valid = (crc == BHND_NVRAM_CRC8_VALID);
221 			if (!crc_valid)
222 				crc_errors++;
223 
224 			nread -= nr;
225 			nbytes += nr;
226 		}
227 
228 		/* Read 8-bit SPROM revision, maintaining 16-bit size alignment
229 		 * required by some OTP/SPROM chipsets. */
230 		error = bhnd_nvram_io_read(io, layout->srev_offset, &srevcrc,
231 		    sizeof(srevcrc));
232 		if (error)
233 			return (error);
234 
235 		srev = srevcrc[0];
236 
237 		/* Early sromrev 1 devices (specifically some BCM440x enet
238 		 * cards) are reported to have been incorrectly programmed
239 		 * with a revision of 0x10. */
240 		if (layout->rev == 1 && srev == 0x10)
241 			srev = 0x1;
242 
243 		/* Check revision against the layout definition */
244 		if (srev != layout->rev)
245 			continue;
246 
247 		/* Check the magic value, skipping to the next layout on
248 		 * failure. */
249 		error = bhnd_nvram_sprom_check_magic(io, layout, &magic);
250 		if (error) {
251 			/* If the CRC is was valid, log the mismatch */
252 			if (crc_valid || BHND_NV_VERBOSE) {
253 				BHND_NV_LOG("invalid sprom %hhu signature: "
254 					    "0x%hx (expected 0x%hx)\n", srev,
255 					    magic, layout->magic_value);
256 
257 					return (ENXIO);
258 			}
259 
260 			continue;
261 		}
262 
263 		/* Check for an earlier CRC error */
264 		if (!crc_valid) {
265 			/* If the magic check succeeded, then we may just have
266 			 * data corruption -- log the CRC error */
267 			if (have_magic || BHND_NV_VERBOSE) {
268 				BHND_NV_LOG("sprom %hhu CRC error (crc=%#hhx, "
269 					    "expected=%#x)\n", srev, crc,
270 					    BHND_NVRAM_CRC8_VALID);
271 			}
272 
273 			continue;
274 		}
275 
276 		/* Identified */
277 		*ident = layout;
278 		return (0);
279 	}
280 
281 	/* No match */
282 	if (crc_errors > 0 && BHND_NV_VERBOSE) {
283 		BHND_NV_LOG("sprom parsing failed with %zu CRC errors\n",
284 		    crc_errors);
285 	}
286 
287 	return (ENXIO);
288 }
289 
290 static int
291 bhnd_nvram_sprom_probe(struct bhnd_nvram_io *io)
292 {
293 	const bhnd_sprom_layout	*layout;
294 	int			 error;
295 
296 	/* Try to parse the input */
297 	if ((error = bhnd_nvram_sprom_ident(io, &layout)))
298 		return (error);
299 
300 	return (BHND_NVRAM_DATA_PROBE_DEFAULT);
301 }
302 
303 static int
304 bhnd_nvram_sprom_getvar_direct(struct bhnd_nvram_io *io, const char *name,
305     void *buf, size_t *len, bhnd_nvram_type type)
306 {
307 	const bhnd_sprom_layout		*layout;
308 	bhnd_sprom_opcode_state		 state;
309 	const struct bhnd_nvram_vardefn	*var;
310 	size_t				 vid;
311 	int				 error;
312 
313 	/* Look up the variable definition and ID */
314 	if ((var = bhnd_nvram_find_vardefn(name)) == NULL)
315 		return (ENOENT);
316 
317 	vid = bhnd_nvram_get_vardefn_id(var);
318 
319 	/* Identify the SPROM image layout */
320 	if ((error = bhnd_nvram_sprom_ident(io, &layout)))
321 		return (error);
322 
323 	/* Initialize SPROM layout interpreter */
324 	if ((error = bhnd_sprom_opcode_init(&state, layout))) {
325 		BHND_NV_LOG("error initializing opcode state: %d\n", error);
326 		return (ENXIO);
327 	}
328 
329 	/* Find SPROM layout entry for the requested variable */
330 	while ((error = bhnd_sprom_opcode_next_var(&state)) == 0) {
331 		bhnd_sprom_opcode_idx_entry	entry;
332 		union bhnd_nvram_sprom_storage	storage;
333 		bhnd_nvram_val			val;
334 
335 		/* Fetch the variable's entry state */
336 		if ((error = bhnd_sprom_opcode_init_entry(&state, &entry)))
337 			return (error);
338 
339 		/* Match against expected VID */
340 		if (entry.vid != vid)
341 			continue;
342 
343 		/* Decode variable to a new value instance */
344 		error = bhnd_nvram_sprom_read_var(&state, &entry, io, &storage,
345 		    &val);
346 		if (error)
347 			return (error);
348 
349 		/* Perform value coercion */
350 		error = bhnd_nvram_val_encode(&val, buf, len, type);
351 
352 		/* Clean up */
353 		bhnd_nvram_val_release(&val);
354 		return (error);
355 	}
356 
357 	/* Hit EOF without matching the requested variable? */
358 	if (error == ENOENT)
359 		return (ENOENT);
360 
361 	/* Some other parse error occured */
362 	return (error);
363 }
364 
365 /**
366  * Return the SPROM layout definition for the given @p sromrev, or NULL if
367  * not found.
368  */
369 static const bhnd_sprom_layout *
370 bhnd_nvram_sprom_get_layout(uint8_t sromrev)
371 {
372 	/* Find matching SPROM layout definition */
373 	for (size_t i = 0; i < bhnd_sprom_num_layouts; i++) {
374 		if (bhnd_sprom_layouts[i].rev == sromrev)
375 			return (&bhnd_sprom_layouts[i]);
376 	}
377 
378 	/* Not found */
379 	return (NULL);
380 }
381 
382 /**
383  * Serialize a SPROM variable.
384  *
385  * @param state	The SPROM opcode state describing the layout of @p io.
386  * @param entry	The variable's SPROM opcode index entry.
387  * @param value	The value to encode to @p io as per @p entry.
388  * @param io	I/O context to which @p value should be written, or NULL
389  *		if no output should be produced. This may be used to validate
390  *		values prior to write.
391  *
392  * @retval 0		success
393  * @retval EFTYPE	If value coercion from @p value to the type required by
394  *			@p entry is unsupported.
395  * @retval ERANGE	If value coercion from @p value would overflow
396  *			(or underflow) the type required by @p entry.
397  * @retval non-zero	If serialization otherwise fails, a regular unix error
398  *			code will be returned.
399  */
400 static int
401 bhnd_nvram_sprom_write_var(bhnd_sprom_opcode_state *state,
402     bhnd_sprom_opcode_idx_entry *entry, bhnd_nvram_val *value,
403     struct bhnd_nvram_io *io)
404 {
405 	const struct bhnd_nvram_vardefn	*var;
406 	uint32_t			 u32[BHND_SPROM_ARRAY_MAXLEN];
407 	bhnd_nvram_type			 itype, var_base_type;
408 	size_t				 ipos, ilen, nelem;
409 	int				 error;
410 
411 	/* Fetch variable definition and the native element type */
412 	var = bhnd_nvram_get_vardefn(entry->vid);
413 	BHND_NV_ASSERT(var != NULL, ("missing variable definition"));
414 
415 	var_base_type = bhnd_nvram_base_type(var->type);
416 
417 	/* Fetch the element count from the SPROM variable layout definition */
418 	if ((error = bhnd_sprom_opcode_eval_var(state, entry)))
419 		return (error);
420 
421 	nelem = state->var.nelem;
422 	BHND_NV_ASSERT(nelem <= var->nelem, ("SPROM nelem=%zu exceeds maximum "
423 	     "NVRAM nelem=%hhu", nelem, var->nelem));
424 
425 	/* Promote the data to a common 32-bit representation */
426 	if (bhnd_nvram_is_signed_type(var_base_type))
427 		itype = BHND_NVRAM_TYPE_INT32_ARRAY;
428 	else
429 		itype = BHND_NVRAM_TYPE_UINT32_ARRAY;
430 
431 	/* Calculate total size of the 32-bit promoted representation */
432 	if ((ilen = bhnd_nvram_value_size(NULL, 0, itype, nelem)) == 0) {
433 		/* Variable-width types are unsupported */
434 		BHND_NV_LOG("invalid %s SPROM variable type %d\n",
435 			    var->name, var->type);
436 		return (EFTYPE);
437 	}
438 
439 	/* The native representation must fit within our scratch array */
440 	if (ilen > sizeof(u32)) {
441 		BHND_NV_LOG("error encoding '%s', SPROM_ARRAY_MAXLEN "
442 			    "incorrect\n", var->name);
443 		return (EFTYPE);
444 	}
445 
446 	/* Initialize our common 32-bit value representation */
447 	if (bhnd_nvram_val_type(value) == BHND_NVRAM_TYPE_NULL) {
448 		/* No value provided; can this variable be encoded as missing
449 		 * by setting all bits to one? */
450 		if (!(var->flags & BHND_NVRAM_VF_IGNALL1)) {
451 			BHND_NV_LOG("missing required property: %s\n",
452 			    var->name);
453 			return (EINVAL);
454 		}
455 
456 		/* Set all bits */
457 		memset(u32, 0xFF, ilen);
458 	} else {
459 		bhnd_nvram_val	 bcm_val;
460 		const void	*var_ptr;
461 		bhnd_nvram_type	 var_type, raw_type;
462 		size_t		 var_len, enc_nelem;
463 
464 		/* Try to coerce the value to the native variable format. */
465 		error = bhnd_nvram_val_convert_init(&bcm_val, var->fmt, value,
466 		    BHND_NVRAM_VAL_DYNAMIC|BHND_NVRAM_VAL_BORROW_DATA);
467 		if (error) {
468 			BHND_NV_LOG("error converting input type %s to %s "
469 			    "format\n",
470 			    bhnd_nvram_type_name(bhnd_nvram_val_type(value)),
471 			    bhnd_nvram_val_fmt_name(var->fmt));
472 			return (error);
473 		}
474 
475 		var_ptr = bhnd_nvram_val_bytes(&bcm_val, &var_len, &var_type);
476 
477 		/*
478 		 * Promote to a common 32-bit representation.
479 		 *
480 		 * We must use the raw type to interpret the input data as its
481 		 * underlying integer representation -- otherwise, coercion
482 		 * would attempt to parse the input as its complex
483 		 * representation.
484 		 *
485 		 * For example, direct CHAR -> UINT32 coercion would attempt to
486 		 * parse the character as a decimal integer, rather than
487 		 * promoting the raw UTF8 byte value to a 32-bit value.
488 		 */
489 		raw_type = bhnd_nvram_raw_type(var_type);
490 		error = bhnd_nvram_value_coerce(var_ptr, var_len, raw_type,
491 		     u32, &ilen, itype);
492 
493 		/* Clean up temporary value representation */
494 		bhnd_nvram_val_release(&bcm_val);
495 
496 		/* Report coercion failure */
497 		if (error) {
498 			BHND_NV_LOG("error promoting %s to %s: %d\n",
499 			    bhnd_nvram_type_name(var_type),
500 			    bhnd_nvram_type_name(itype), error);
501 			return (error);
502 		}
503 
504 		/* Encoded element count must match SPROM's definition */
505 		error = bhnd_nvram_value_nelem(u32, ilen, itype, &enc_nelem);
506 		if (error)
507 			return (error);
508 
509 		if (enc_nelem != nelem) {
510 			const char *type_name;
511 
512 			type_name = bhnd_nvram_type_name(var_base_type);
513 			BHND_NV_LOG("invalid %s property value '%s[%zu]': "
514 			    "required %s[%zu]", var->name, type_name,
515 			    enc_nelem, type_name, nelem);
516 			return (EFTYPE);
517 		}
518 	}
519 
520 	/*
521 	 * Seek to the start of the variable's SPROM layout definition and
522 	 * iterate over all bindings.
523 	 */
524 	if ((error = bhnd_sprom_opcode_seek(state, entry))) {
525 		BHND_NV_LOG("variable seek failed: %d\n", error);
526 		return (error);
527 	}
528 
529 	ipos = 0;
530 	while ((error = bhnd_sprom_opcode_next_binding(state)) == 0) {
531 		bhnd_sprom_opcode_bind	*binding;
532 		bhnd_sprom_opcode_var	*binding_var;
533 		size_t			 offset;
534 		uint32_t		 skip_out_bytes;
535 
536 		BHND_NV_ASSERT(
537 		    state->var_state >= SPROM_OPCODE_VAR_STATE_OPEN,
538 		    ("invalid var state"));
539 		BHND_NV_ASSERT(state->var.have_bind, ("invalid bind state"));
540 
541 		binding_var = &state->var;
542 		binding = &state->var.bind;
543 
544 		/* Calculate output skip bytes for this binding.
545 		 *
546 		 * Skip directions are defined in terms of decoding, and
547 		 * reversed when encoding. */
548 		skip_out_bytes = binding->skip_in;
549 		error = bhnd_sprom_opcode_apply_scale(state, &skip_out_bytes);
550 		if (error)
551 			return (error);
552 
553 		/* Bind */
554 		offset = state->offset;
555 		for (size_t i = 0; i < binding->count; i++) {
556 			if (ipos >= nelem) {
557 				BHND_NV_LOG("input skip %u positioned %zu "
558 				    "beyond nelem %zu\n", binding->skip_out,
559 				    ipos, nelem);
560 				return (EINVAL);
561 			}
562 
563 			/* Write next offset */
564 			if (io != NULL) {
565 				error = bhnd_nvram_sprom_write_offset(var, io,
566 				    binding_var->base_type,
567 				    offset,
568 				    binding_var->mask,
569 				    binding_var->shift,
570 				    u32[ipos]);
571 				if (error)
572 					return (error);
573 			}
574 
575 			/* Adjust output position; this was already verified to
576 			 * not overflow/underflow during SPROM opcode
577 			 * evaluation */
578 			if (binding->skip_in_negative) {
579 				offset -= skip_out_bytes;
580 			} else {
581 				offset += skip_out_bytes;
582 			}
583 
584 			/* Skip advancing input if additional bindings are
585 			 * required to fully encode intv */
586 			if (binding->skip_out == 0)
587 				continue;
588 
589 			/* Advance input position */
590 			if (SIZE_MAX - binding->skip_out < ipos) {
591 				BHND_NV_LOG("output skip %u would overflow "
592 				    "%zu\n", binding->skip_out, ipos);
593 				return (EINVAL);
594 			}
595 
596 			ipos += binding->skip_out;
597 		}
598 	}
599 
600 	/* Did we iterate all bindings until hitting end of the variable
601 	 * definition? */
602 	BHND_NV_ASSERT(error != 0, ("loop terminated early"));
603 	if (error != ENOENT)
604 		return (error);
605 
606 	return (0);
607 }
608 
609 static int
610 bhnd_nvram_sprom_serialize(bhnd_nvram_data_class *cls, bhnd_nvram_plist *props,
611     bhnd_nvram_plist *options, void *outp, size_t *olen)
612 {
613 	bhnd_sprom_opcode_state		 state;
614 	struct bhnd_nvram_io		*io;
615 	bhnd_nvram_prop			*prop;
616 	bhnd_sprom_opcode_idx_entry	*entry;
617 	const bhnd_sprom_layout		*layout;
618 	size_t				 limit;
619 	uint8_t				 crc;
620 	uint8_t				 sromrev;
621 	int				 error;
622 
623 	limit = *olen;
624 	layout = NULL;
625 	io = NULL;
626 
627 	/* Fetch sromrev property */
628 	if (!bhnd_nvram_plist_contains(props, BHND_NVAR_SROMREV)) {
629 		BHND_NV_LOG("missing required property: %s\n",
630 		    BHND_NVAR_SROMREV);
631 		return (EINVAL);
632 	}
633 
634 	error = bhnd_nvram_plist_get_uint8(props, BHND_NVAR_SROMREV, &sromrev);
635 	if (error) {
636 		BHND_NV_LOG("error reading sromrev property: %d\n", error);
637 		return (EFTYPE);
638 	}
639 
640 	/* Find SPROM layout definition */
641 	if ((layout = bhnd_nvram_sprom_get_layout(sromrev)) == NULL) {
642 		BHND_NV_LOG("unsupported sromrev: %hhu\n", sromrev);
643 		return (EFTYPE);
644 	}
645 
646 	/* Provide required size to caller */
647 	*olen = layout->size;
648 	if (outp == NULL)
649 		return (0);
650 	else if (limit < *olen)
651 		return (ENOMEM);
652 
653 	/* Initialize SPROM layout interpreter */
654 	if ((error = bhnd_sprom_opcode_init(&state, layout))) {
655 		BHND_NV_LOG("error initializing opcode state: %d\n", error);
656 		return (ENXIO);
657 	}
658 
659 	/* Check for unsupported properties */
660 	prop = NULL;
661 	while ((prop = bhnd_nvram_plist_next(props, prop)) != NULL) {
662 		const char *name;
663 
664 		/* Fetch the corresponding SPROM layout index entry */
665 		name = bhnd_nvram_prop_name(prop);
666 		entry = bhnd_sprom_opcode_index_find(&state, name);
667 		if (entry == NULL) {
668 			BHND_NV_LOG("property '%s' unsupported by sromrev "
669 			    "%hhu\n", name, layout->rev);
670 			error = EINVAL;
671 			goto finished;
672 		}
673 	}
674 
675 	/* Zero-initialize output */
676 	memset(outp, 0, *olen);
677 
678 	/* Allocate wrapping I/O context for output buffer */
679 	io = bhnd_nvram_ioptr_new(outp, *olen, *olen, BHND_NVRAM_IOPTR_RDWR);
680 	if (io == NULL) {
681 		error = ENOMEM;
682 		goto finished;
683 	}
684 
685 	/*
686 	 * Serialize all SPROM variable data.
687 	 */
688 	entry = NULL;
689 	while ((entry = bhnd_sprom_opcode_index_next(&state, entry)) != NULL) {
690 		const struct bhnd_nvram_vardefn	*var;
691 		bhnd_nvram_val			*val;
692 
693 		var = bhnd_nvram_get_vardefn(entry->vid);
694 		BHND_NV_ASSERT(var != NULL, ("missing variable definition"));
695 
696 		/* Fetch prop; will be NULL if unavailable */
697 		prop = bhnd_nvram_plist_get_prop(props, var->name);
698 		if (prop != NULL) {
699 			val = bhnd_nvram_prop_val(prop);
700 		} else {
701 			val = BHND_NVRAM_VAL_NULL;
702 		}
703 
704 		/* Attempt to serialize the property value to the appropriate
705 		 * offset within the output buffer */
706 		error = bhnd_nvram_sprom_write_var(&state, entry, val, io);
707 		if (error) {
708 			BHND_NV_LOG("error serializing %s to required type "
709 			    "%s: %d\n", var->name,
710 			    bhnd_nvram_type_name(var->type), error);
711 
712 			/* ENOMEM is reserved for signaling that the output
713 			 * buffer capacity is insufficient */
714 			if (error == ENOMEM)
715 				error = EINVAL;
716 
717 			goto finished;
718 		}
719 	}
720 
721 	/*
722 	 * Write magic value, if any.
723 	 */
724 	if (!(layout->flags & SPROM_LAYOUT_MAGIC_NONE)) {
725 		uint16_t magic;
726 
727 		magic = htole16(layout->magic_value);
728 		error = bhnd_nvram_io_write(io, layout->magic_offset, &magic,
729 		    sizeof(magic));
730 		if (error) {
731 			BHND_NV_LOG("error writing magic value: %d\n", error);
732 			goto finished;
733 		}
734 	}
735 
736 	/* Calculate the CRC over all SPROM data, not including the CRC byte. */
737 	crc = ~bhnd_nvram_crc8(outp, layout->crc_offset,
738 	    BHND_NVRAM_CRC8_INITIAL);
739 
740 	/* Write the checksum. */
741 	error = bhnd_nvram_io_write(io, layout->crc_offset, &crc, sizeof(crc));
742 	if (error) {
743 		BHND_NV_LOG("error writing CRC value: %d\n", error);
744 		goto finished;
745 	}
746 
747 	/*
748 	 * Success!
749 	 */
750 	error = 0;
751 
752 finished:
753 	bhnd_sprom_opcode_fini(&state);
754 
755 	if (io != NULL)
756 		bhnd_nvram_io_free(io);
757 
758 	return (error);
759 }
760 
761 static int
762 bhnd_nvram_sprom_new(struct bhnd_nvram_data *nv, struct bhnd_nvram_io *io)
763 {
764 	struct bhnd_nvram_sprom	*sp;
765 	int			 error;
766 
767 	sp = (struct bhnd_nvram_sprom *)nv;
768 
769 	/* Identify the SPROM input data */
770 	if ((error = bhnd_nvram_sprom_ident(io, &sp->layout)))
771 		return (error);
772 
773 	/* Copy SPROM image to our shadow buffer */
774 	sp->data = bhnd_nvram_iobuf_copy_range(io, 0, sp->layout->size);
775 	if (sp->data == NULL)
776 		goto failed;
777 
778 	/* Initialize SPROM binding eval state */
779 	if ((error = bhnd_sprom_opcode_init(&sp->state, sp->layout)))
780 		goto failed;
781 
782 	return (0);
783 
784 failed:
785 	if (sp->data != NULL)
786 		bhnd_nvram_io_free(sp->data);
787 
788 	return (error);
789 }
790 
791 static void
792 bhnd_nvram_sprom_free(struct bhnd_nvram_data *nv)
793 {
794 	struct bhnd_nvram_sprom *sp = (struct bhnd_nvram_sprom *)nv;
795 
796 	bhnd_sprom_opcode_fini(&sp->state);
797 	bhnd_nvram_io_free(sp->data);
798 }
799 
800 size_t
801 bhnd_nvram_sprom_count(struct bhnd_nvram_data *nv)
802 {
803 	struct bhnd_nvram_sprom *sprom = (struct bhnd_nvram_sprom *)nv;
804 	return (sprom->layout->num_vars);
805 }
806 
807 static bhnd_nvram_plist *
808 bhnd_nvram_sprom_options(struct bhnd_nvram_data *nv)
809 {
810 	return (NULL);
811 }
812 
813 static uint32_t
814 bhnd_nvram_sprom_caps(struct bhnd_nvram_data *nv)
815 {
816 	return (BHND_NVRAM_DATA_CAP_INDEXED);
817 }
818 
819 static const char *
820 bhnd_nvram_sprom_next(struct bhnd_nvram_data *nv, void **cookiep)
821 {
822 	struct bhnd_nvram_sprom		*sp;
823 	bhnd_sprom_opcode_idx_entry	*entry;
824 	const struct bhnd_nvram_vardefn	*var;
825 
826 	sp = (struct bhnd_nvram_sprom *)nv;
827 
828 	/* Find next index entry that is not disabled by virtue of IGNALL1 */
829 	entry = *cookiep;
830 	while ((entry = bhnd_sprom_opcode_index_next(&sp->state, entry))) {
831 		/* Update cookiep and fetch variable definition */
832 		*cookiep = entry;
833 		var = SPROM_COOKIE_TO_NVRAM_VAR(*cookiep);
834 
835 		/* We might need to parse the variable's value to determine
836 		 * whether it should be treated as unset */
837 		if (var->flags & BHND_NVRAM_VF_IGNALL1) {
838 			int     error;
839 			size_t  len;
840 
841 			error = bhnd_nvram_sprom_getvar(nv, *cookiep, NULL,
842 			    &len, var->type);
843 			if (error) {
844 				BHND_NV_ASSERT(error == ENOENT, ("unexpected "
845 				    "error parsing variable: %d", error));
846 				continue;
847 			}
848 		}
849 
850 		/* Found! */
851 		return (var->name);
852 	}
853 
854 	/* Reached end of index entries */
855 	return (NULL);
856 }
857 
858 static void *
859 bhnd_nvram_sprom_find(struct bhnd_nvram_data *nv, const char *name)
860 {
861 	struct bhnd_nvram_sprom		*sp;
862 	bhnd_sprom_opcode_idx_entry	*entry;
863 
864 	sp = (struct bhnd_nvram_sprom *)nv;
865 
866 	entry = bhnd_sprom_opcode_index_find(&sp->state, name);
867 	return (entry);
868 }
869 
870 /**
871  * Write @p value of @p type to the SPROM @p data at @p offset, applying
872  * @p mask and @p shift, and OR with the existing data.
873  *
874  * @param var The NVRAM variable definition.
875  * @param data The SPROM data to be modified.
876  * @param type The type to write at @p offset.
877  * @param offset The data offset to be written.
878  * @param mask The mask to be applied to @p value after shifting.
879  * @param shift The shift to be applied to @p value; if positive, a left
880  * shift will be applied, if negative, a right shift (this is the reverse of the
881  * decoding behavior)
882  * @param value The value to be written. The parsed value will be OR'd with the
883  * current contents of @p data at @p offset.
884  */
885 static int
886 bhnd_nvram_sprom_write_offset(const struct bhnd_nvram_vardefn *var,
887     struct bhnd_nvram_io *data, bhnd_nvram_type type, size_t offset,
888     uint32_t mask, int8_t shift, uint32_t value)
889 {
890 	union bhnd_nvram_sprom_storage	scratch;
891 	int				error;
892 
893 #define	NV_WRITE_INT(_widen, _repr, _swap)	do {		\
894 	/* Narrow the 32-bit representation */			\
895 	scratch._repr[1] = (_widen)value;			\
896 								\
897 	/* Shift and mask the new value */			\
898 	if (shift > 0)						\
899 		scratch._repr[1] <<= shift;			\
900 	else if (shift < 0)					\
901 		scratch._repr[1] >>= -shift;			\
902 	scratch._repr[1] &= mask;				\
903 								\
904 	/* Swap to output byte order */				\
905 	scratch._repr[1] = _swap(scratch._repr[1]);		\
906 								\
907 	/* Fetch the current value */				\
908 	error = bhnd_nvram_io_read(data, offset,		\
909 	    &scratch._repr[0], sizeof(scratch._repr[0]));	\
910 	if (error) {						\
911 		BHND_NV_LOG("error reading %s SPROM offset "	\
912 		    "%#zx: %d\n", var->name, offset, error);	\
913 		return (EFTYPE);				\
914 	}							\
915 								\
916 	/* Mask and set our new value's bits in the current	\
917 	 * value */						\
918 	if (shift >= 0)						\
919 		scratch._repr[0] &= ~_swap(mask << shift);	\
920 	else if (shift < 0)					\
921 		scratch._repr[0] &= ~_swap(mask >> (-shift));	\
922 	scratch._repr[0] |= scratch._repr[1];			\
923 								\
924 	/* Perform write */					\
925 	error = bhnd_nvram_io_write(data, offset,		\
926 	    &scratch._repr[0], sizeof(scratch._repr[0]));	\
927 	if (error) {						\
928 		BHND_NV_LOG("error writing %s SPROM offset "	\
929 		    "%#zx: %d\n", var->name, offset, error);	\
930 		return (EFTYPE);				\
931 	}							\
932 } while(0)
933 
934 	/* Apply mask/shift and widen to a common 32bit representation */
935 	switch (type) {
936 	case BHND_NVRAM_TYPE_UINT8:
937 		NV_WRITE_INT(uint32_t,	u8,	);
938 		break;
939 	case BHND_NVRAM_TYPE_UINT16:
940 		NV_WRITE_INT(uint32_t,	u16,	htole16);
941 		break;
942 	case BHND_NVRAM_TYPE_UINT32:
943 		NV_WRITE_INT(uint32_t,	u32,	htole32);
944 		break;
945 	case BHND_NVRAM_TYPE_INT8:
946 		NV_WRITE_INT(int32_t,	i8,	);
947 		break;
948 	case BHND_NVRAM_TYPE_INT16:
949 		NV_WRITE_INT(int32_t,	i16,	htole16);
950 		break;
951 	case BHND_NVRAM_TYPE_INT32:
952 		NV_WRITE_INT(int32_t,	i32,	htole32);
953 		break;
954 	case BHND_NVRAM_TYPE_CHAR:
955 		NV_WRITE_INT(uint32_t,	u8,	);
956 		break;
957 	default:
958 		BHND_NV_LOG("unhandled %s offset type: %d\n", var->name, type);
959 		return (EFTYPE);
960 	}
961 #undef	NV_WRITE_INT
962 
963 	return (0);
964 }
965 
966 /**
967  * Read the value of @p type from the SPROM @p data at @p offset, apply @p mask
968  * and @p shift, and OR with the existing @p value.
969  *
970  * @param var The NVRAM variable definition.
971  * @param data The SPROM data to be decoded.
972  * @param type The type to read at @p offset
973  * @param offset The data offset to be read.
974  * @param mask The mask to be applied to the value read at @p offset.
975  * @param shift The shift to be applied after masking; if positive, a right
976  * shift will be applied, if negative, a left shift.
977  * @param value The read destination; the parsed value will be OR'd with the
978  * current contents of @p value.
979  */
980 static int
981 bhnd_nvram_sprom_read_offset(const struct bhnd_nvram_vardefn *var,
982     struct bhnd_nvram_io *data, bhnd_nvram_type type, size_t offset,
983     uint32_t mask, int8_t shift, uint32_t *value)
984 {
985 	union bhnd_nvram_sprom_storage	scratch;
986 	int				error;
987 
988 #define	NV_PARSE_INT(_widen, _repr, _swap)		do {	\
989 	/* Perform read */					\
990 	error = bhnd_nvram_io_read(data, offset,		\
991 	    &scratch._repr[0], sizeof(scratch._repr[0]));	\
992 	if (error) {						\
993 		BHND_NV_LOG("error reading %s SPROM offset "	\
994 		    "%#zx: %d\n", var->name, offset, error);	\
995 		return (EFTYPE);				\
996 	}							\
997 								\
998 	/* Swap to host byte order */				\
999 	scratch._repr[0] = _swap(scratch._repr[0]);		\
1000 								\
1001 	/* Mask and shift the value */				\
1002 	scratch._repr[0] &= mask;				\
1003 	if (shift > 0) {					\
1004 		scratch. _repr[0] >>= shift;			\
1005 	} else if (shift < 0) {					\
1006 		scratch. _repr[0] <<= -shift;			\
1007 	}							\
1008 								\
1009 	/* Widen to 32-bit representation and OR with current	\
1010 	 * value */						\
1011 	(*value) |= (_widen)scratch._repr[0];			\
1012 } while(0)
1013 
1014 	/* Apply mask/shift and widen to a common 32bit representation */
1015 	switch (type) {
1016 	case BHND_NVRAM_TYPE_UINT8:
1017 		NV_PARSE_INT(uint32_t,	u8,	);
1018 		break;
1019 	case BHND_NVRAM_TYPE_UINT16:
1020 		NV_PARSE_INT(uint32_t,	u16,	le16toh);
1021 		break;
1022 	case BHND_NVRAM_TYPE_UINT32:
1023 		NV_PARSE_INT(uint32_t,	u32,	le32toh);
1024 		break;
1025 	case BHND_NVRAM_TYPE_INT8:
1026 		NV_PARSE_INT(int32_t,	i8,	);
1027 		break;
1028 	case BHND_NVRAM_TYPE_INT16:
1029 		NV_PARSE_INT(int32_t,	i16,	le16toh);
1030 		break;
1031 	case BHND_NVRAM_TYPE_INT32:
1032 		NV_PARSE_INT(int32_t,	i32,	le32toh);
1033 		break;
1034 	case BHND_NVRAM_TYPE_CHAR:
1035 		NV_PARSE_INT(uint32_t,	u8,	);
1036 		break;
1037 	default:
1038 		BHND_NV_LOG("unhandled %s offset type: %d\n", var->name, type);
1039 		return (EFTYPE);
1040 	}
1041 #undef	NV_PARSE_INT
1042 
1043 	return (0);
1044 }
1045 
1046 /**
1047  * Read a SPROM variable value from @p io.
1048  *
1049  * @param	state		The SPROM opcode state describing the layout of @p io.
1050  * @param	entry		The variable's SPROM opcode index entry.
1051  * @param	io		The input I/O context.
1052  * @param	storage		Storage to be used with @p val.
1053  * @param[out]	val		Value instance to be initialized with the
1054  *				parsed variable data.
1055  *
1056  * The returned @p val instance will hold a borrowed reference to @p storage,
1057  * and must be copied via bhnd_nvram_val_copy() if it will be referenced beyond
1058  * the lifetime of @p storage.
1059  *
1060  * The caller is responsible for releasing any allocated value state
1061  * via bhnd_nvram_val_release().
1062  */
1063 static int
1064 bhnd_nvram_sprom_read_var(struct bhnd_sprom_opcode_state *state,
1065     struct bhnd_sprom_opcode_idx_entry *entry, struct bhnd_nvram_io *io,
1066     union bhnd_nvram_sprom_storage *storage, bhnd_nvram_val *val)
1067 {
1068 	union bhnd_nvram_sprom_storage	*inp;
1069 	const struct bhnd_nvram_vardefn	*var;
1070 	bhnd_nvram_type			 var_btype;
1071 	uint32_t			 intv;
1072 	size_t				 ilen, ipos, iwidth;
1073 	size_t				 nelem;
1074 	bool				 all_bits_set;
1075 	int				 error;
1076 
1077 	/* Fetch canonical variable definition */
1078 	var = bhnd_nvram_get_vardefn(entry->vid);
1079 	BHND_NV_ASSERT(var != NULL, ("invalid entry"));
1080 
1081 	/*
1082 	 * Fetch the array length from the SPROM variable definition.
1083 	 *
1084 	 * This generally be identical to the array length provided by the
1085 	 * canonical NVRAM variable definition, but some SPROM layouts may
1086 	 * define a smaller element count.
1087 	 */
1088 	if ((error = bhnd_sprom_opcode_eval_var(state, entry))) {
1089 		BHND_NV_LOG("variable evaluation failed: %d\n", error);
1090 		return (error);
1091 	}
1092 
1093 	nelem = state->var.nelem;
1094 	if (nelem > var->nelem) {
1095 		BHND_NV_LOG("SPROM array element count %zu cannot be "
1096 		    "represented by '%s' element count of %hhu\n", nelem,
1097 		    var->name, var->nelem);
1098 		return (EFTYPE);
1099 	}
1100 
1101 	/* Fetch the var's base element type */
1102 	var_btype = bhnd_nvram_base_type(var->type);
1103 
1104 	/* Calculate total byte length of the native encoding */
1105 	if ((iwidth = bhnd_nvram_value_size(NULL, 0, var_btype, 1)) == 0) {
1106 		/* SPROM does not use (and we do not support) decoding of
1107 		 * variable-width data types */
1108 		BHND_NV_LOG("invalid SPROM data type: %d", var->type);
1109 		return (EFTYPE);
1110 	}
1111 	ilen = nelem * iwidth;
1112 
1113 	/* Decode into our caller's local storage */
1114 	inp = storage;
1115 	if (ilen > sizeof(*storage)) {
1116 		BHND_NV_LOG("error decoding '%s', SPROM_ARRAY_MAXLEN "
1117 		    "incorrect\n", var->name);
1118 		return (EFTYPE);
1119 	}
1120 
1121 	/* Zero-initialize our decode buffer; any output elements skipped
1122 	 * during decode should default to zero. */
1123 	memset(inp, 0, ilen);
1124 
1125 	/*
1126 	 * Decode the SPROM data, iteratively decoding up to nelem values.
1127 	 */
1128 	if ((error = bhnd_sprom_opcode_seek(state, entry))) {
1129 		BHND_NV_LOG("variable seek failed: %d\n", error);
1130 		return (error);
1131 	}
1132 
1133 	ipos = 0;
1134 	intv = 0x0;
1135 	if (var->flags & BHND_NVRAM_VF_IGNALL1)
1136 		all_bits_set = true;
1137 	else
1138 		all_bits_set = false;
1139 	while ((error = bhnd_sprom_opcode_next_binding(state)) == 0) {
1140 		bhnd_sprom_opcode_bind	*binding;
1141 		bhnd_sprom_opcode_var	*binding_var;
1142 		bhnd_nvram_type		 intv_type;
1143 		size_t			 offset;
1144 		size_t			 nbyte;
1145 		uint32_t		 skip_in_bytes;
1146 		void			*ptr;
1147 
1148 		BHND_NV_ASSERT(
1149 		    state->var_state >= SPROM_OPCODE_VAR_STATE_OPEN,
1150 		    ("invalid var state"));
1151 		BHND_NV_ASSERT(state->var.have_bind, ("invalid bind state"));
1152 
1153 		binding_var = &state->var;
1154 		binding = &state->var.bind;
1155 
1156 		if (ipos >= nelem) {
1157 			BHND_NV_LOG("output skip %u positioned "
1158 			    "%zu beyond nelem %zu\n",
1159 			    binding->skip_out, ipos, nelem);
1160 			return (EINVAL);
1161 		}
1162 
1163 		/* Calculate input skip bytes for this binding */
1164 		skip_in_bytes = binding->skip_in;
1165 		error = bhnd_sprom_opcode_apply_scale(state, &skip_in_bytes);
1166 		if (error)
1167 			return (error);
1168 
1169 		/* Bind */
1170 		offset = state->offset;
1171 		for (size_t i = 0; i < binding->count; i++) {
1172 			/* Read the offset value, OR'ing with the current
1173 			 * value of intv */
1174 			error = bhnd_nvram_sprom_read_offset(var, io,
1175 			    binding_var->base_type,
1176 			    offset,
1177 			    binding_var->mask,
1178 			    binding_var->shift,
1179 			    &intv);
1180 			if (error)
1181 				return (error);
1182 
1183 			/* If IGNALL1, record whether value does not have
1184 			 * all bits set. */
1185 			if (var->flags & BHND_NVRAM_VF_IGNALL1 &&
1186 			    all_bits_set)
1187 			{
1188 				uint32_t all1;
1189 
1190 				all1 = binding_var->mask;
1191 				if (binding_var->shift > 0)
1192 					all1 >>= binding_var->shift;
1193 				else if (binding_var->shift < 0)
1194 					all1 <<= -binding_var->shift;
1195 
1196 				if ((intv & all1) != all1)
1197 					all_bits_set = false;
1198 			}
1199 
1200 			/* Adjust input position; this was already verified to
1201 			 * not overflow/underflow during SPROM opcode
1202 			 * evaluation */
1203 			if (binding->skip_in_negative) {
1204 				offset -= skip_in_bytes;
1205 			} else {
1206 				offset += skip_in_bytes;
1207 			}
1208 
1209 			/* Skip writing to inp if additional bindings are
1210 			 * required to fully populate intv */
1211 			if (binding->skip_out == 0)
1212 				continue;
1213 
1214 			/* We use bhnd_nvram_value_coerce() to perform
1215 			 * overflow-checked coercion from the widened
1216 			 * uint32/int32 intv value to the requested output
1217 			 * type */
1218 			if (bhnd_nvram_is_signed_type(var_btype))
1219 				intv_type = BHND_NVRAM_TYPE_INT32;
1220 			else
1221 				intv_type = BHND_NVRAM_TYPE_UINT32;
1222 
1223 			/* Calculate address of the current element output
1224 			 * position */
1225 			ptr = (uint8_t *)inp + (iwidth * ipos);
1226 
1227 			/* Perform coercion of the array element */
1228 			nbyte = iwidth;
1229 			error = bhnd_nvram_value_coerce(&intv, sizeof(intv),
1230 			    intv_type, ptr, &nbyte, var_btype);
1231 			if (error)
1232 				return (error);
1233 
1234 			/* Clear temporary state */
1235 			intv = 0x0;
1236 
1237 			/* Advance output position */
1238 			if (SIZE_MAX - binding->skip_out < ipos) {
1239 				BHND_NV_LOG("output skip %u would overflow "
1240 				    "%zu\n", binding->skip_out, ipos);
1241 				return (EINVAL);
1242 			}
1243 
1244 			ipos += binding->skip_out;
1245 		}
1246 	}
1247 
1248 	/* Did we iterate all bindings until hitting end of the variable
1249 	 * definition? */
1250 	BHND_NV_ASSERT(error != 0, ("loop terminated early"));
1251 	if (error != ENOENT) {
1252 		return (error);
1253 	}
1254 
1255 	/* If marked IGNALL1 and all bits are set, treat variable as
1256 	 * unavailable */
1257 	if ((var->flags & BHND_NVRAM_VF_IGNALL1) && all_bits_set)
1258 		return (ENOENT);
1259 
1260 	/* Provide value wrapper */
1261 	return (bhnd_nvram_val_init(val, var->fmt, inp, ilen, var->type,
1262 	    BHND_NVRAM_VAL_BORROW_DATA));
1263 }
1264 
1265 
1266 /**
1267  * Common variable decoding; fetches and decodes variable to @p val,
1268  * using @p storage for actual data storage.
1269  *
1270  * The returned @p val instance will hold a borrowed reference to @p storage,
1271  * and must be copied via bhnd_nvram_val_copy() if it will be referenced beyond
1272  * the lifetime of @p storage.
1273  *
1274  * The caller is responsible for releasing any allocated value state
1275  * via bhnd_nvram_val_release().
1276  */
1277 static int
1278 bhnd_nvram_sprom_getvar_common(struct bhnd_nvram_data *nv, void *cookiep,
1279     union bhnd_nvram_sprom_storage *storage, bhnd_nvram_val *val)
1280 {
1281 	struct bhnd_nvram_sprom		*sp;
1282 	bhnd_sprom_opcode_idx_entry	*entry;
1283 	const struct bhnd_nvram_vardefn	*var;
1284 
1285 	BHND_NV_ASSERT(cookiep != NULL, ("NULL variable cookiep"));
1286 
1287 	sp = (struct bhnd_nvram_sprom *)nv;
1288 	entry = cookiep;
1289 
1290 	/* Fetch canonical variable definition */
1291 	var = SPROM_COOKIE_TO_NVRAM_VAR(cookiep);
1292 	BHND_NV_ASSERT(var != NULL, ("invalid cookiep %p", cookiep));
1293 
1294 	return (bhnd_nvram_sprom_read_var(&sp->state, entry, sp->data, storage,
1295 	    val));
1296 }
1297 
1298 static int
1299 bhnd_nvram_sprom_getvar_order(struct bhnd_nvram_data *nv, void *cookiep1,
1300     void *cookiep2)
1301 {
1302 	struct bhnd_sprom_opcode_idx_entry *e1, *e2;
1303 
1304 	e1 = cookiep1;
1305 	e2 = cookiep2;
1306 
1307 	/* Use the index entry order; this matches the order of variables
1308 	 * returned via bhnd_nvram_sprom_next() */
1309 	if (e1 < e2)
1310 		return (-1);
1311 	else if (e1 > e2)
1312 		return (1);
1313 
1314 	return (0);
1315 }
1316 
1317 static int
1318 bhnd_nvram_sprom_getvar(struct bhnd_nvram_data *nv, void *cookiep, void *buf,
1319     size_t *len, bhnd_nvram_type otype)
1320 {
1321 	bhnd_nvram_val			val;
1322 	union bhnd_nvram_sprom_storage	storage;
1323 	int				error;
1324 
1325 	/* Decode variable to a new value instance */
1326 	error = bhnd_nvram_sprom_getvar_common(nv, cookiep, &storage, &val);
1327 	if (error)
1328 		return (error);
1329 
1330 	/* Perform value coercion */
1331 	error = bhnd_nvram_val_encode(&val, buf, len, otype);
1332 
1333 	/* Clean up */
1334 	bhnd_nvram_val_release(&val);
1335 	return (error);
1336 }
1337 
1338 static int
1339 bhnd_nvram_sprom_copy_val(struct bhnd_nvram_data *nv, void *cookiep,
1340     bhnd_nvram_val **value)
1341 {
1342 	bhnd_nvram_val			val;
1343 	union bhnd_nvram_sprom_storage	storage;
1344 	int				error;
1345 
1346 	/* Decode variable to a new value instance */
1347 	error = bhnd_nvram_sprom_getvar_common(nv, cookiep, &storage, &val);
1348 	if (error)
1349 		return (error);
1350 
1351 	/* Attempt to copy to heap */
1352 	*value = bhnd_nvram_val_copy(&val);
1353 	bhnd_nvram_val_release(&val);
1354 
1355 	if (*value == NULL)
1356 		return (ENOMEM);
1357 
1358 	return (0);
1359 }
1360 
1361 static const void *
1362 bhnd_nvram_sprom_getvar_ptr(struct bhnd_nvram_data *nv, void *cookiep,
1363     size_t *len, bhnd_nvram_type *type)
1364 {
1365 	/* Unsupported */
1366 	return (NULL);
1367 }
1368 
1369 static const char *
1370 bhnd_nvram_sprom_getvar_name(struct bhnd_nvram_data *nv, void *cookiep)
1371 {
1372 	const struct bhnd_nvram_vardefn	*var;
1373 
1374 	BHND_NV_ASSERT(cookiep != NULL, ("NULL variable cookiep"));
1375 
1376 	var = SPROM_COOKIE_TO_NVRAM_VAR(cookiep);
1377 	BHND_NV_ASSERT(var != NULL, ("invalid cookiep %p", cookiep));
1378 
1379 	return (var->name);
1380 }
1381 
1382 static int
1383 bhnd_nvram_sprom_filter_setvar(struct bhnd_nvram_data *nv, const char *name,
1384     bhnd_nvram_val *value, bhnd_nvram_val **result)
1385 {
1386 	struct bhnd_nvram_sprom		*sp;
1387 	const struct bhnd_nvram_vardefn	*var;
1388 	bhnd_sprom_opcode_idx_entry	*entry;
1389 	bhnd_nvram_val			*spval;
1390 	int				 error;
1391 
1392 	sp = (struct bhnd_nvram_sprom *)nv;
1393 
1394 	/* Is this an externally immutable variable name? */
1395 	if (bhnd_sprom_is_external_immutable(name))
1396 		return (EINVAL);
1397 
1398 	/* Variable must be defined in our SPROM layout */
1399 	if ((entry = bhnd_sprom_opcode_index_find(&sp->state, name)) == NULL)
1400 		return (ENOENT);
1401 
1402 	var = bhnd_nvram_get_vardefn(entry->vid);
1403 	BHND_NV_ASSERT(var != NULL, ("missing variable definition"));
1404 
1405 	/* Value must be convertible to the native variable type */
1406 	error = bhnd_nvram_val_convert_new(&spval, var->fmt, value,
1407 	    BHND_NVRAM_VAL_DYNAMIC);
1408 	if (error)
1409 		return (error);
1410 
1411 	/* Value must be encodeable by our SPROM layout */
1412 	error = bhnd_nvram_sprom_write_var(&sp->state, entry, spval, NULL);
1413 	if (error) {
1414 		bhnd_nvram_val_release(spval);
1415 		return (error);
1416 	}
1417 
1418 	/* Success. Transfer our ownership of the converted value to the
1419 	 * caller */
1420 	*result = spval;
1421 	return (0);
1422 }
1423 
1424 static int
1425 bhnd_nvram_sprom_filter_unsetvar(struct bhnd_nvram_data *nv, const char *name)
1426 {
1427 	struct bhnd_nvram_sprom		*sp;
1428 	const struct bhnd_nvram_vardefn	*var;
1429 	bhnd_sprom_opcode_idx_entry	*entry;
1430 
1431 	sp = (struct bhnd_nvram_sprom *)nv;
1432 
1433 	/* Is this an externally immutable variable name? */
1434 	if (bhnd_sprom_is_external_immutable(name))
1435 		return (EINVAL);
1436 
1437 	/* Variable must be defined in our SPROM layout */
1438 	if ((entry = bhnd_sprom_opcode_index_find(&sp->state, name)) == NULL)
1439 		return (ENOENT);
1440 
1441 	var = bhnd_nvram_get_vardefn(entry->vid);
1442 
1443 	/* Variable must be capable of representing a NULL/deleted value.
1444 	 *
1445 	 * Since SPROM's layout is fixed, this requires IGNALL -- if
1446 	 * all bits are set, an IGNALL variable is treated as unset. */
1447 	if (!(var->flags & BHND_NVRAM_VF_IGNALL1))
1448 		return (EINVAL);
1449 
1450 	return (0);
1451 }
1452 
1453 /**
1454  * Return true if @p name represents a special immutable variable name
1455  * (e.g. sromrev) that cannot be updated in an SPROM existing image.
1456  *
1457  * @param name The name to check.
1458  */
1459 static bool
1460 bhnd_sprom_is_external_immutable(const char *name)
1461 {
1462 	/* The layout revision is immutable and cannot be changed */
1463 	if (strcmp(name, BHND_NVAR_SROMREV) == 0)
1464 		return (true);
1465 
1466 	return (false);
1467 }
1468