Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
/*-
 * Copyright (c) 2015-2016 Landon Fuller <landonf@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
 *    redistribution must be conditioned upon including a substantially
 *    similar Disclaimer requirement for further binary redistribution.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGES.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/endian.h>

#ifdef _KERNEL

#include <sys/param.h>
#include <sys/ctype.h>
#include <sys/malloc.h>
#include <sys/systm.h>

#else /* !_KERNEL */

#include <ctype.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#endif /* _KERNEL */

#include "bhnd_nvram_private.h"

#include "bhnd_nvram_datavar.h"

#include "bhnd_nvram_data_bcmreg.h"	/* for BCM_NVRAM_MAGIC */

/**
 * Broadcom "Board Text" data class.
 *
 * This format is used to provide external NVRAM data for some
 * fullmac WiFi devices, and as an input format when programming
 * NVRAM/SPROM/OTP.
 */

struct bhnd_nvram_btxt {
	struct bhnd_nvram_data	 nv;	/**< common instance state */
	struct bhnd_nvram_io	*data;	/**< memory-backed board text data */
	size_t			 count;	/**< variable count */
};

BHND_NVRAM_DATA_CLASS_DEFN(btxt, "Broadcom Board Text",
    BHND_NVRAM_DATA_CAP_DEVPATHS, sizeof(struct bhnd_nvram_btxt))

/** Minimal identification header */
union bhnd_nvram_btxt_ident {
	uint32_t	bcm_magic;
	char		btxt[8];
};

static void	*bhnd_nvram_btxt_offset_to_cookiep(struct bhnd_nvram_btxt *btxt,
		 size_t io_offset);
static size_t	 bhnd_nvram_btxt_cookiep_to_offset(struct bhnd_nvram_btxt *btxt,
		     void *cookiep);

static int	bhnd_nvram_btxt_entry_len(struct bhnd_nvram_io *io,
		    size_t offset, size_t *line_len, size_t *env_len);
static int	bhnd_nvram_btxt_seek_next(struct bhnd_nvram_io *io,
		    size_t *offset);
static int	bhnd_nvram_btxt_seek_eol(struct bhnd_nvram_io *io,
		    size_t *offset);

static int
bhnd_nvram_btxt_probe(struct bhnd_nvram_io *io)
{
	union bhnd_nvram_btxt_ident	ident;
	char				c;
	int				error;

	/* Look at the initial header for something that looks like 
	 * an ASCII board text file */
	if ((error = bhnd_nvram_io_read(io, 0x0, &ident, sizeof(ident))))
		return (error);

	/* The BCM NVRAM format uses a 'FLSH' little endian magic value, which
	 * shouldn't be interpreted as BTXT */
	if (le32toh(ident.bcm_magic) == BCM_NVRAM_MAGIC)
		return (ENXIO);

	/* Don't match on non-ASCII/non-printable data */
	for (size_t i = 0; i < nitems(ident.btxt); i++) {
		c = ident.btxt[i];
		if (!bhnd_nv_isprint(c))
			return (ENXIO);
	}

	/* The first character should either be a valid key char (alpha),
	 * whitespace, or the start of a comment ('#') */
	c = ident.btxt[0];
	if (!bhnd_nv_isspace(c) && !bhnd_nv_isalpha(c) && c != '#')
		return (ENXIO);

	/* We assert a low priority, given that we've only scanned an
	 * initial few bytes of the file. */
	return (BHND_NVRAM_DATA_PROBE_MAYBE);
}

/**
 * Parser states for bhnd_nvram_bcm_getvar_direct_common().
 */
typedef enum {
	BTXT_PARSE_LINE_START,
	BTXT_PARSE_KEY,
	BTXT_PARSE_KEY_END,
	BTXT_PARSE_NEXT_LINE,
	BTXT_PARSE_VALUE_START,
	BTXT_PARSE_VALUE
} btxt_parse_state;

