xref: /netbsd-src/usr.sbin/installboot/evboards.c (revision a4d52a8bafa0c5b0f585ec80a7499256c3677a93)
1 /*	$NetBSD: evboards.c,v 1.8 2022/11/01 19:51:46 andvar Exp $	*/
2 
3 /*-
4  * Copyright (c) 2019 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #if HAVE_NBTOOL_CONFIG_H
33 #include "nbtool_config.h"
34 #endif
35 
36 #include <sys/cdefs.h>
37 #if !defined(__lint)
38 __RCSID("$NetBSD: evboards.c,v 1.8 2022/11/01 19:51:46 andvar Exp $");
39 #endif  /* !__lint */
40 
41 #include <sys/types.h>
42 #include <sys/param.h>		/* for roundup() */
43 #include <sys/stat.h>
44 #include <assert.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <fts.h>
49 #include <inttypes.h>
50 #include <limits.h>
51 #include <stdarg.h>
52 #include <stdlib.h>
53 #include <stdio.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #ifdef SUPPORT_FDT
58 #include "libfdt.h"
59 #endif
60 
61 #if !HAVE_NBTOOL_CONFIG_H
62 #include <sys/utsname.h>
63 
64 #ifdef SUPPORT_OPENFIRMWARE
65 #include <sys/ioctl.h>
66 #include <dev/ofw/openfirmio.h>
67 #endif
68 
69 #endif /* ! HAVE_NBTOOL_CONFIG_H */
70 
71 #include "installboot.h"
72 #include "evboards.h"
73 
74 /*
75  * The board database is implemented as a property list.  The base
76  * system provides a set of known boards, keyed by their "compatible"
77  * device tree property.
78  *
79  * The database provided by the base system is meant to help guide
80  * the user as to which u-boot package needs to be installed on the
81  * system in order to write the boot loader to the boot media.  The
82  * base board plist is specific to the $MACHINE (e.g. "evbarm"), and
83  * is installed along with the build tools, e.g.:
84  *
85  * (native location)
86  *	/usr/sbin/installboot
87  *	/usr/share/installboot/evbarm/boards.plist
88  *	/usr/share/installboot/evbmips/boards.plist
89  *
90  * (example cross host tool location)
91  *	/usr/local/xnbsd/bin/nbinstallboot
92  *	/usr/local/xnbsd/share/installboot/evbarm/boards.plist
93  *	/usr/local/xnbsd/share/installboot/evbmips/boards.plist
94  *
95  * The schema of the base board plist is as follows:
96  *
97  * <plist>
98  * <dict>
99  *	<!--
100  *	  -- Key: string matching a "compatible" DT property.
101  *	  -- Value: dictionary representing a board object.
102  *	  -- (required)
103  *	  -->
104  *	<key>example,example-board</key>
105  *	<dict>
106  *		<!--
107  *		  -- Key: "description".
108  *		  -- Value: string containing the board description.
109  *		  -- (required)
110  *		  -->
111  *		<key>description</key>
112  *		<string>Example Co. Example Board</string>
113  *
114  *		<!--
115  *		  -- Key: "u-boot-pkg".
116  *		  -- Value: string representing the board-specific
117  *		  --        portion of the u-boot package name.
118  *		  --        In this example, the package's full name
119  *		  --        is "u-boot-exampleboard".  This is used
120  *		  --        to recommend to the user which u-boot
121  *		  --        package to install.  If not present, then
122  *		  --        no package recommendation will be made.
123  *		  -- (optional)
124  *		  -->
125  *		<key>u-boot-pkg</key>
126  *		<string>exampleboard</string>
127  *	</dict>
128  * </dict>
129  * </plist>
130  *
131  * Individual u-boot packages install their own overlay property list
132  * files that installboot(8) then scans for.  These overlay files are
133  * named "installboot.plist", and are installed alongside the u-boot
134  * binaries by the individual u-boot packages, for example:
135  *
136  *	/usr/pkg/share/u-boot/exampleboard/installboot.plist
137  *	/usr/pkg/share/u-boot/exampleboard/u-boot-with-spl.bin
138  *
139  * installboot(8) scans a set of directories looking for "installboot.plist"
140  * overlay files one directory deep.  For example:
141  *
142  *	/usr/pkg/share/u-boot/
143  *				exampleboard/installboot.plist
144  *				superarmdeluxe/installboot.plist
145  *				dummy/
146  *
147  * In this example, "/usr/pkg/share/u-boot" is scanned, it would identify
148  * "exampleboard" and "superarmdeluxe" as directories containing overlays
149  * and load them.
150  *
151  * The default path scanned for u-boot packages is:
152  *
153  *	/usr/pkg/share/u-boot
154  *
155  * This can be overridden with either the INSTALLBOOT_UBOOT_PATHS
156  * environment variable or the command line option -u, which contains
157  * a colon-separated list of directories, e.g.:
158  *
159  *	/usr/pkg/share/u-boot:/home/jmcneill/hackityhack/u-boot
160  *
161  * The scan only consults the top-level children of the specified directory.
162  *
163  * Each overlay includes complete board objects that entirely replace
164  * the system-provided board objects in memory.  Some of the keys in
165  * overlay board objects are computed at run-time and should not appear
166  * in the plists loaded from the file system.
167  *
168  * The schema of the overlay board plists are as follows:
169  *
170  * <plist>
171  * <dict>
172  *	<!--
173  *	  -- Key: string matching a "compatible" DT property.
174  *	  -- Value: dictionary representing a board object.
175  *	  -- (required)
176  *	  -->
177  *	<key>example,example-board</key>
178  *	<dict>
179  *		<!--
180  *		  -- Key: "description".
181  *		  -- Value: string containing the board description.
182  *		  -- (required)
183  *		  -->
184  *		<key>description</key>
185  *		<string>Example Co. Example Board</string>
186  *
187  *		<!--
188  *		  -- Key: "u-boot-install".
189  *		  --      (and variants; see discussion below)
190  *		  --      "u-boot-install-emmc", etc.).
191  *		  -- Value: Array of u-boot installation step objects,
192  *		  --        as described below.
193  *		  -- (required)
194  *		  --
195  *		  -- At least one of these objects is required.  If the
196  *		  -- board uses a single set of steps for all boot media
197  *		  -- types, then it should provide just "u-boot-install".
198  *		  -- Otherwise, it would provide one or more objects
199  *		  -- with names reflecting the media type, e.g.:
200  *		  --
201  *		  --	"u-boot-install-sdmmc"	(for SD cards)
202  *		  --	"u-boot-install-emmc"	(for eMMC modules)
203  *		  --	"u-boot-install-usb"	(for USB block storage)
204  *		  --	"u-boot-install-spi"	(for SPI NOR flash)
205  *		  --
206  *		  -- These installation steps will be selectable using
207  *		  -- the "media=..." option to installboot(8).
208  *		  -->
209  *		<key>u-boot-install</key>
210  *		<array>
211  *			<!-- see installation object discussion below. -->
212  *		</array>
213  *
214  *		<!--
215  *		  -- Key: "runtime-u-boot-path"
216  *		  -- Value: A string representing the path to the u-boot
217  *		  --        binary files needed to install the boot loader.
218  *		  --        This value is computed at run-time and is the
219  *		  --        same directory in which the installboot.plist
220  *		  --        file for that u-boot package is located.
221  *		  --        This key/value pair should never be included
222  *		  --        in an installboot.plist file, and including it
223  *		  --	    will cause the overlay to be rejected.
224  *		  -- (computed at run-time)
225  *		  -->
226  *		<key>runtime-u-boot-path</key>
227  *		<string>/usr/pkg/share/u-boot/exampleboard</string>
228  *	</dict>
229  * </dict>
230  * </plist>
231  *
232  * The installation objects provide a description of the steps needed
233  * to install u-boot on the boot media.  Each installation object it
234  * itself an array of step object.
235  *
236  * A basic installation object has a single step that instructs
237  * installboot(8) to write a file to a specific offset onto the
238  * boot media.
239  *
240  *	<key>u-boot-install</key>
241  *	<!-- installation object -->
242  *	<array>
243  *		<!-- step object -->
244  *		<dict>
245  *			<!--
246  *			  -- Key: "file-name".
247  *			  -- Value: a string naming the file to be
248  *			  --        written to the media.
249  *			  -- (required)
250  *			  -->
251  *			<key>file-name</key>
252  *			<string>u-boot-with-spl.bin</string>
253  *
254  *			<!--
255  *			  -- Key: "image-offset".
256  *			  -- Value: an integer specifying the offset
257  *			  --        into the output image or device
258  *			  --        where to write the file.  Defaults
259  *			  --        to 0 if not specified.
260  *			  -- (optional)
261  *			  -->
262  *			<key>image-offset</key>
263  *			<integer>8192</integer>
264  *		</dict>
265  *	</array>
266  *
267  * Some installations require multiple steps with special handling.
268  *
269  *	<key>u-boot-install</key>
270  *	<array>
271  *		<--
272  *		 -- Step 1: Write the initial portion of the boot
273  *		 -- loader onto the media.  The loader has a "hole"
274  *		 -- to leave room for the MBR partition table.  Take
275  *		 -- care not to scribble over the table.
276  *		 -->
277  *		<dict>
278  *			<key>file-name</key>
279  *			<string>u-boot-img.bin</string>
280  *
281  *			<!--
282  *			  -- Key: "file-size".
283  *			  -- Value: an integer specifying the amount of
284  *			  --        data from the file to be written to the
285  *			  --        output.  Defaults to "to end of file" if
286  *			  --        not specified.
287  *			  -- (optional)
288  *			  -->
289  *			<!-- Stop short of the MBR partition table. -->
290  *			<key>file-size</key>
291  *			<integer>442</integer>
292  *
293  *			<!--
294  *			  -- Key: "preserve".
295  *			  -- Value: a boolean indicating that any partial
296  *			  --        output block should preserve any pre-
297  *			  --        existing contents of that block for
298  *			  --        the portion of the of the block not
299  *			  --        overwritten by the input file.
300  *			  --        (read-modify-write)
301  *			  -- (optional)
302  *			  -->
303  *			<!-- Preserve the MBR partition table. -->
304  *			<key>preserve</key>
305  *			<true/>
306  *		</dict>
307  *		<--
308  *		 -- Step 2: Write the rest of the loader after the
309  *		 -- MBR partition table.
310  *		 -->
311  *		<dict>
312  *			<key>file-name</key>
313  *			<string>u-boot-img.bin</string>
314  *
315  *			<!--
316  *			  -- Key: "file-offset".
317  *			  -- Value: an integer specifying the offset into
318  *			  --        the input file from where to start
319  *			  --        copying to the output.
320  *			  -- (optional)
321  *			  -->
322  *			<key>file-offset</key>
323  *			<integer>512</integer>
324  *
325  *			<!-- ...just after the MBR partition table. -->
326  *			<key>image-offset</key>
327  *			<integer>512</integer>
328  *		</dict>
329  *	</array>
330  *
331  * There are some additional directives for installing on raw flash devices:
332  *
333  *	<key>u-boot-install-spi</key>
334  *	<array>
335  *		<!-- This board's SPI NOR flash is 16Mbit (2MB) in size,
336  *		  -- arranged as 32 512Kbit (64KB) blocks.
337  *		<dict>
338  *			<key>file-name</key>
339  *			<string>u-boot-with-spl.bin</string>
340  *
341  *			<!-- Key: "input-block-size".
342  *			  -- Value: an integer specifying how much file
343  *			  --        data to read per input block before
344  *			  --        padding.  Must be used in conjunction
345  *			  --        with "input-pad-size".
346  *			  -- (optional)
347  *			  -->
348  *			<key>input-block-size</key>
349  *			<integer>2048</integer>
350  *
351  *			<!-- Key: "input-pad-size".
352  *			  -- Value: an integer specifying the amount of
353  *			  --        zero padding inserted per input block.
354  *			  --        Must be used in conjunction with
355  *			  --        "input-block-size".
356  *			  -- (optional)
357  *			  -->
358  *			<key>input-pad-size</key>
359  *			<integer>2048</integer>
360  *
361  *			<!-- Key: "output-size".
362  *			  -- Value: an integer specifying the total
363  *			  --        size to be written to the output
364  *			  --        device.  This is used when writing
365  *			  --        a bootloader to a raw flash memory
366  *			  --        device such as a SPI NOR flash.
367  *			  --        The boot loader MUST fit within
368  *			  --        this size and the output will be
369  *			  --        padded to this size with zeros.
370  *			  --
371  *			  --        If the "output-block-size" key (below)
372  *			  --        is also specified, then this value
373  *			  --        must be a multiple of the output block
374  *			  --        size.
375  *			  -- (optional)
376  *			  -->
377  *			<key>output-size</key>
378  *			<integer>2097152</integer>
379  *
380  *			<-- Key: "output-block-size"
381  *			 -- Value: an integer specifying the size of
382  *			 --        the blocks used to write to the
383  *			 --        output device.  If the output device
384  *			 --        simulates a disk block storage device,
385  *			 --        then this value must be a multiple of
386  *			 --        the reported sector size.
387  *			 -- (optional)
388  *			 -->
389  *			<key>output-block-size</key>
390  *			<integer>65536</integer>
391  *		</dict>
392  *	</array>
393  *
394  * For boards that require a media specification to be provided, it
395  * may be the case that two media types have identical steps.  It
396  * could be confusing for users to see a list of media types that does
397  * not include the media type on which they are installing, so there
398  * is an alias capability:
399  *
400  *	<key>u-boot-install-spi</key>
401  *	<array>
402  *		.
403  *		.
404  *		.
405  *	</array>
406  *	<key>u-boot-install-sdmmc</key>
407  *	<array>
408  *		.
409  *		.
410  *		.
411  *	</array>
412  *	<-- Steps for eMMC are identical to SDMMC on this board. -->
413  *	<key>u-boot-install-emmc</key>
414  *	<string>u-boot-install-sdmmc</string>
415  */
416 
417 /*
418  * make_path --
419  *	Build a path into the given buffer with the specified
420  *	format.  Returns NULL if the path won't fit.
421  */
422 static __printflike(3,4) const char *
make_path(char * buf,size_t bufsize,const char * fmt,...)423 make_path(char *buf, size_t bufsize, const char *fmt, ...)
424 {
425 	va_list ap;
426 	int ret;
427 
428 	va_start(ap, fmt);
429 	ret = vsnprintf(buf, bufsize, fmt, ap);
430 	va_end(ap);
431 
432 	if (ret < 0 || (size_t)ret >= bufsize)
433 		return NULL;
434 
435 	return buf;
436 }
437 
438 #ifndef EVBOARDS_PLIST_BASE
439 #define	EVBOARDS_PLIST_BASE	"/usr"
440 #endif
441 
442 static const char evb_db_base_location[] =
443     EVBOARDS_PLIST_BASE "/share/installboot";
444 
445 /*
446  * evb_db_base_path --
447  *	Returns the path to the base board db file.
448  */
449 static const char *
evb_db_base_path(ib_params * params,char * buf,size_t bufsize)450 evb_db_base_path(ib_params *params, char *buf, size_t bufsize)
451 {
452 
453 	return make_path(buf, bufsize, "%s/%s/boards.plist",
454 	    evb_db_base_location, params->machine->name);
455 }
456 
457 /*
458  * evb_uboot_pkg_paths --
459  *	Returns an array of u-boot package paths to scan for
460  *	installboot.plist files.
461  *
462  *	Number of array elements, not including the NULL terminator,
463  *	is returned in *countp.
464  *
465  *	The working buffer is returned in *bufp so that the caller
466  *	can free it.
467  */
468 static char **
evb_uboot_pkg_paths(ib_params * params,int * countp,void ** bufp)469 evb_uboot_pkg_paths(ib_params *params, int *countp, void **bufp)
470 {
471 	char **ret_array = NULL;
472 	char *buf = NULL;
473 	const char *pathspec;
474 	int i, count;
475 	char *cp, *startcp;
476 
477 	pathspec = params->uboot_paths;
478 	assert(pathspec != NULL);
479 
480 	if (strlen(pathspec) == 0)
481 		goto out;
482 
483 	/* Count the path elements. */
484 	for (cp = __UNCONST(pathspec), count = 0;;) {
485 		count++;
486 		cp = strchr(cp, ':');
487 		if (cp == NULL)
488 			break;
489 		cp++;
490 	}
491 
492 	buf = malloc((sizeof(char *) * (count + 1)) +
493 		     strlen(pathspec) + 1);
494 	if (buf == NULL)
495 		goto out;
496 
497 	/*
498 	 * Because we want to follow the usual "paths are listed in priority
499 	 * order" semantics, we reverse the order of the paths when we put
500 	 * them into the array we feed to fts.  This is because we always
501 	 * overwrite existing entries as we find them, thus the last board
502 	 * object found one a given key is the one that will be used.
503 	 */
504 
505 	ret_array = (char **)buf;
506 	startcp = buf + (sizeof(char *) * (count + 1));
507 	/* this is a safe strcpy(); don't replace it. */
508 	strcpy(startcp, pathspec);
509 
510 	cp = strrchr(startcp, ':');
511 	if (cp == NULL)
512 		cp = startcp;
513 
514 	for (i = 0;;) {
515 		if (*cp == ':') {
516 			ret_array[i++] = cp+1;
517 			*cp-- = '\0';
518 		} else
519 			ret_array[i++] = cp;
520 		if (cp == startcp)
521 			break;
522 		cp = strrchr(cp, ':');
523 		if (cp == NULL)
524 			cp = startcp;
525 	}
526 	assert(i == count);
527 	ret_array[i] = NULL;
528 
529  out:
530 	if (ret_array == NULL) {
531 		if (buf != NULL)
532 			free(buf);
533 	} else {
534 		if (countp != NULL)
535 			*countp = count;
536 		if (bufp != NULL)
537 			*bufp = buf;
538 	}
539 	return ret_array;
540 }
541 
542 static const char step_file_name_key[] = "file-name";
543 static const char step_file_offset_key[] = "file-offset";
544 static const char step_file_size_key[] = "file-size";
545 static const char step_image_offset_key[] = "image-offset";
546 static const char step_input_block_size_key[] = "input-block-size";
547 static const char step_input_pad_size_key[] = "input-pad-size";
548 static const char step_output_size_key[] = "output-size";
549 static const char step_output_block_size_key[] = "output-block-size";
550 static const char step_preserve_key[] = "preserve";
551 
552 static bool
validate_ubstep_object(evb_ubstep obj)553 validate_ubstep_object(evb_ubstep obj)
554 {
555 	/*
556 	 * evb_ubstep is a dictionary with the following keys:
557 	 *
558 	 *	"file-name"         (string) (required)
559 	 *	"file-offset"       (number) (optional)
560 	 *	"file-size"         (number) (optional)
561 	 *	"image-offset"      (number) (optional)
562 	 *	"input-block-size"  (number) (optional)
563 	 *	"input-pad-size"    (number) (optional)
564 	 *	"output-size"       (number) (optional)
565 	 *	"output-block-size" (number) (optional)
566 	 *	"preserve"          (bool)   (optional)
567 	 */
568 	if (prop_object_type(obj) != PROP_TYPE_DICTIONARY)
569 		return false;
570 
571 	prop_object_t v;
572 
573 	v = prop_dictionary_get(obj, step_file_name_key);
574 	if (v == NULL ||
575 	    prop_object_type(v) != PROP_TYPE_STRING)
576 	    	return false;
577 
578 	v = prop_dictionary_get(obj, step_file_offset_key);
579 	if (v != NULL &&
580 	    prop_object_type(v) != PROP_TYPE_NUMBER)
581 	    	return false;
582 
583 	v = prop_dictionary_get(obj, step_file_size_key);
584 	if (v != NULL &&
585 	    prop_object_type(v) != PROP_TYPE_NUMBER)
586 	    	return false;
587 
588 	v = prop_dictionary_get(obj, step_image_offset_key);
589 	if (v != NULL &&
590 	    prop_object_type(v) != PROP_TYPE_NUMBER)
591 	    	return false;
592 
593 	bool have_input_block_size = false;
594 	bool have_input_pad_size = false;
595 
596 	v = prop_dictionary_get(obj, step_input_block_size_key);
597 	if (v != NULL) {
598 		have_input_block_size = true;
599 		if (prop_object_type(v) != PROP_TYPE_NUMBER)
600 			return false;
601 	}
602 
603 	v = prop_dictionary_get(obj, step_input_pad_size_key);
604 	if (v != NULL) {
605 		have_input_pad_size = true;
606 		if (prop_object_type(v) != PROP_TYPE_NUMBER)
607 			return false;
608 	}
609 
610 	/* Must have both or neither of input-{block,pad}-size. */
611 	if (have_input_block_size ^ have_input_pad_size)
612 		return false;
613 
614 	v = prop_dictionary_get(obj, step_output_size_key);
615 	if (v != NULL &&
616 	    prop_object_type(v) != PROP_TYPE_NUMBER)
617 		return false;
618 
619 	v = prop_dictionary_get(obj, step_output_block_size_key);
620 	if (v != NULL &&
621 	    prop_object_type(v) != PROP_TYPE_NUMBER)
622 		return false;
623 
624 	v = prop_dictionary_get(obj, step_preserve_key);
625 	if (v != NULL &&
626 	    prop_object_type(v) != PROP_TYPE_BOOL)
627 	    	return false;
628 
629 	return true;
630 }
631 
632 static bool
validate_ubinstall_object(evb_board board,evb_ubinstall obj)633 validate_ubinstall_object(evb_board board, evb_ubinstall obj)
634 {
635 	/*
636 	 * evb_ubinstall is either:
637 	 * -- an array with one or more evb_ubstep objects.
638 	 * -- a string representing an alias of another evb_ubinstall
639 	 *    object
640 	 *
641 	 * (evb_ubsteps is just a convenience type for iterating
642 	 * over the steps.)
643 	 */
644 
645 	if (prop_object_type(obj) == PROP_TYPE_STRING) {
646 		evb_ubinstall tobj = prop_dictionary_get(board,
647 		    prop_string_value((prop_string_t)obj));
648 
649 		/*
650 		 * The target evb_ubinstall object must exist
651 		 * and must itself be a proper evb_ubinstall,
652 		 * not another alias.
653 		 */
654 		if (tobj == NULL ||
655 		    prop_object_type(tobj) != PROP_TYPE_ARRAY) {
656 			return false;
657 		}
658 		return true;
659 	}
660 
661 	if (prop_object_type(obj) != PROP_TYPE_ARRAY)
662 		return false;
663 	if (prop_array_count(obj) < 1)
664 		return false;
665 
666 	prop_object_t v;
667 	prop_object_iterator_t iter = prop_array_iterator(obj);
668 
669 	while ((v = prop_object_iterator_next(iter)) != NULL) {
670 		if (!validate_ubstep_object(v))
671 			break;
672 	}
673 
674 	prop_object_iterator_release(iter);
675 	return v == NULL;
676 }
677 
678 static const char board_description_key[] = "description";
679 static const char board_u_boot_pkg_key[] = "u-boot-pkg";
680 static const char board_u_boot_path_key[] = "runtime-u-boot-path";
681 static const char board_u_boot_install_key[] = "u-boot-install";
682 
683 static bool
validate_board_object(evb_board obj,bool is_overlay)684 validate_board_object(evb_board obj, bool is_overlay)
685 {
686 	/*
687 	 * evb_board is a dictionary with the following keys:
688 	 *
689 	 *	"description"		(string) (required)
690 	 *	"u-boot-pkg"		(string) (optional, base only)
691 	 *	"runtime-u-boot-path"	(string) (required, overlay only)
692 	 *
693 	 * With special consideration for these keys:
694 	 *
695 	 * Either this key and no other "u-boot-install*" keys:
696 	 *	"u-boot-install"	(string) (required, overlay only)
697 	 *
698 	 * Or one or more keys of the following pattern:
699 	 *	"u-boot-install-*"	(string) (required, overlay only)
700 	 */
701 	bool has_default_install = false;
702 	bool has_media_install = false;
703 
704 	if (prop_object_type(obj) != PROP_TYPE_DICTIONARY)
705 		return false;
706 
707 	prop_object_t v;
708 
709 	v = prop_dictionary_get(obj, board_description_key);
710 	if (v == NULL ||
711 	    prop_object_type(v) != PROP_TYPE_STRING)
712 	    	return false;
713 
714 	v = prop_dictionary_get(obj, board_u_boot_pkg_key);
715 	if (v != NULL &&
716 	    (is_overlay || prop_object_type(v) != PROP_TYPE_STRING))
717 	    	return false;
718 
719 	/*
720 	 * "runtime-u-boot-path" is added to an overlay after we've
721 	 * validated the board object, so simply make sure it's not
722 	 * present.
723 	 */
724 	v = prop_dictionary_get(obj, board_u_boot_path_key);
725 	if (v != NULL)
726 		return false;
727 
728 	prop_object_iterator_t iter = prop_dictionary_iterator(obj);
729 	prop_dictionary_keysym_t key;
730 	while ((key = prop_object_iterator_next(iter)) != NULL) {
731 		const char *cp = prop_dictionary_keysym_value(key);
732 		if (strcmp(cp, board_u_boot_install_key) == 0) {
733 			has_default_install = true;
734 		} else if (strncmp(cp, board_u_boot_install_key,
735 				   sizeof(board_u_boot_install_key) - 1) == 0 &&
736 			   cp[sizeof(board_u_boot_install_key) - 1] == '-') {
737 			has_media_install = true;
738 		} else {
739 			continue;
740 		}
741 		v = prop_dictionary_get_keysym(obj, key);
742 		assert(v != NULL);
743 		if (!is_overlay || !validate_ubinstall_object(obj, v))
744 			break;
745 	}
746 	prop_object_iterator_release(iter);
747 	if (key != NULL)
748 		return false;
749 
750 	/*
751 	 * Overlays must have only a default install key OR one or more
752 	 * media install keys.
753 	 */
754 	if (is_overlay)
755 		return has_default_install ^ has_media_install;
756 
757 	/*
758 	 * Base board objects must have neither.
759 	 */
760 	return (has_default_install | has_media_install) == false;
761 }
762 
763 /*
764  * evb_db_load_overlay --
765  *	Load boards from an overlay file into the db.
766  */
767 static void
evb_db_load_overlay(ib_params * params,const char * path,const char * runtime_uboot_path)768 evb_db_load_overlay(ib_params *params, const char *path,
769     const char *runtime_uboot_path)
770 {
771 	prop_dictionary_t overlay;
772 	struct stat sb;
773 
774 	if (params->flags & IB_VERBOSE)
775 		printf("Loading '%s'.\n", path);
776 
777 	if (stat(path, &sb) < 0) {
778 		warn("'%s'", path);
779 		return;
780 	} else {
781 		overlay = prop_dictionary_internalize_from_file(path);
782 		if (overlay == NULL) {
783 			warnx("unable to parse overlay '%s'", path);
784 			return;
785 		}
786 	}
787 
788 	/*
789 	 * Validate all of the board objects and add them to the board
790 	 * db, replacing any existing entries as we go.
791 	 */
792 	prop_object_iterator_t iter = prop_dictionary_iterator(overlay);
793 	prop_dictionary_keysym_t key;
794 	prop_dictionary_t board;
795 	while ((key = prop_object_iterator_next(iter)) != NULL) {
796 		board = prop_dictionary_get_keysym(overlay, key);
797 		assert(board != NULL);
798 		if (!validate_board_object(board, true)) {
799 			warnx("invalid board object in '%s': '%s'", path,
800 			    prop_dictionary_keysym_value(key));
801 			continue;
802 		}
803 
804 		/* Add "runtime-u-boot-path". */
805 		prop_string_t string =
806 		    prop_string_create_copy(runtime_uboot_path);
807 		assert(string != NULL);
808 		prop_dictionary_set(board, board_u_boot_path_key, string);
809 		prop_object_release(string);
810 
811 		/* Insert into board db. */
812 		prop_dictionary_set_keysym(params->mach_data, key, board);
813 	}
814 	prop_object_iterator_release(iter);
815 	prop_object_release(overlay);
816 }
817 
818 /*
819  * evb_db_load_overlays --
820  *	Load the overlays from the search path.
821  */
822 static void
evb_db_load_overlays(ib_params * params)823 evb_db_load_overlays(ib_params *params)
824 {
825 	char overlay_pathbuf[PATH_MAX+1];
826 	const char *overlay_path;
827 	char **paths;
828 	void *pathsbuf = NULL;
829 	FTS *fts;
830 	FTSENT *chp, *p;
831 	struct stat sb;
832 
833 	paths = evb_uboot_pkg_paths(params, NULL, &pathsbuf);
834 	if (paths == NULL) {
835 		warnx("No u-boot search path?");
836 		return;
837 	}
838 
839 	fts = fts_open(paths, FTS_COMFOLLOW | FTS_LOGICAL | FTS_NOCHDIR, NULL);
840 	if (fts == NULL ||
841 	    (chp = fts_children(fts, 0)) == NULL) {
842 		warn("Unable to search u-boot path");
843 		if (fts != NULL)
844 			fts_close(fts);
845 		return;
846 	}
847 
848 	chp = fts_children(fts, 0);
849 
850 	while ((p = fts_read(fts)) != NULL) {
851 		if (p->fts_info != FTS_D)
852 			continue;
853 		overlay_path = make_path(overlay_pathbuf,
854 		    sizeof(overlay_pathbuf), "%s/installboot.plist",
855 		    p->fts_path);
856 		if (overlay_path == NULL)
857 			continue;
858 		if (stat(overlay_path, &sb) < 0)
859 			continue;
860 		evb_db_load_overlay(params, overlay_path, p->fts_path);
861 	}
862 
863 	fts_close(fts);
864 
865 	/*
866 	 * If the user specified a stage1 loader, then consult it last
867 	 * for a possible u-boot package location.
868 	 */
869 	if (params->stage1 != NULL) {
870 		overlay_path = make_path(overlay_pathbuf,
871 		    sizeof(overlay_pathbuf), "%s/installboot.plist",
872 		    params->stage1);
873 		if (overlay_path != NULL) {
874 			if (stat(overlay_path, &sb) == 0) {
875 				evb_db_load_overlay(params, overlay_path,
876 				    params->stage1);
877 			}
878 		}
879 	}
880 }
881 
882 /*
883  * evb_db_load_base --
884  *	Load the base board db.
885  */
886 static bool
evb_db_load_base(ib_params * params)887 evb_db_load_base(ib_params *params)
888 {
889 	char buf[PATH_MAX+1];
890 	const char *path;
891 	prop_dictionary_t board_db;
892 	struct stat sb;
893 
894 	path = evb_db_base_path(params, buf, sizeof(buf));
895 	if (path == NULL)
896 		return false;
897 
898 	if (params->flags & IB_VERBOSE)
899 		printf("Loading '%s'.\n", path);
900 
901 	if (stat(path, &sb) < 0) {
902 		if (errno != ENOENT) {
903 			warn("'%s'", path);
904 			return false;
905 		}
906 		board_db = prop_dictionary_create();
907 		assert(board_db != NULL);
908 	} else {
909 		board_db = prop_dictionary_internalize_from_file(path);
910 		if (board_db == NULL) {
911 			warnx("unable to parse board db '%s'", path);
912 			return false;
913 		}
914 	}
915 
916 	if (prop_dictionary_count(board_db) == 0) {
917 		/*
918 		 * Oh well, maybe we'll load some overlays.
919 		 */
920 		goto done;
921 	}
922 
923 	/*
924 	 * Validate all of the board objects and remove any bad ones.
925 	 */
926 	prop_array_t all_board_keys = prop_dictionary_all_keys(board_db);
927 	prop_object_iterator_t iter = prop_array_iterator(all_board_keys);
928 	prop_dictionary_keysym_t key;
929 	prop_dictionary_t board;
930 	while ((key = prop_object_iterator_next(iter)) != NULL) {
931 		board = prop_dictionary_get_keysym(board_db, key);
932 		assert(board != NULL);
933 		if (!validate_board_object(board, false)) {
934 			warnx("invalid board object in '%s': '%s'", path,
935 			    prop_dictionary_keysym_value(key));
936 			prop_dictionary_remove_keysym(board_db, key);
937 		}
938 	}
939 	prop_object_iterator_release(iter);
940 	prop_object_release(all_board_keys);
941 
942  done:
943 	params->mach_data = board_db;
944 	return true;
945 }
946 
947 /*
948  * evb_db_load --
949  *	Load the board database.
950  */
951 bool
evb_db_load(ib_params * params)952 evb_db_load(ib_params *params)
953 {
954 	if (!evb_db_load_base(params))
955 		return false;
956 	evb_db_load_overlays(params);
957 
958 	return true;
959 }
960 
961 #if !HAVE_NBTOOL_CONFIG_H
962 /*
963  * Native board name guessing methods.
964  */
965 
966 #ifdef SUPPORT_OPENFIRMWARE
967 static int
ofw_fd(void)968 ofw_fd(void)
969 {
970 	static const char openfirm_path[] = "/dev/openfirm";
971 
972 	return open(openfirm_path, O_RDONLY);
973 }
974 
975 static int
OF_finddevice(const char * name)976 OF_finddevice(const char *name)
977 {
978 	struct ofiocdesc ofio = {
979 		.of_name = __UNCONST(name),
980 		.of_namelen = strlen(name),
981 	};
982 	int fd = ofw_fd();
983 
984 	if (fd == -1)
985 		return -1;
986 
987 	if (ioctl(fd, OFIOCFINDDEVICE, &ofio) < 0) {
988 		if (errno != ENOENT)
989 			warn("OFIOCFINDDEVICE('%s')", name);
990 		ofio.of_nodeid = -1;
991 	}
992 	(void) close(fd);
993 
994 	return ofio.of_nodeid;
995 }
996 
997 static int
OF_getprop(int phandle,const char * prop,void * buf,size_t buflen)998 OF_getprop(int phandle, const char *prop, void *buf, size_t buflen)
999 {
1000 	struct ofiocdesc ofio = {
1001 		.of_nodeid = phandle,
1002 		.of_name = __UNCONST(prop),
1003 		.of_namelen = strlen(prop),
1004 		.of_buf = buf,
1005 		.of_buflen = buflen,
1006 	};
1007 	int fd = ofw_fd();
1008 
1009 	if (fd == -1)
1010 		return -1;
1011 
1012 	int save_errno = 0;
1013 
1014 	if (ioctl(fd, OFIOCGET, &ofio) < 0) {
1015 		save_errno = errno;
1016 		if (errno != ENOMEM && errno != ENOENT) {
1017 			save_errno = errno;
1018 			warn("OFIOCGET('%s')", prop);
1019 		}
1020 		ofio.of_buflen = -1;
1021 	}
1022 	(void) close(fd);
1023 	errno = save_errno;
1024 
1025 	return ofio.of_buflen;
1026 }
1027 
1028 static void *
ofw_getprop(int phandle,const char * prop,int * lenp)1029 ofw_getprop(int phandle, const char *prop, int *lenp)
1030 {
1031 	size_t buflen = 32;
1032 	void *buf = NULL;
1033 	int len;
1034 
1035 	for (;;) {
1036 		void *newbuf = realloc(buf, buflen);
1037 		if (newbuf == NULL) {
1038 			free(buf);
1039 			return NULL;
1040 		}
1041 		buf = newbuf;
1042 		switch (len = OF_getprop(phandle, prop, buf, buflen)) {
1043 		case -1:
1044 			if (errno != ENOMEM) {
1045 				free(buf);
1046 				return NULL;
1047 			}
1048 			buflen *= 2;
1049 			break;
1050 
1051 		default:
1052 			if (lenp)
1053 				*lenp = len;
1054 			return buf;
1055 		}
1056 	}
1057 }
1058 
1059 static evb_board
evb_db_get_board_from_ofw(ib_params * params,const char ** board_namep)1060 evb_db_get_board_from_ofw(ib_params *params, const char **board_namep)
1061 {
1062 	int phandle;
1063 	int compatible_len = 0;
1064 	char *compatible_buf;
1065 	const char *sp, *nsp;
1066 	evb_board board;
1067 
1068 	phandle = OF_finddevice("/");
1069 	if (phandle == -1) {
1070 		/* No OpenFirmware available. */
1071 		return NULL;
1072 	}
1073 
1074 	compatible_buf = ofw_getprop(phandle, "compatible", &compatible_len);
1075 
1076 	/*
1077 	 * We just leak compatible_buf on success.  Not a big deal since
1078 	 * we are not a long-running process.
1079 	 */
1080 
1081 	sp = compatible_buf;
1082 	while (compatible_len &&
1083 	       (nsp = memchr(sp, 0, compatible_len)) != NULL) {
1084 		if (params->flags & IB_VERBOSE)
1085 			printf("Checking OFW compatible string '%s'.\n", sp);
1086 		board = prop_dictionary_get(params->mach_data, sp);
1087 		if (board != NULL) {
1088 			if (board_namep)
1089 				*board_namep = sp;
1090 			return board;
1091 		}
1092 		nsp++;	/* skip over NUL */
1093 		compatible_len -= (nsp - sp);
1094 		sp = nsp;
1095 	}
1096 
1097 	free(compatible_buf);
1098 	return NULL;
1099 }
1100 #endif /* SUPPORT_OPENFIRMWARE */
1101 
1102 #endif /* ! HAVE_NBTOOL_CONFIG_H */
1103 
1104 /*
1105  * Host-tool and native board name guessing methods.
1106  */
1107 
1108 #ifdef SUPPORT_FDT
1109 static void *
load_dtb(ib_params * params)1110 load_dtb(ib_params *params)
1111 {
1112 	struct stat sb;
1113 	void *buf;
1114 	int fd;
1115 
1116 	if (stat(params->dtb, &sb) < 0) {
1117 		warn("%s", params->dtb);
1118 		return NULL;
1119 	}
1120 
1121 	buf = malloc((size_t)sb.st_size);
1122 	assert(buf != NULL);
1123 
1124 	if ((fd = open(params->dtb, O_RDONLY)) < 0) {
1125 		warn("%s", params->dtb);
1126 		free(buf);
1127 		return NULL;
1128 	}
1129 
1130 	if (read(fd, buf, (size_t)sb.st_size) != (ssize_t)sb.st_size) {
1131 		warn("read '%s'", params->dtb);
1132 		free(buf);
1133 		buf = NULL;
1134 	}
1135 	(void) close(fd);
1136 
1137 	return buf;
1138 }
1139 
1140 static evb_board
evb_db_get_board_from_dtb(ib_params * params,const char ** board_namep)1141 evb_db_get_board_from_dtb(ib_params *params, const char **board_namep)
1142 {
1143 	evb_board board = NULL;
1144 	void *fdt = NULL;
1145 	int error;
1146 
1147 	fdt = load_dtb(params);
1148 	if (fdt == NULL)
1149 		return NULL;
1150 
1151 	error = fdt_check_header(fdt);
1152 	if (error) {
1153 		warnx("%s: %s", params->dtb, fdt_strerror(error));
1154 		goto bad;
1155 	}
1156 
1157 	const int system_root = fdt_path_offset(fdt, "/");
1158 	if (system_root < 0) {
1159 		warnx("%s: unable to find node '/'", params->dtb);
1160 		goto bad;
1161 	}
1162 
1163 	const int system_ncompat = fdt_stringlist_count(fdt, system_root,
1164 	    "compatible");
1165 	if (system_ncompat <= 0) {
1166 		warnx("%s: no 'compatible' property on node '/'", params->dtb);
1167 		goto bad;
1168 	}
1169 
1170 	const char *compatible;
1171 	int si;
1172 	for (si = 0; si < system_ncompat; si++) {
1173 		compatible = fdt_stringlist_get(fdt, system_root,
1174 		    "compatible", si, NULL);
1175 		if (compatible == NULL)
1176 			continue;
1177 		if (params->flags & IB_VERBOSE)
1178 			printf("Checking FDT compatible string '%s'.\n",
1179 			    compatible);
1180 		board = prop_dictionary_get(params->mach_data, compatible);
1181 		if (board != NULL) {
1182 			/*
1183 			 * We just leak compatible on success.  Not a big
1184 			 * deal since we are not a long-running process.
1185 			 */
1186 			if (board_namep) {
1187 				*board_namep = strdup(compatible);
1188 				assert(*board_namep != NULL);
1189 			}
1190 			free(fdt);
1191 			return board;
1192 		}
1193 	}
1194 
1195  bad:
1196 	if (fdt != NULL)
1197 		free(fdt);
1198 	return NULL;
1199 }
1200 #endif /* SUPPORT_FDT */
1201 
1202 /*
1203  * evb_db_get_board --
1204  *	Return the specified board object from the database.
1205  */
1206 evb_board
evb_db_get_board(ib_params * params)1207 evb_db_get_board(ib_params *params)
1208 {
1209 	const char *board_name = NULL;
1210 	evb_board board = NULL;
1211 
1212 #if !HAVE_NBTOOL_CONFIG_H
1213 	/*
1214 	 * If we're not a host tool, determine if we're running "natively".
1215 	 */
1216 	bool is_native = false;
1217 	struct utsname utsname;
1218 
1219 	if (uname(&utsname) < 0) {
1220 		warn("uname");
1221 	} else if (strcmp(utsname.machine, params->machine->name) == 0) {
1222 		is_native = true;
1223 	}
1224 #endif /* ! HAVE_NBTOOL_CONFIG_H */
1225 
1226 	/*
1227 	 * Logic for determing board type that can be shared by host-tool
1228 	 * and native builds goes here.
1229 	 */
1230 
1231 	/*
1232 	 * Command-line argument trumps all.
1233 	 */
1234 	if (params->flags & IB_BOARD) {
1235 		board_name = params->board;
1236 	}
1237 
1238 #ifdef SUPPORT_FDT
1239 	if (board_name == NULL && (params->flags & IB_DTB)) {
1240 		board = evb_db_get_board_from_dtb(params, &board_name);
1241 		if ((params->flags & IB_VERBOSE) && board != NULL)
1242 			printf("Found board '%s' from DTB data.\n", board_name);
1243 #if !HAVE_NBTOOL_CONFIG_H
1244 		/*
1245 		 * If the user specified a DTB, then regardless of the
1246 		 * outcome, this is like specifying the board directly,
1247 		 * so native checks should be skipped.
1248 		 */
1249 		is_native = false;
1250 #endif /* ! HAVE_NBTOOL_CONFIG_H */
1251 	}
1252 #endif /* SUPPORT_FDT */
1253 
1254 #if !HAVE_NBTOOL_CONFIG_H
1255 	/*
1256 	 * Non-host-tool logic for determining the board type goes here.
1257 	 */
1258 
1259 #ifdef SUPPORT_OPENFIRMWARE
1260 	if (board_name == NULL && is_native) {
1261 		board = evb_db_get_board_from_ofw(params, &board_name);
1262 		if ((params->flags & IB_VERBOSE) && board != NULL)
1263 			printf("Found board '%s' from OFW data.\n", board_name);
1264 	}
1265 #endif /* SUPPORT_OPENFIRMWARE */
1266 
1267 	/* Ensure is_native is consumed. */
1268 	if (is_native == false)
1269 		is_native = false;
1270 
1271 #endif /* ! HAVE_NBTOOL_CONFIG_H */
1272 
1273 	/*
1274 	 * If all else fails, we can always rely on the user, right?
1275 	 */
1276 	if (board_name == NULL) {
1277 		if (!(params->flags & IB_BOARD)) {
1278 			warnx("Must specify board=...");
1279 			return NULL;
1280 		}
1281 		board_name = params->board;
1282 	}
1283 
1284 	assert(board_name != NULL);
1285 
1286 	if (board == NULL)
1287 		board = prop_dictionary_get(params->mach_data, board_name);
1288 	if (board == NULL)
1289 		warnx("Unknown board '%s'", board_name);
1290 
1291 	/* Ensure params->board is always valid. */
1292 	params->board = board_name;
1293 
1294 	if (params->flags & IB_VERBOSE) {
1295 		printf("Board: %s\n", evb_board_get_description(params, board));
1296 	}
1297 
1298 	return board;
1299 }
1300 
1301 /*
1302  * evb_db_list_boards --
1303  *	Print the list of known boards to the specified output stream.
1304  */
1305 void
evb_db_list_boards(ib_params * params,FILE * out)1306 evb_db_list_boards(ib_params *params, FILE *out)
1307 {
1308 	prop_object_iterator_t iter;
1309 	prop_dictionary_keysym_t key;
1310 	evb_board board;
1311 	const char *uboot_pkg;
1312 	const char *uboot_path;
1313 
1314 	/*
1315 	 * By default, we only list boards that we have a u-boot
1316 	 * package installed for, or if we know which package you
1317 	 * need to install.  You get the full monty in verbose mode.
1318 	 */
1319 
1320 	iter = prop_dictionary_iterator(params->mach_data);
1321 	while ((key = prop_object_iterator_next(iter)) != NULL) {
1322 		board = prop_dictionary_get_keysym(params->mach_data, key);
1323 		assert(board != NULL);
1324 		uboot_pkg = evb_board_get_uboot_pkg(params, board);
1325 		uboot_path = evb_board_get_uboot_path(params, board);
1326 
1327 		if (uboot_pkg == NULL && uboot_path == NULL &&
1328 		    !(params->flags & IB_VERBOSE))
1329 			continue;
1330 
1331 		fprintf(out, "%-30s %s\n",
1332 		    prop_dictionary_keysym_value(key),
1333 		    evb_board_get_description(params, board));
1334 
1335 		if ((params->flags & IB_VERBOSE) && uboot_path) {
1336 			fprintf(out, "\t(u-boot package found at %s)\n",
1337 			    uboot_path);
1338 		} else if ((params->flags & IB_VERBOSE) && uboot_pkg) {
1339 			fprintf(out,
1340 			    "\t(install the sysutils/u-boot-%s package)\n",
1341 			    uboot_pkg);
1342 		}
1343 	}
1344 	prop_object_iterator_release(iter);
1345 }
1346 
1347 /*
1348  * evb_board_get_description --
1349  *	Return the description for the specified board.
1350  */
1351 const char *
evb_board_get_description(ib_params * params,evb_board board)1352 evb_board_get_description(ib_params *params, evb_board board)
1353 {
1354 	prop_string_t string;
1355 
1356 	string = prop_dictionary_get(board, board_description_key);
1357 	return prop_string_value(string);
1358 }
1359 
1360 /*
1361  * evb_board_get_uboot_pkg --
1362  *	Return the u-boot package name for the specified board.
1363  */
1364 const char *
evb_board_get_uboot_pkg(ib_params * params,evb_board board)1365 evb_board_get_uboot_pkg(ib_params *params, evb_board board)
1366 {
1367 	prop_string_t string;
1368 
1369 	string = prop_dictionary_get(board, board_u_boot_pkg_key);
1370 	if (string == NULL)
1371 		return NULL;
1372 	return prop_string_value(string);
1373 }
1374 
1375 /*
1376  * evb_board_get_uboot_path --
1377  *	Return the u-boot installed package path for the specified board.
1378  */
1379 const char *
evb_board_get_uboot_path(ib_params * params,evb_board board)1380 evb_board_get_uboot_path(ib_params *params, evb_board board)
1381 {
1382 	prop_string_t string;
1383 
1384 	string = prop_dictionary_get(board, board_u_boot_path_key);
1385 	if (string == NULL)
1386 		return NULL;
1387 	return prop_string_value(string);
1388 }
1389 
1390 /*
1391  * evb_board_get_uboot_install --
1392  *	Return the u-boot install object for the specified board,
1393  *	corresponding to the media specified by the user.
1394  */
1395 evb_ubinstall
evb_board_get_uboot_install(ib_params * params,evb_board board)1396 evb_board_get_uboot_install(ib_params *params, evb_board board)
1397 {
1398 	evb_ubinstall install;
1399 
1400 	install = prop_dictionary_get(board, board_u_boot_install_key);
1401 
1402 	if (!(params->flags & IB_MEDIA)) {
1403 		if (install == NULL) {
1404 			warnx("Must specify media=... for board '%s'",
1405 			    params->board);
1406 			goto list_media;
1407 		}
1408 		return install;
1409 	}
1410 
1411 	/* media=... was specified by the user. */
1412 
1413 	if (install) {
1414 		warnx("media=... is not a valid option for board '%s'",
1415 		    params->board);
1416 		return NULL;
1417 	}
1418 
1419 	char install_key[128];
1420 	int n = snprintf(install_key, sizeof(install_key), "%s-%s",
1421 	    board_u_boot_install_key, params->media);
1422 	if (n < 0 || (size_t)n >= sizeof(install_key))
1423 		goto invalid_media;
1424 	install = prop_dictionary_get(board, install_key);
1425 	if (install != NULL) {
1426 		if (prop_object_type(install) == PROP_TYPE_STRING) {
1427 			/*
1428 			 * This is an alias.  Fetch the target.  We
1429 			 * have already validated that the target
1430 			 * exists.
1431 			 */
1432 			install = prop_dictionary_get(board,
1433 			    prop_string_value((prop_string_t)install));
1434 		}
1435 		return install;
1436 	}
1437  invalid_media:
1438 	warnx("invalid media specification: '%s'", params->media);
1439  list_media:
1440 	fprintf(stderr, "Valid media types:");
1441 	prop_array_t array = evb_board_copy_uboot_media(params, board);
1442 	assert(array != NULL);
1443 	prop_object_iterator_t iter = prop_array_iterator(array);
1444 	prop_string_t string;
1445 	while ((string = prop_object_iterator_next(iter)) != NULL)
1446 		fprintf(stderr, " %s", prop_string_value(string));
1447 	fprintf(stderr, "\n");
1448 	prop_object_iterator_release(iter);
1449 	prop_object_release(array);
1450 
1451 	return NULL;
1452 }
1453 
1454 /*
1455  * evb_board_copy_uboot_media --
1456  *	Return the valid media types for the given board as an array
1457  *	of strings.
1458  *
1459  *	Follows the create rule; caller is responsible for releasing
1460  *	the array.
1461  */
1462 prop_array_t
evb_board_copy_uboot_media(ib_params * params,evb_board board)1463 evb_board_copy_uboot_media(ib_params *params, evb_board board)
1464 {
1465 	prop_array_t array = prop_array_create();
1466 	prop_object_iterator_t iter = prop_dictionary_iterator(board);
1467 	prop_string_t string;
1468 	prop_dictionary_keysym_t key;
1469 	const char *cp;
1470 
1471 	assert(array != NULL);
1472 	assert(iter != NULL);
1473 
1474 	while ((key = prop_object_iterator_next(iter)) != NULL) {
1475 		cp = prop_dictionary_keysym_value(key);
1476 		if (strcmp(cp, board_u_boot_install_key) == 0 ||
1477 		    strncmp(cp, board_u_boot_install_key,
1478 			    sizeof(board_u_boot_install_key) - 1) != 0)
1479 			continue;
1480 		string = prop_string_create_copy(strrchr(cp, '-')+1);
1481 		assert(string != NULL);
1482 		prop_array_add(array, string);
1483 		prop_object_release(string);
1484 	}
1485 	prop_object_iterator_release(iter);
1486 	return array;
1487 }
1488 
1489 /*
1490  * evb_ubinstall_get_steps --
1491  *	Get the install steps for a given install object.
1492  */
1493 evb_ubsteps
evb_ubinstall_get_steps(ib_params * params,evb_ubinstall install)1494 evb_ubinstall_get_steps(ib_params *params, evb_ubinstall install)
1495 {
1496 	return prop_array_iterator(install);
1497 }
1498 
1499 /*
1500  * evb_ubsteps_next_step --
1501  *	Return the next step in the install object.
1502  *
1503  *	N.B. The iterator is released upon termination.
1504  */
1505 evb_ubstep
evb_ubsteps_next_step(ib_params * params,evb_ubsteps steps)1506 evb_ubsteps_next_step(ib_params *params, evb_ubsteps steps)
1507 {
1508 	prop_dictionary_t step = prop_object_iterator_next(steps);
1509 
1510 	/* If we are out of steps, release the iterator. */
1511 	if (step == NULL)
1512 		prop_object_iterator_release(steps);
1513 
1514 	return step;
1515 }
1516 
1517 /*
1518  * evb_ubstep_get_file_name --
1519  *	Returns the input file name for the step.
1520  */
1521 const char *
evb_ubstep_get_file_name(ib_params * params,evb_ubstep step)1522 evb_ubstep_get_file_name(ib_params *params, evb_ubstep step)
1523 {
1524 	prop_string_t string = prop_dictionary_get(step, step_file_name_key);
1525 	return prop_string_value(string);
1526 }
1527 
1528 /*
1529  * evb_ubstep_get_file_offset --
1530  *	Returns the input file offset for the step.
1531  */
1532 uint64_t
evb_ubstep_get_file_offset(ib_params * params,evb_ubstep step)1533 evb_ubstep_get_file_offset(ib_params *params, evb_ubstep step)
1534 {
1535 	prop_number_t number = prop_dictionary_get(step, step_file_offset_key);
1536 	if (number != NULL)
1537 		return prop_number_unsigned_value(number);
1538 	return 0;
1539 }
1540 
1541 /*
1542  * evb_ubstep_get_file_size --
1543  *	Returns the size of the input file to copy for this step, or
1544  *	zero if the remainder of the file should be copied.
1545  */
1546 uint64_t
evb_ubstep_get_file_size(ib_params * params,evb_ubstep step)1547 evb_ubstep_get_file_size(ib_params *params, evb_ubstep step)
1548 {
1549 	prop_number_t number = prop_dictionary_get(step, step_file_size_key);
1550 	if (number != NULL)
1551 		return prop_number_unsigned_value(number);
1552 	return 0;
1553 }
1554 
1555 /*
1556  * evb_ubstep_get_image_offset --
1557  *	Returns the offset into the destination image / device to
1558  *	copy the input file.
1559  */
1560 uint64_t
evb_ubstep_get_image_offset(ib_params * params,evb_ubstep step)1561 evb_ubstep_get_image_offset(ib_params *params, evb_ubstep step)
1562 {
1563 	prop_number_t number = prop_dictionary_get(step, step_image_offset_key);
1564 	if (number != NULL)
1565 		return prop_number_unsigned_value(number);
1566 	return 0;
1567 }
1568 
1569 /*
1570  * evb_ubstep_get_input_block_size --
1571  *	Returns the input block size to use when reading the boot loader
1572  *	file.
1573  */
1574 uint64_t
evb_ubstep_get_input_block_size(ib_params * params,evb_ubstep step)1575 evb_ubstep_get_input_block_size(ib_params *params, evb_ubstep step)
1576 {
1577 	prop_number_t number = prop_dictionary_get(step,
1578 						   step_input_block_size_key);
1579 	if (number != NULL)
1580 		return prop_number_unsigned_value(number);
1581 	return 0;
1582 }
1583 
1584 /*
1585  * evb_ubstep_get_input_pad_size --
1586  *	Returns the input pad size to use when reading the boot loader
1587  *	file.
1588  */
1589 uint64_t
evb_ubstep_get_input_pad_size(ib_params * params,evb_ubstep step)1590 evb_ubstep_get_input_pad_size(ib_params *params, evb_ubstep step)
1591 {
1592 	prop_number_t number = prop_dictionary_get(step,
1593 						   step_input_pad_size_key);
1594 	if (number != NULL)
1595 		return prop_number_unsigned_value(number);
1596 	return 0;
1597 }
1598 
1599 /*
1600  * evb_ubstep_get_output_size --
1601  *	Returns the total output size that will be written to the
1602  *	output device.
1603  */
1604 uint64_t
evb_ubstep_get_output_size(ib_params * params,evb_ubstep step)1605 evb_ubstep_get_output_size(ib_params *params, evb_ubstep step)
1606 {
1607 	prop_number_t number = prop_dictionary_get(step, step_output_size_key);
1608 	if (number != NULL)
1609 		return prop_number_unsigned_value(number);
1610 	return 0;
1611 }
1612 
1613 /*
1614  * evb_ubstep_get_output_block_size --
1615  *	Returns the block size that must be written to the output device.
1616  */
1617 uint64_t
evb_ubstep_get_output_block_size(ib_params * params,evb_ubstep step)1618 evb_ubstep_get_output_block_size(ib_params *params, evb_ubstep step)
1619 {
1620 	prop_number_t number = prop_dictionary_get(step,
1621 						   step_output_block_size_key);
1622 	if (number != NULL)
1623 		return prop_number_unsigned_value(number);
1624 	return 0;
1625 }
1626 
1627 /*
1628  * evb_ubstep_preserves_partial_block --
1629  *	Returns true if the step preserves a partial block.
1630  */
1631 bool
evb_ubstep_preserves_partial_block(ib_params * params,evb_ubstep step)1632 evb_ubstep_preserves_partial_block(ib_params *params, evb_ubstep step)
1633 {
1634 	prop_bool_t val = prop_dictionary_get(step, step_preserve_key);
1635 	if (val != NULL)
1636 		return prop_bool_true(val);
1637 	return false;
1638 }
1639 
1640 /*
1641  * evb_uboot_file_path --
1642  *	Build a file path from the u-boot base path in the board object
1643  *	and the file name in the step object.
1644  */
1645 static const char *
evb_uboot_file_path(ib_params * params,evb_board board,evb_ubstep step,char * buf,size_t bufsize)1646 evb_uboot_file_path(ib_params *params, evb_board board, evb_ubstep step,
1647     char *buf, size_t bufsize)
1648 {
1649 	const char *base_path = evb_board_get_uboot_path(params, board);
1650 	const char *file_name = evb_ubstep_get_file_name(params, step);
1651 
1652 	if (base_path == NULL || file_name == NULL)
1653 		return NULL;
1654 
1655 	return make_path(buf, bufsize, "%s/%s", base_path, file_name);
1656 }
1657 
1658 /*
1659  * evb_uboot_do_step --
1660  *	Given a evb_ubstep, do the deed.
1661  */
1662 static int
evb_uboot_do_step(ib_params * params,const char * uboot_file,evb_ubstep step)1663 evb_uboot_do_step(ib_params *params, const char *uboot_file, evb_ubstep step)
1664 {
1665 	struct stat sb;
1666 	int ifd = -1;
1667 	char *blockbuf = NULL;
1668 	off_t curoffset;
1669 	off_t file_remaining;
1670 	bool rv = false;
1671 
1672 	uint64_t file_size = evb_ubstep_get_file_size(params, step);
1673 	uint64_t file_offset = evb_ubstep_get_file_offset(params, step);
1674 	uint64_t image_offset = evb_ubstep_get_image_offset(params, step);
1675 	uint64_t output_size = evb_ubstep_get_output_size(params, step);
1676 	size_t   output_block_size =
1677 			(size_t)evb_ubstep_get_output_block_size(params, step);
1678 	size_t   input_block_size =
1679 			(size_t)evb_ubstep_get_input_block_size(params, step);
1680 	size_t   input_pad_size =
1681 			(size_t)evb_ubstep_get_input_pad_size(params, step);
1682 	bool	 preserves_partial_block =
1683 			evb_ubstep_preserves_partial_block(params, step);
1684 	const char *uboot_file_name =
1685 			evb_ubstep_get_file_name(params, step);
1686 
1687 	if (input_block_size == 0 && output_block_size == 0) {
1688 		if (params->flags & IB_VERBOSE) {
1689 			printf("Defaulting input-block-size and "
1690 			       "output-block-size to sectorsize "
1691 			       "(%" PRIu32 ")\n", params->sectorsize);
1692 		}
1693 		input_block_size = output_block_size = params->sectorsize;
1694 	} else if (input_block_size != 0 && output_block_size == 0) {
1695 		if (params->flags & IB_VERBOSE) {
1696 			printf("Defaulting output-block-size to "
1697 			       "input-block-size (%zu)\n",
1698 			       input_block_size);
1699 		}
1700 		output_block_size = input_block_size;
1701 	} else if (output_block_size != 0 && input_block_size == 0) {
1702 		if (params->flags & IB_VERBOSE) {
1703 			printf("Defaulting input-block-size to "
1704 			       "output-block-size (%zu)\n",
1705 			       output_block_size);
1706 		}
1707 		input_block_size = output_block_size;
1708 	}
1709 
1710 	if (output_block_size % params->sectorsize) {
1711 		warnx("output-block-size (%zu) is not a multiple of "
1712 		      "device sector size (%" PRIu32 ")",
1713 		      output_block_size, params->sectorsize);
1714 		goto out;
1715 	}
1716 
1717 	if ((input_block_size + input_pad_size) > output_block_size) {
1718 		warnx("input-{block+pad}-size (%zu) is larger than "
1719 		      "output-block-size (%zu)",
1720 		      input_block_size + input_pad_size,
1721 		      output_block_size);
1722 		goto out;
1723 	}
1724 
1725 	if (output_block_size % (input_block_size + input_pad_size)) {
1726 		warnx("output-block-size (%zu) it not a multiple of "
1727 		      "input-{block+pad}-size (%zu)",
1728 		      output_block_size,
1729 		      input_block_size + input_pad_size);
1730 		goto out;
1731 	}
1732 
1733 	blockbuf = malloc(output_block_size);
1734 	if (blockbuf == NULL)
1735 		goto out;
1736 
1737 	ifd = open(uboot_file, O_RDONLY);
1738 	if (ifd < 0) {
1739 		warn("open '%s'", uboot_file);
1740 		goto out;
1741 	}
1742 	if (fstat(ifd, &sb) < 0) {
1743 		warn("fstat '%s'", uboot_file);
1744 		goto out;
1745 	}
1746 
1747 	if (file_size)
1748 		file_remaining = (off_t)file_size;
1749 	else
1750 		file_remaining = sb.st_size - (off_t)file_offset;
1751 
1752 	if (output_size == 0) {
1753 		output_size = roundup(file_remaining, output_block_size);
1754 	} else if ((uint64_t)file_remaining > output_size) {
1755 		warnx("file size (%lld) is larger than output-size (%" PRIu64
1756 		      ")", (long long)file_remaining, output_size);
1757 		goto out;
1758 	}
1759 
1760 	if (params->flags & IB_VERBOSE) {
1761 		if (file_offset) {
1762 			printf("Writing '%s' %lld @ %" PRIu64
1763 			       "to '%s' @  %" PRIu64 "\n",
1764 			       uboot_file_name, (long long)file_remaining,
1765 			       file_offset, params->filesystem, image_offset);
1766 		} else {
1767 			printf("Writing '%s' %lld to '%s' @ %" PRIu64 "\n",
1768 			       uboot_file_name, (long long)file_remaining,
1769 			       params->filesystem, image_offset);
1770 		}
1771 	}
1772 
1773 	if (lseek(ifd, (off_t)file_offset, SEEK_SET) < 0) {
1774 		warn("lseek '%s' @ %" PRIu64, uboot_file,
1775 		    file_offset);
1776 		goto out;
1777 	}
1778 
1779 	for (curoffset = (off_t)image_offset;
1780 	     output_size != 0;
1781 	     curoffset += output_block_size, output_size -= output_block_size) {
1782 
1783 		size_t outblock_remaining;
1784 		size_t this_inblock;
1785 		char *fill;
1786 
1787 		/*
1788 		 * Initialize the output buffer.  We're either
1789 		 * filling it with zeros, or we're preserving
1790 		 * device contents that we don't overwrite.
1791 		 */
1792 		memset(blockbuf, 0, output_block_size);
1793 		if (preserves_partial_block) {
1794 			if (params->flags & IB_VERBOSE) {
1795 				printf("(Reading '%s' -- %zu @ %lld)\n",
1796 				       params->filesystem,
1797 				       output_block_size,
1798 				       (long long)curoffset);
1799 			}
1800 			if (pread(params->fsfd, blockbuf,
1801 				  output_block_size, curoffset) < 0) {
1802 				warn("pread '%s'", params->filesystem);
1803 				goto out;
1804 			}
1805 		}
1806 
1807 		/*
1808 		 * Fill the output buffer with the file contents,
1809 		 * interleaved with padding as necessary.  (If
1810 		 * there is no file left, we're going to be left
1811 		 * with padding to cover the output-size.)
1812 		 */
1813 		for (outblock_remaining = output_block_size, fill = blockbuf;
1814 		     outblock_remaining != 0;
1815 		     fill += input_block_size + input_pad_size,
1816 		     outblock_remaining -= input_block_size + input_pad_size) {
1817 
1818 			this_inblock = input_block_size;
1819 			if ((off_t)this_inblock > file_remaining) {
1820 				this_inblock = file_remaining;
1821 			}
1822 
1823 			if (this_inblock) {
1824 				if (params->flags & IB_VERBOSE) {
1825 					printf("(Reading '%s' -- %zu @ %lld)\n",
1826 					       uboot_file_name,
1827 					       this_inblock,
1828 					       (long long)lseek(ifd, 0,
1829 								SEEK_CUR));
1830 				}
1831 				if (read(ifd, fill, this_inblock)
1832 				    != (ssize_t)this_inblock) {
1833 					warn("read '%s'", uboot_file);
1834 					goto out;
1835 				}
1836 				file_remaining -= this_inblock;
1837 			}
1838 		}
1839 
1840 		if (params->flags & IB_VERBOSE) {
1841 			printf("(Writing '%s' -- %zu @ %lld)\n",
1842 			       params->filesystem,
1843 			       output_block_size, (long long)curoffset);
1844 		}
1845 		if (!(params->flags & IB_NOWRITE) &&
1846 		    pwrite(params->fsfd, blockbuf, output_block_size,
1847 			   curoffset) != (ssize_t)output_block_size) {
1848 			warn("pwrite '%s'", params->filesystem);
1849 			goto out;
1850 		}
1851 	}
1852 
1853 	/* Success! */
1854 	rv = true;
1855 
1856  out:
1857 	if (ifd != -1 && close(ifd) == -1)
1858 		warn("close '%s'", uboot_file);
1859 	if (blockbuf)
1860 		free(blockbuf);
1861 	return rv;
1862 }
1863 
1864 int
evb_uboot_setboot(ib_params * params,evb_board board)1865 evb_uboot_setboot(ib_params *params, evb_board board)
1866 {
1867 	char uboot_filebuf[PATH_MAX+1];
1868 	const char *uboot_file;
1869 	struct stat sb;
1870 	off_t max_offset = 0;
1871 
1872 	/*
1873 	 * If we don't have a u-boot path for this board, it means
1874 	 * that a u-boot package wasn't found.  Prompt the user to
1875 	 * install it.
1876 	 */
1877 	if (evb_board_get_uboot_path(params, board) == NULL) {
1878 		warnx("No u-boot package found for board '%s'",
1879 		    params->board);
1880 		uboot_file = evb_board_get_uboot_pkg(params, board);
1881 		if (uboot_file != NULL)
1882 			warnx("Please install the sysutils/u-boot-%s package.",
1883 			    uboot_file);
1884 		return 0;
1885 	}
1886 
1887 	evb_ubinstall install = evb_board_get_uboot_install(params, board);
1888 	evb_ubsteps steps;
1889 	evb_ubstep step;
1890 
1891 	if (install == NULL)
1892 		return 0;
1893 
1894 	/*
1895 	 * First, make sure the files are all there.  While we're
1896 	 * at it, calculate the largest byte offset that we will
1897 	 * be writing.
1898 	 */
1899 	steps = evb_ubinstall_get_steps(params, install);
1900 	while ((step = evb_ubsteps_next_step(params, steps)) != NULL) {
1901 		uint64_t file_offset = evb_ubstep_get_file_offset(params, step);
1902 		uint64_t file_size = evb_ubstep_get_file_size(params, step);
1903 		uint64_t image_offset =
1904 		    evb_ubstep_get_image_offset(params, step);
1905 		uboot_file = evb_uboot_file_path(params, board, step,
1906 		    uboot_filebuf, sizeof(uboot_filebuf));
1907 		if (uboot_file == NULL)
1908 			return 0;
1909 		if (stat(uboot_file, &sb) < 0) {
1910 			warn("%s", uboot_file);
1911 			return 0;
1912 		}
1913 		if (!S_ISREG(sb.st_mode)) {
1914 			warnx("%s: %s", uboot_file, strerror(EFTYPE));
1915 			return 0;
1916 		}
1917 		off_t this_max;
1918 		if (file_size)
1919 			this_max = file_size;
1920 		else
1921 			this_max = sb.st_size - file_offset;
1922 		this_max += image_offset;
1923 		if (max_offset < this_max)
1924 			max_offset = this_max;
1925 	}
1926 
1927 	/*
1928 	 * Ok, we've verified that all of the files are there, and now
1929 	 * max_offset points to the first byte that's available for a
1930 	 * partition containing a file system.
1931 	 */
1932 
1933 	off_t rounded_max_offset = (off_t)(max_offset / params->sectorsize) *
1934 	    params->sectorsize;
1935 	if (rounded_max_offset != max_offset)
1936 		rounded_max_offset += params->sectorsize;
1937 
1938 	if (params->flags & IB_VERBOSE) {
1939 		printf("Max u-boot offset (rounded): %lld (%lld)\n",
1940 		    (long long)max_offset, (long long)rounded_max_offset);
1941 		printf("First free block available for file systems: "
1942 		    "%lld (0x%llx)\n",
1943 		    (long long)rounded_max_offset / params->sectorsize,
1944 		    (long long)rounded_max_offset / params->sectorsize);
1945 	}
1946 
1947 	/* XXX Check MBR table for overlapping partitions. */
1948 
1949 	/*
1950 	 * Now write each binary component to the appropriate location
1951 	 * on disk.
1952 	 */
1953 	steps = evb_ubinstall_get_steps(params, install);
1954 	while ((step = evb_ubsteps_next_step(params, steps)) != NULL) {
1955 		uboot_file = evb_uboot_file_path(params, board, step,
1956 		    uboot_filebuf, sizeof(uboot_filebuf));
1957 		if (uboot_file == NULL)
1958 			return 0;
1959 		if (!evb_uboot_do_step(params, uboot_file, step))
1960 			return 0;
1961 	}
1962 
1963 	return 1;
1964 }
1965