static int
bhnd_nvram_btxt_getvar_direct(struct bhnd_nvram_io *io, const char *name,
    void *outp, size_t *olen, bhnd_nvram_type otype)
{
	char				 buf[512];
	btxt_parse_state		 pstate;
	size_t				 limit, offset;
	size_t				 buflen, bufpos;
	size_t				 namelen, namepos;
	size_t				 vlen;
	int				 error;

	limit = bhnd_nvram_io_getsize(io);
	offset = 0;

	/* Loop our parser until we find the requested variable, or hit EOF */
	pstate = BTXT_PARSE_LINE_START;
	buflen = 0;
	bufpos = 0;
	namelen = strlen(name);
	namepos = 0;
	vlen = 0;

	while ((offset - bufpos) < limit) {
		BHND_NV_ASSERT(bufpos <= buflen,
		    ("buf position invalid (%zu > %zu)", bufpos, buflen));
		BHND_NV_ASSERT(buflen <= sizeof(buf),
		    ("buf length invalid (%zu > %zu", buflen, sizeof(buf)));

		/* Repopulate our parse buffer? */
		if (buflen - bufpos == 0) {
			BHND_NV_ASSERT(offset < limit, ("offset overrun"));

			buflen = bhnd_nv_ummin(sizeof(buf), limit - offset);
			bufpos = 0;

			error = bhnd_nvram_io_read(io, offset, buf, buflen);
			if (error)
				return (error);

			offset += buflen;
		}

		switch (pstate) {
		case BTXT_PARSE_LINE_START:
			BHND_NV_ASSERT(bufpos < buflen, ("empty buffer!"));

			/* Reset name matching position */
			namepos = 0;

			/* Trim any leading whitespace */
			while (bufpos < buflen && bhnd_nv_isspace(buf[bufpos]))
			{
				bufpos++;
			}

			if (bufpos == buflen) {
				/* Continue parsing the line */
				pstate = BTXT_PARSE_LINE_START;
			} else if (bufpos < buflen && buf[bufpos] == '#') {
				/* Comment; skip to next line */
				pstate = BTXT_PARSE_NEXT_LINE;
			} else {
				/* Start name matching */
				pstate = BTXT_PARSE_KEY;
			}

			break;

		case BTXT_PARSE_KEY: {
			size_t navail, nleft;

			nleft = namelen - namepos;
			navail = bhnd_nv_ummin(buflen - bufpos, nleft);

			if (strncmp(name+namepos, buf+bufpos, navail) == 0) {
				/* Matched */
				namepos += navail;
				bufpos += navail;

				if (namepos == namelen) {
					/* Matched the full variable; look for
					 * its trailing delimiter */
					pstate = BTXT_PARSE_KEY_END;
				} else {
					/* Continue matching the name */
					pstate = BTXT_PARSE_KEY;
				}
			} else {
				/* No match; advance to next entry and restart
				 * name matching */
				pstate = BTXT_PARSE_NEXT_LINE;
			}

			break;
		}

		case BTXT_PARSE_KEY_END:
			BHND_NV_ASSERT(bufpos < buflen, ("empty buffer!"));

			if (buf[bufpos] == '=') {
				/* Key fully matched; advance past '=' and
				 * parse the value */
				bufpos++;
				pstate = BTXT_PARSE_VALUE_START;
			} else {
				/* No match; advance to next line and restart
				 * name matching */
				pstate = BTXT_PARSE_NEXT_LINE;
			}

			break;

		case BTXT_PARSE_NEXT_LINE: {
			const char *p;

			/* Scan for a '\r', '\n', or '\r\n' terminator */
			p = memchr(buf+bufpos, '\n', buflen - bufpos);
			if (p == NULL)
				p = memchr(buf+bufpos, '\r', buflen - bufpos);

			if (p != NULL) {
				/* Found entry terminator; restart name
				 * matching at next line */
				pstate = BTXT_PARSE_LINE_START;
				bufpos = (p - buf);
			} else {
				/* Consumed full buffer looking for newline; 
				 * force repopulation of the buffer and
				 * retry */
				pstate = BTXT_PARSE_NEXT_LINE;
				bufpos = buflen;
			}

			break;
		}

		case BTXT_PARSE_VALUE_START: {
			const char *p;

			/* Scan for a terminating newline */
			p = memchr(buf+bufpos, '\n', buflen - bufpos);
			if (p == NULL)
				p = memchr(buf+bufpos, '\r', buflen - bufpos);

			if (p != NULL) {
				/* Found entry terminator; parse the value */
				vlen = p - &buf[bufpos];
				pstate = BTXT_PARSE_VALUE;

			} else if (p == NULL && offset == limit) {
				/* Hit EOF without a terminating newline;
				 * treat the entry as implicitly terminated */
				vlen = buflen - bufpos;
				pstate = BTXT_PARSE_VALUE;

			} else if (p == NULL && bufpos > 0) {
				size_t	nread;

				/* Move existing value data to start of
				 * buffer */
				memmove(buf, buf+bufpos, buflen - bufpos);
				buflen = bufpos;
				bufpos = 0;

				/* Populate full buffer to allow retry of
				 * value parsing */
				nread = bhnd_nv_ummin(sizeof(buf) - buflen,
				    limit - offset);

				error = bhnd_nvram_io_read(io, offset,
				    buf+buflen, nread);
				if (error)
					return (error);

				offset += nread;
				buflen += nread;
			} else {
				/* Value exceeds our buffer capacity */
				BHND_NV_LOG("cannot parse value for '%s' "
				    "(exceeds %zu byte limit)\n", name,
				    sizeof(buf));

				return (ENXIO);
			}

			break;
		}

		case BTXT_PARSE_VALUE:
			BHND_NV_ASSERT(vlen <= buflen, ("value buf overrun"));

			/* Trim any trailing whitespace */
			while (vlen > 0 && bhnd_nv_isspace(buf[bufpos+vlen-1]))
				vlen--;

			/* Write the value to the caller's buffer */
			return (bhnd_nvram_value_coerce(buf+bufpos, vlen,
			    BHND_NVRAM_TYPE_STRING, outp, olen, otype));
		}
	}

	/* Variable not found */
	return (ENOENT);
}

static int
bhnd_nvram_btxt_serialize(bhnd_nvram_data_class *cls, bhnd_nvram_plist *props,
    bhnd_nvram_plist *options, void *outp, size_t *olen)
{
	bhnd_nvram_prop	*prop;
	size_t		 limit, nbytes;
	int		 error;

	/* Determine output byte limit */
	if (outp != NULL)
		limit = *olen;
	else
		limit = 0;

	nbytes = 0;

	/* Write all properties */
	prop = NULL;
	while ((prop = bhnd_nvram_plist_next(props, prop)) != NULL) {
		const char	*name;
		char		*p;
		size_t		 prop_limit;
		size_t		 name_len, value_len;

		if (outp == NULL || limit < nbytes) {
			p = NULL;
			prop_limit = 0;
		} else {
			p = ((char *)outp) + nbytes;
			prop_limit = limit - nbytes;
		}

		/* Fetch and write 'name=' to output */
		name = bhnd_nvram_prop_name(prop);
		name_len = strlen(name) + 1;

		if (prop_limit > name_len) {
			memcpy(p, name, name_len - 1);
			p[name_len - 1] = '=';

			prop_limit -= name_len;
			p += name_len;
		} else {
			prop_limit = 0;
			p = NULL;
		}

		/* Advance byte count */
		if (SIZE_MAX - nbytes < name_len)
			return (EFTYPE); /* would overflow size_t */

		nbytes += name_len;

		/* Write NUL-terminated value to output, rewrite NUL as
		 * '\n' record delimiter */
		value_len = prop_limit;
		error = bhnd_nvram_prop_encode(prop, p, &value_len,
		    BHND_NVRAM_TYPE_STRING);
		if (p != NULL && error == 0) {
			/* Replace trailing '\0' with newline */
			BHND_NV_ASSERT(value_len > 0, ("string length missing "
			    "minimum required trailing NUL"));

			*(p + (value_len - 1)) = '\n';
		} else if (error && error != ENOMEM) {
			/* If encoding failed for any reason other than ENOMEM
			 * (which we'll detect and report after encoding all
			 * properties), return immediately */
			BHND_NV_LOG("error serializing %s to required type "
			    "%s: %d\n", name,
			    bhnd_nvram_type_name(BHND_NVRAM_TYPE_STRING),
			    error);
			return (error);
		}

		/* Advance byte count */
		if (SIZE_MAX - nbytes < value_len)
			return (EFTYPE); /* would overflow size_t */

		nbytes += value_len;
	}

	/* Provide required length */
	*olen = nbytes;
	if (limit < *olen) {
		if (outp == NULL)
			return (0);

		return (ENOMEM);
	}

	return (0);
}

/**
 * Initialize @p btxt with the provided board text data mapped by @p src.
 * 
 * @param btxt A newly allocated data instance.
 */
static int
bhnd_nvram_btxt_init(struct bhnd_nvram_btxt *btxt, struct bhnd_nvram_io *src)
{
	const void		*ptr;
	const char		*name, *value;
	size_t			 name_len, value_len;
	size_t			 line_len, env_len;
	size_t			 io_offset, io_size, str_size;
	int			 error;

	BHND_NV_ASSERT(btxt->data == NULL, ("btxt data already allocated"));

	if ((btxt->data = bhnd_nvram_iobuf_copy(src)) == NULL)
		return (ENOMEM);

	io_size = bhnd_nvram_io_getsize(btxt->data);
	io_offset = 0;

	/* Fetch a pointer mapping the entirity of the board text data */
	error = bhnd_nvram_io_read_ptr(btxt->data, 0x0, &ptr, io_size, NULL);
	if (error)
		return (error);

	/* Determine the actual size, minus any terminating NUL. We
	 * parse NUL-terminated C strings, but do not include NUL termination
	 * in our internal or serialized representations */
	str_size = strnlen(ptr, io_size);

	/* If the terminating NUL is not found at the end of the buffer,
	 * this is BCM-RAW or other NUL-delimited NVRAM format. */
	if (str_size < io_size && str_size + 1 < io_size)
		return (EINVAL);

	/* Adjust buffer size to account for NUL termination (if any) */
	io_size = str_size;
	if ((error = bhnd_nvram_io_setsize(btxt->data, io_size)))
		return (error);

	/* Process the buffer */
	btxt->count = 0;
	while (io_offset < io_size) {
		const void	*envp;

		/* Seek to the next key=value entry */
		if ((error = bhnd_nvram_btxt_seek_next(btxt->data, &io_offset)))
			return (error);

		/* Determine the entry and line length */
		error = bhnd_nvram_btxt_entry_len(btxt->data, io_offset,
		    &line_len, &env_len);
		if (error)
			return (error);

		/* EOF? */
		if (env_len == 0) {
			BHND_NV_ASSERT(io_offset == io_size,
		           ("zero-length record returned from "
			    "bhnd_nvram_btxt_seek_next()"));
			break;
		}

		/* Fetch a pointer to the line start */
		error = bhnd_nvram_io_read_ptr(btxt->data, io_offset, &envp,
		    env_len, NULL);
		if (error)
			return (error);

		/* Parse the key=value string */
		error = bhnd_nvram_parse_env(envp, env_len, '=', &name,
		    &name_len, &value, &value_len);
		if (error) {
			return (error);
		}

		/* Insert a '\0' character, replacing the '=' delimiter and
		 * allowing us to vend references directly to the variable
		 * name */
		error = bhnd_nvram_io_write(btxt->data, io_offset+name_len,
		    &(char){'\0'}, 1);
		if (error)
			return (error);

		/* Add to variable count */
		btxt->count++;

		/* Advance past EOL */
		io_offset += line_len;
	}

	return (0);
}

static int
bhnd_nvram_btxt_new(struct bhnd_nvram_data *nv, struct bhnd_nvram_io *io)
{
	struct bhnd_nvram_btxt	*btxt;
	int			 error;

	/* Allocate and initialize the BTXT data instance */
	btxt = (struct bhnd_nvram_btxt *)nv;

	/* Parse the BTXT input data and initialize our backing
	 * data representation */
	if ((error = bhnd_nvram_btxt_init(btxt, io))) {
		bhnd_nvram_btxt_free(nv);
		return (error);
	}

	return (0);
}

static void
bhnd_nvram_btxt_free(struct bhnd_nvram_data *nv)
{
	struct bhnd_nvram_btxt *btxt = (struct bhnd_nvram_btxt *)nv;
	if (btxt->data != NULL)
		bhnd_nvram_io_free(btxt->data);
}

size_t
bhnd_nvram_btxt_count(struct bhnd_nvram_data *nv)
{
	struct bhnd_nvram_btxt *btxt = (struct bhnd_nvram_btxt *)nv;
	return (btxt->count);
}

static bhnd_nvram_plist *
bhnd_nvram_btxt_options(struct bhnd_nvram_data *nv)
{
	return (NULL);
}

static uint32_t
bhnd_nvram_btxt_caps(struct bhnd_nvram_data *nv)
{
	return (BHND_NVRAM_DATA_CAP_READ_PTR|BHND_NVRAM_DATA_CAP_DEVPATHS);
}

static void *
bhnd_nvram_btxt_find(struct bhnd_nvram_data *nv, const char *name)
{
	return (bhnd_nvram_data_generic_find(nv, name));
}

static const char *
bhnd_nvram_btxt_next(struct bhnd_nvram_data *nv, void **cookiep)
{
	struct bhnd_nvram_btxt	*btxt;
	const void		*nptr;
	size_t			 io_offset, io_size;
	int			 error;

	btxt = (struct bhnd_nvram_btxt *)nv;

	io_size = bhnd_nvram_io_getsize(btxt->data);

	if (*cookiep == NULL) {
		/* Start search at initial file offset */
		io_offset = 0x0;
	} else {
		/* Start search after the current entry */
		io_offset = bhnd_nvram_btxt_cookiep_to_offset(btxt, *cookiep);

		/* Scan past the current entry by finding the next newline */
		error = bhnd_nvram_btxt_seek_eol(btxt->data, &io_offset);
		if (error) {
			BHND_NV_LOG("unexpected error in seek_eol(): %d\n",
			    error);
			return (NULL);
		}
	}

	/* Already at EOF? */
	if (io_offset == io_size)
		return (NULL);

	/* Seek to the first valid entry, or EOF */
	if ((error = bhnd_nvram_btxt_seek_next(btxt->data, &io_offset))) {
		BHND_NV_LOG("unexpected error in seek_next(): %d\n", error);
		return (NULL);
	}

	/* Hit EOF? */
	if (io_offset == io_size)
		return (NULL);

	/* Provide the new cookie for this offset */
	*cookiep = bhnd_nvram_btxt_offset_to_cookiep(btxt, io_offset);

	/* Fetch the name pointer; it must be at least 1 byte long */
	error = bhnd_nvram_io_read_ptr(btxt->data, io_offset, &nptr, 1, NULL);
	if (error) {
		BHND_NV_LOG("unexpected error in read_ptr(): %d\n", error);
		return (NULL);
	}

	/* Return the name pointer */
	return (nptr);
}

static int
bhnd_nvram_btxt_getvar_order(struct bhnd_nvram_data *nv, void *cookiep1,
    void *cookiep2)
{
	if (cookiep1 < cookiep2)
		return (-1);

	if (cookiep1 > cookiep2)
		return (1);

	return (0);
}

static int
bhnd_nvram_btxt_getvar(struct bhnd_nvram_data *nv, void *cookiep, void *buf,
    size_t *len, bhnd_nvram_type type)
{
	return (bhnd_nvram_data_generic_rp_getvar(nv, cookiep, buf, len, type));
}

static int
bhnd_nvram_btxt_copy_val(struct bhnd_nvram_data *nv, void *cookiep,
    bhnd_nvram_val **value)
{
	return (bhnd_nvram_data_generic_rp_copy_val(nv, cookiep, value));
}

const void *
bhnd_nvram_btxt_getvar_ptr(struct bhnd_nvram_data *nv, void *cookiep,
    size_t *len, bhnd_nvram_type *type)
{
	struct bhnd_nvram_btxt	*btxt;
	const void		*eptr;
	const char		*vptr;
	size_t			 io_offset, io_size;
	size_t			 line_len, env_len;
	int			 error;

	btxt = (struct bhnd_nvram_btxt *)nv;

	io_size = bhnd_nvram_io_getsize(btxt->data);
	io_offset = bhnd_nvram_btxt_cookiep_to_offset(btxt, cookiep);

	/* At EOF? */
	if (io_offset == io_size)
		return (NULL);

	/* Determine the entry length */
	error = bhnd_nvram_btxt_entry_len(btxt->data, io_offset, &line_len,
	    &env_len);
	if (error) {
		BHND_NV_LOG("unexpected error in entry_len(): %d\n", error);
		return (NULL);
	}

	/* Fetch the entry's value pointer and length */
	error = bhnd_nvram_io_read_ptr(btxt->data, io_offset, &eptr, env_len,
	    NULL);
	if (error) {
		BHND_NV_LOG("unexpected error in read_ptr(): %d\n", error);
		return (NULL);
	}

	error = bhnd_nvram_parse_env(eptr, env_len, '\0', NULL, NULL, &vptr,
	    len);
	if (error) {
		BHND_NV_LOG("unexpected error in parse_env(): %d\n", error);
		return (NULL);
	}

	/* Type is always CSTR */
	*type = BHND_NVRAM_TYPE_STRING;

	return (vptr);
}

static const char *
bhnd_nvram_btxt_getvar_name(struct bhnd_nvram_data *nv, void *cookiep)
{
	struct bhnd_nvram_btxt	*btxt;
	const void		*ptr;
	size_t			 io_offset, io_size;
	int			 error;

	btxt = (struct bhnd_nvram_btxt *)nv;

	io_size = bhnd_nvram_io_getsize(btxt->data);
	io_offset = bhnd_nvram_btxt_cookiep_to_offset(btxt, cookiep);

	/* At EOF? */
	if (io_offset == io_size)
		BHND_NV_PANIC("invalid cookiep: %p", cookiep);

	/* Variable name is found directly at the given offset; trailing
	 * NUL means we can assume that it's at least 1 byte long */
	error = bhnd_nvram_io_read_ptr(btxt->data, io_offset, &ptr, 1, NULL);
	if (error)
		BHND_NV_PANIC("unexpected error in read_ptr(): %d\n", error);

	return (ptr);
}

/**
 * Return a cookiep for the given I/O offset.
 */
static void *
bhnd_nvram_btxt_offset_to_cookiep(struct bhnd_nvram_btxt *btxt,
    size_t io_offset)
{
	const void	*ptr;
	int		 error;

	BHND_NV_ASSERT(io_offset < bhnd_nvram_io_getsize(btxt->data),
	    ("io_offset %zu out-of-range", io_offset));
	BHND_NV_ASSERT(io_offset < UINTPTR_MAX,
	    ("io_offset %#zx exceeds UINTPTR_MAX", io_offset));

	error = bhnd_nvram_io_read_ptr(btxt->data, 0x0, &ptr, io_offset, NULL);
	if (error)
		BHND_NV_PANIC("error mapping offset %zu: %d", io_offset, error);

	ptr = (const uint8_t *)ptr + io_offset;
	return (__DECONST(void *, ptr));
}

/* Convert a cookiep back to an I/O offset */
static size_t
bhnd_nvram_btxt_cookiep_to_offset(struct bhnd_nvram_btxt *btxt, void *cookiep)
{
	const void	*ptr;
	intptr_t	 offset;
	size_t		 io_size;
	int		 error;

	BHND_NV_ASSERT(cookiep != NULL, ("null cookiep"));

	io_size = bhnd_nvram_io_getsize(btxt->data);
	error = bhnd_nvram_io_read_ptr(btxt->data, 0x0, &ptr, io_size, NULL);
	if (error)
		BHND_NV_PANIC("error mapping offset %zu: %d", io_size, error);

	offset = (const uint8_t *)cookiep - (const uint8_t *)ptr;
	BHND_NV_ASSERT(offset >= 0, ("invalid cookiep"));
	BHND_NV_ASSERT((uintptr_t)offset < SIZE_MAX, ("cookiep > SIZE_MAX)"));
	BHND_NV_ASSERT((uintptr_t)offset <= io_size, ("cookiep > io_size)"));

	return ((size_t)offset);
}

/* Determine the entry length and env 'key=value' string length of the entry
 * at @p offset */
static int
bhnd_nvram_btxt_entry_len(struct bhnd_nvram_io *io, size_t offset,
    size_t *line_len, size_t *env_len)
{
	const uint8_t	*baseptr, *p;
	const void	*rbuf;
	size_t		 nbytes;
	int		 error;

	/* Fetch read buffer */
	if ((error = bhnd_nvram_io_read_ptr(io, offset, &rbuf, 0, &nbytes)))
		return (error);

	/* Find record termination (EOL, or '#') */
	p = rbuf;
	baseptr = rbuf;
	while ((size_t)(p - baseptr) < nbytes) {
		if (*p == '#' || *p == '\n' || *p == '\r')
			break;

		p++;
	}

	/* Got line length, now trim any trailing whitespace to determine
	 * actual env length */
	*line_len = p - baseptr;
	*env_len = *line_len;

	for (size_t i = 0; i < *line_len; i++) {
		char c = baseptr[*line_len - i - 1];
		if (!bhnd_nv_isspace(c))
			break;

		*env_len -= 1;
	}

	return (0);
}

/* Seek past the next line ending (\r, \r\n, or \n) */
static int
bhnd_nvram_btxt_seek_eol(struct bhnd_nvram_io *io, size_t *offset)
{
	const uint8_t	*baseptr, *p;
	const void	*rbuf;
	size_t		 nbytes;
	int		 error;

	/* Fetch read buffer */
	if ((error = bhnd_nvram_io_read_ptr(io, *offset, &rbuf, 0, &nbytes)))
		return (error);

	baseptr = rbuf;
	p = rbuf;
	while ((size_t)(p - baseptr) < nbytes) {
		char c = *p;

		/* Advance to next char. The next position may be EOF, in which
		 * case a read will be invalid */
		p++;

		if (c == '\r') {
			/* CR, check for optional LF */
			if ((size_t)(p - baseptr) < nbytes) {
				if (*p == '\n')
					p++;
			}

			break;
		} else if (c == '\n') {
			break;
		}
	}

	/* Hit newline or EOF */
	*offset += (p - baseptr);
	return (0);
}

/* Seek to the next valid non-comment line (or EOF) */
static int
bhnd_nvram_btxt_seek_next(struct bhnd_nvram_io *io, size_t *offset)
{
	const uint8_t	*baseptr, *p;
	const void	*rbuf;
	size_t		 nbytes;
	int		 error;

	/* Fetch read buffer */
	if ((error = bhnd_nvram_io_read_ptr(io, *offset, &rbuf, 0, &nbytes)))
		return (error);

	/* Skip leading whitespace and comments */
	baseptr = rbuf;
	p = rbuf;
	while ((size_t)(p - baseptr) < nbytes) {
		char c = *p;

		/* Skip whitespace */
		if (bhnd_nv_isspace(c)) {
			p++;
			continue;
		}

		/* Skip entire comment line */
		if (c == '#') {
			size_t line_off = *offset + (p - baseptr);

			if ((error = bhnd_nvram_btxt_seek_eol(io, &line_off)))
				return (error);

			p = baseptr + (line_off - *offset);
			continue;
		}

		/* Non-whitespace, non-comment */
		break;
	}

	*offset += (p - baseptr);
	return (0);
}

static int
bhnd_nvram_btxt_filter_setvar(struct bhnd_nvram_data *nv, const char *name,
    bhnd_nvram_val *value, bhnd_nvram_val **result)
{
	bhnd_nvram_val	*str;
	const char	*inp;
	bhnd_nvram_type	 itype;
	size_t		 ilen;
	int		 error;

	/* Name (trimmed of any path prefix) must be valid */
	if (!bhnd_nvram_validate_name(bhnd_nvram_trim_path_name(name)))
		return (EINVAL);

	/* Value must be bcm-formatted string */
	error = bhnd_nvram_val_convert_new(&str, &bhnd_nvram_val_bcm_string_fmt,
	    value, BHND_NVRAM_VAL_DYNAMIC);
	if (error)
		return (error);

	/* Value string must not contain our record delimiter character ('\n'),
	 * or our comment character ('#') */
	inp = bhnd_nvram_val_bytes(str, &ilen, &itype);
	BHND_NV_ASSERT(itype == BHND_NVRAM_TYPE_STRING, ("non-string value"));
	for (size_t i = 0; i < ilen; i++) {
		switch (inp[i]) {
		case '\n':
		case '#':
			BHND_NV_LOG("invalid character (%#hhx) in value\n",
			    inp[i]);
			bhnd_nvram_val_release(str);
			return (EINVAL);
		}
	}

	/* Success. Transfer result ownership to the caller. */
	*result = str;
	return (0);
}

static int
bhnd_nvram_btxt_filter_unsetvar(struct bhnd_nvram_data *nv, const char *name)
{
	/* We permit deletion of any variable */
	return (0);
}