xref: /illumos-gate/usr/src/cmd/boot/bootadm/bootadm.c (revision d288ba74)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * bootadm(1M) is a new utility for managing bootability of
28  * Solaris *Newboot* environments. It has two primary tasks:
29  * 	- Allow end users to manage bootability of Newboot Solaris instances
30  *	- Provide services to other subsystems in Solaris (primarily Install)
31  */
32 
33 /* Headers */
34 #include <stdio.h>
35 #include <errno.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <signal.h>
44 #include <sys/wait.h>
45 #include <sys/mnttab.h>
46 #include <sys/mntent.h>
47 #include <sys/statvfs.h>
48 #include <libnvpair.h>
49 #include <ftw.h>
50 #include <fcntl.h>
51 #include <strings.h>
52 #include <utime.h>
53 #include <sys/systeminfo.h>
54 #include <sys/dktp/fdisk.h>
55 #include <sys/param.h>
56 #include <dirent.h>
57 #include <ctype.h>
58 #include <libgen.h>
59 #include <sys/sysmacros.h>
60 #include <sys/elf.h>
61 #include <libscf.h>
62 #include <zlib.h>
63 #include <sys/lockfs.h>
64 #include <sys/filio.h>
65 
66 #if !defined(_OPB)
67 #include <sys/ucode.h>
68 #endif
69 
70 #include <pwd.h>
71 #include <grp.h>
72 #include <device_info.h>
73 #include <sys/vtoc.h>
74 #include <sys/efi_partition.h>
75 
76 #include <locale.h>
77 
78 #include "message.h"
79 #include "bootadm.h"
80 
81 #ifndef TEXT_DOMAIN
82 #define	TEXT_DOMAIN	"SUNW_OST_OSCMD"
83 #endif	/* TEXT_DOMAIN */
84 
85 /* Type definitions */
86 
87 /* Primary subcmds */
88 typedef enum {
89 	BAM_MENU = 3,
90 	BAM_ARCHIVE
91 } subcmd_t;
92 
93 typedef enum {
94     OPT_ABSENT = 0,	/* No option */
95     OPT_REQ,		/* option required */
96     OPT_OPTIONAL	/* option may or may not be present */
97 } option_t;
98 
99 typedef struct {
100 	char	*subcmd;
101 	option_t option;
102 	error_t (*handler)();
103 	int	unpriv;			/* is this an unprivileged command */
104 } subcmd_defn_t;
105 
106 #define	LINE_INIT	0	/* lineNum initial value */
107 #define	ENTRY_INIT	-1	/* entryNum initial value */
108 #define	ALL_ENTRIES	-2	/* selects all boot entries */
109 
110 #define	GRUB_DIR		"/boot/grub"
111 #define	GRUB_STAGE2		GRUB_DIR "/stage2"
112 #define	GRUB_MENU		"/boot/grub/menu.lst"
113 #define	MENU_TMP		"/boot/grub/menu.lst.tmp"
114 #define	GRUB_BACKUP_MENU	"/etc/lu/GRUB_backup_menu"
115 #define	RAMDISK_SPECIAL		"/ramdisk"
116 #define	STUBBOOT		"/stubboot"
117 #define	MULTIBOOT		"/platform/i86pc/multiboot"
118 #define	GRUBSIGN_DIR		"/boot/grub/bootsign"
119 #define	GRUBSIGN_BACKUP		"/etc/bootsign"
120 #define	GRUBSIGN_UFS_PREFIX	"rootfs"
121 #define	GRUBSIGN_ZFS_PREFIX	"pool_"
122 #define	GRUBSIGN_LU_PREFIX	"BE_"
123 #define	UFS_SIGNATURE_LIST	"/var/run/grub_ufs_signatures"
124 #define	ZFS_LEGACY_MNTPT	"/tmp/bootadm_mnt_zfs_legacy"
125 
126 #define	BOOTADM_RDONLY_TEST	"BOOTADM_RDONLY_TEST"
127 
128 /* lock related */
129 #define	BAM_LOCK_FILE		"/var/run/bootadm.lock"
130 #define	LOCK_FILE_PERMS		(S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
131 
132 #define	CREATE_RAMDISK		"boot/solaris/bin/create_ramdisk"
133 #define	CREATE_DISKMAP		"boot/solaris/bin/create_diskmap"
134 #define	EXTRACT_BOOT_FILELIST	"boot/solaris/bin/extract_boot_filelist"
135 #define	GRUBDISK_MAP		"/var/run/solaris_grubdisk.map"
136 
137 #define	GRUB_slice		"/etc/lu/GRUB_slice"
138 #define	GRUB_root		"/etc/lu/GRUB_root"
139 #define	GRUB_fdisk		"/etc/lu/GRUB_fdisk"
140 #define	GRUB_fdisk_target	"/etc/lu/GRUB_fdisk_target"
141 #define	FINDROOT_INSTALLGRUB	"/etc/lu/installgrub.findroot"
142 #define	LULIB			"/usr/lib/lu/lulib"
143 #define	LULIB_PROPAGATE_FILE	"lulib_propagate_file"
144 #define	CKSUM			"/usr/bin/cksum"
145 #define	LU_MENU_CKSUM		"/etc/lu/menu.cksum"
146 #define	BOOTADM			"/sbin/bootadm"
147 
148 #define	INSTALLGRUB		"/sbin/installgrub"
149 #define	STAGE1			"/boot/grub/stage1"
150 #define	STAGE2			"/boot/grub/stage2"
151 
152 typedef enum zfs_mnted {
153 	ZFS_MNT_ERROR = -1,
154 	LEGACY_MOUNTED = 1,
155 	LEGACY_ALREADY,
156 	ZFS_MOUNTED,
157 	ZFS_ALREADY
158 } zfs_mnted_t;
159 
160 /*
161  * The following two defines are used to detect and create the correct
162  * boot archive  when safemode patching is underway.  LOFS_PATCH_FILE is a
163  * contracted private interface between bootadm and the install
164  * consolidation.  It is set by pdo.c when a patch with SUNW_PATCH_SAFEMODE
165  * is applied.
166  */
167 #define	LOFS_PATCH_FILE		"/var/run/.patch_loopback_mode"
168 #define	LOFS_PATCH_MNT		"/var/run/.patch_root_loopbackmnt"
169 
170 /*
171  * Default file attributes
172  */
173 #define	DEFAULT_DEV_MODE	0644	/* default permissions */
174 #define	DEFAULT_DEV_UID		0	/* user root */
175 #define	DEFAULT_DEV_GID		3	/* group sys */
176 
177 /*
178  * Menu related
179  * menu_cmd_t and menu_cmds must be kept in sync
180  */
181 char *menu_cmds[] = {
182 	"default",	/* DEFAULT_CMD */
183 	"timeout",	/* TIMEOUT_CMD */
184 	"title",	/* TITLE_CMD */
185 	"root",		/* ROOT_CMD */
186 	"kernel",	/* KERNEL_CMD */
187 	"kernel$",	/* KERNEL_DOLLAR_CMD */
188 	"module",	/* MODULE_CMD */
189 	"module$",	/* MODULE_DOLLAR_CMD */
190 	" ",		/* SEP_CMD */
191 	"#",		/* COMMENT_CMD */
192 	"chainloader",	/* CHAINLOADER_CMD */
193 	"args",		/* ARGS_CMD */
194 	"findroot",	/* FINDROOT_CMD */
195 	NULL
196 };
197 
198 #define	OPT_ENTRY_NUM	"entry"
199 
200 /*
201  * exec_cmd related
202  */
203 typedef struct {
204 	line_t *head;
205 	line_t *tail;
206 } filelist_t;
207 
208 #define	BOOT_FILE_LIST	"boot/solaris/filelist.ramdisk"
209 #define	ETC_FILE_LIST	"etc/boot/solaris/filelist.ramdisk"
210 
211 #define	FILE_STAT	"boot/solaris/filestat.ramdisk"
212 #define	FILE_STAT_TMP	"boot/solaris/filestat.ramdisk.tmp"
213 #define	DIR_PERMS	(S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
214 #define	FILE_STAT_MODE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
215 
216 #define	FILE_STAT_TIMESTAMP	"boot/solaris/timestamp.cache"
217 
218 /* Globals */
219 int bam_verbose;
220 int bam_force;
221 int bam_debug;
222 static char *prog;
223 static subcmd_t bam_cmd;
224 static char *bam_root;
225 static int bam_rootlen;
226 static int bam_root_readonly;
227 static int bam_alt_root;
228 static int bam_extend = 0;
229 static int bam_purge = 0;
230 static char *bam_subcmd;
231 static char *bam_opt;
232 static char **bam_argv;
233 static int bam_argc;
234 static int bam_check;
235 static int bam_saved_check;
236 static int bam_smf_check;
237 static int bam_lock_fd = -1;
238 static int bam_zfs;
239 static char rootbuf[PATH_MAX] = "/";
240 static int bam_update_all;
241 static int bam_alt_platform;
242 static char *bam_platform;
243 static char *bam_home_env = NULL;
244 
245 /* function prototypes */
246 static void parse_args_internal(int, char *[]);
247 static void parse_args(int, char *argv[]);
248 static error_t bam_menu(char *, char *, int, char *[]);
249 static error_t bam_archive(char *, char *);
250 
251 static void bam_exit(int);
252 static void bam_lock(void);
253 static void bam_unlock(void);
254 
255 static int exec_cmd(char *, filelist_t *);
256 static error_t read_globals(menu_t *, char *, char *, int);
257 static int menu_on_bootdisk(char *os_root, char *menu_root);
258 static menu_t *menu_read(char *);
259 static error_t menu_write(char *, menu_t *);
260 static void linelist_free(line_t *);
261 static void menu_free(menu_t *);
262 static void filelist_free(filelist_t *);
263 static error_t list2file(char *, char *, char *, line_t *);
264 static error_t list_entry(menu_t *, char *, char *);
265 static error_t delete_all_entries(menu_t *, char *, char *);
266 static error_t update_entry(menu_t *mp, char *menu_root, char *opt);
267 static error_t update_temp(menu_t *mp, char *dummy, char *opt);
268 
269 static error_t update_archive(char *, char *);
270 static error_t list_archive(char *, char *);
271 static error_t update_all(char *, char *);
272 static error_t read_list(char *, filelist_t *);
273 static error_t set_global(menu_t *, char *, int);
274 static error_t set_option(menu_t *, char *, char *);
275 static error_t set_kernel(menu_t *, menu_cmd_t, char *, char *, size_t);
276 static error_t get_kernel(menu_t *, menu_cmd_t, char *, size_t);
277 static char *expand_path(const char *);
278 
279 static long s_strtol(char *);
280 static int s_fputs(char *, FILE *);
281 
282 static int is_zfs(char *root);
283 static int is_ufs(char *root);
284 static int is_pcfs(char *root);
285 static int is_amd64(void);
286 static char *get_machine(void);
287 static void append_to_flist(filelist_t *, char *);
288 static char *mount_top_dataset(char *pool, zfs_mnted_t *mnted);
289 static int umount_top_dataset(char *pool, zfs_mnted_t mnted, char *mntpt);
290 static int ufs_add_to_sign_list(char *sign);
291 static error_t synchronize_BE_menu(void);
292 
293 #if !defined(_OPB)
294 static void ucode_install();
295 #endif
296 
297 /* Menu related sub commands */
298 static subcmd_defn_t menu_subcmds[] = {
299 	"set_option",		OPT_ABSENT,	set_option, 0,	/* PUB */
300 	"list_entry",		OPT_OPTIONAL,	list_entry, 1,	/* PUB */
301 	"delete_all_entries",	OPT_ABSENT,	delete_all_entries, 0, /* PVT */
302 	"update_entry",		OPT_REQ,	update_entry, 0, /* menu */
303 	"update_temp",		OPT_OPTIONAL,	update_temp, 0,	/* reboot */
304 	"upgrade",		OPT_ABSENT,	upgrade_menu, 0, /* menu */
305 	NULL,			0,		NULL, 0	/* must be last */
306 };
307 
308 /* Archive related sub commands */
309 static subcmd_defn_t arch_subcmds[] = {
310 	"update",		OPT_ABSENT,	update_archive, 0, /* PUB */
311 	"update_all",		OPT_ABSENT,	update_all, 0,	/* PVT */
312 	"list",			OPT_OPTIONAL,	list_archive, 1, /* PUB */
313 	NULL,			0,		NULL, 0	/* must be last */
314 };
315 
316 enum dircache_copy_opt {
317 	FILE32 = 0,
318 	FILE64,
319 	CACHEDIR_NUM
320 };
321 
322 /*
323  * Directory specific flags:
324  * NEED_UPDATE : the specified archive needs to be updated
325  * NO_MULTI : don't extend the specified archive, but recreate it
326  */
327 #define	NEED_UPDATE		0x00000001
328 #define	NO_MULTI		0x00000002
329 
330 #define	set_dir_flag(id, f)	(walk_arg.dirinfo[id].flags |= f)
331 #define	unset_dir_flag(id, f)	(walk_arg.dirinfo[id].flags &= ~f)
332 #define	is_dir_flag_on(id, f)	(walk_arg.dirinfo[id].flags & f ? 1 : 0)
333 
334 #define	get_cachedir(id)	(walk_arg.dirinfo[id].cdir_path)
335 #define	get_updatedir(id)	(walk_arg.dirinfo[id].update_path)
336 #define	get_count(id)		(walk_arg.dirinfo[id].count)
337 #define	has_cachedir(id)	(walk_arg.dirinfo[id].has_dir)
338 #define	set_dir_present(id)	(walk_arg.dirinfo[id].has_dir = 1)
339 
340 /*
341  * dirinfo_t (specific cache directory information):
342  * cdir_path:   path to the archive cache directory
343  * update_path: path to the update directory (contains the files that will be
344  *              used to extend the archive)
345  * has_dir:	the specified cache directory is active
346  * count:	the number of files to update
347  * flags:	directory specific flags
348  */
349 typedef struct _dirinfo {
350 	char	cdir_path[PATH_MAX];
351 	char	update_path[PATH_MAX];
352 	int	has_dir;
353 	int	count;
354 	int	flags;
355 } dirinfo_t;
356 
357 /*
358  * Update flags:
359  * NEED_CACHE_DIR : cache directory is missing and needs to be created
360  * IS_SPARC_TARGET : the target mountpoint is a SPARC environment
361  * UPDATE_ERROR : an error occourred while traversing the list of files
362  * RDONLY_FSCHK : the target filesystem is read-only
363  * RAMDSK_FSCHK : the target filesystem is on a ramdisk
364  */
365 #define	NEED_CACHE_DIR		0x00000001
366 #define	IS_SPARC_TARGET		0x00000002
367 #define	UPDATE_ERROR		0x00000004
368 #define	RDONLY_FSCHK		0x00000008
369 #define	INVALIDATE_CACHE	0x00000010
370 
371 #define	is_flag_on(flag)	(walk_arg.update_flags & flag ? 1 : 0)
372 #define	set_flag(flag)		(walk_arg.update_flags |= flag)
373 #define	unset_flag(flag)	(walk_arg.update_flags &= ~flag)
374 
375 /*
376  * struct walk_arg :
377  * update_flags: flags related to the current updating process
378  * new_nvlp/old_nvlp: new and old list of archive-files / attributes pairs
379  * sparcfile: list of file paths for mkisofs -path-list (SPARC only)
380  */
381 static struct {
382 	int 		update_flags;
383 	nvlist_t 	*new_nvlp;
384 	nvlist_t 	*old_nvlp;
385 	FILE 		*sparcfile;
386 	dirinfo_t	dirinfo[CACHEDIR_NUM];
387 } walk_arg;
388 
389 struct safefile {
390 	char *name;
391 	struct safefile *next;
392 };
393 
394 static struct safefile *safefiles = NULL;
395 #define	NEED_UPDATE_FILE "/etc/svc/volatile/boot_archive_needs_update"
396 
397 /* Thanks growisofs */
398 #define	CD_BLOCK	((off64_t)2048)
399 #define	VOLDESC_OFF	16
400 #define	DVD_BLOCK	(32*1024)
401 #define	MAX_IVDs	16
402 
403 struct iso_pdesc {
404     unsigned char type	[1];
405     unsigned char id	[5];
406     unsigned char void1	[80-5-1];
407     unsigned char volume_space_size [8];
408     unsigned char void2	[2048-80-8];
409 };
410 
411 /*
412  * COUNT_MAX:	maximum number of changed files to justify a multisession update
413  * BA_SIZE_MAX:	maximum size of the boot_archive to justify a multisession
414  * 		update
415  */
416 #define	COUNT_MAX		50
417 #define	BA_SIZE_MAX		(50 * 1024 * 1024)
418 
419 #define	bam_nowrite()		(bam_check || bam_smf_check)
420 
421 static int sync_menu = 1;	/* whether we need to sync the BE menus */
422 
423 static void
424 usage(void)
425 {
426 	(void) fprintf(stderr, "USAGE:\n");
427 
428 	/* archive usage */
429 	(void) fprintf(stderr,
430 	    "\t%s update-archive [-vn] [-R altroot [-p platform>]]\n", prog);
431 	(void) fprintf(stderr,
432 	    "\t%s list-archive [-R altroot [-p platform>]]\n", prog);
433 #if !defined(_OPB)
434 	/* x86 only */
435 	(void) fprintf(stderr, "\t%s set-menu [-R altroot] key=value\n", prog);
436 	(void) fprintf(stderr, "\t%s list-menu [-R altroot]\n", prog);
437 #endif
438 }
439 
440 /*
441  * Best effort attempt to restore the $HOME value.
442  */
443 static void
444 restore_env()
445 {
446 	char	home_env[PATH_MAX];
447 
448 	if (bam_home_env) {
449 		(void) snprintf(home_env, sizeof (home_env), "HOME=%s",
450 		    bam_home_env);
451 		(void) putenv(home_env);
452 	}
453 }
454 
455 
456 #define		SLEEP_TIME	5
457 #define		MAX_TRIES	4
458 
459 /*
460  * Sanitize the environment in which bootadm will execute its sub-processes
461  * (ex. mkisofs). This is done to prevent those processes from attempting
462  * to access files (ex. .mkisofsrc) or stat paths that might be on NFS
463  * or, potentially, insecure.
464  */
465 static void
466 sanitize_env()
467 {
468 	int	stry = 0;
469 
470 	/* don't depend on caller umask */
471 	(void) umask(0022);
472 
473 	/* move away from a potential unsafe current working directory */
474 	while (chdir("/") == -1) {
475 		if (errno != EINTR) {
476 			bam_print("WARNING: unable to chdir to /");
477 			break;
478 		}
479 	}
480 
481 	bam_home_env = getenv("HOME");
482 	while (bam_home_env != NULL && putenv("HOME=/") == -1) {
483 		if (errno == ENOMEM) {
484 			/* retry no more than MAX_TRIES times */
485 			if (++stry > MAX_TRIES) {
486 				bam_print("WARNING: unable to recover from "
487 				    "system memory pressure... aborting \n");
488 				bam_exit(EXIT_FAILURE);
489 			}
490 			/* memory is tight, try to sleep */
491 			bam_print("Attempting to recover from memory pressure: "
492 			    "sleeping for %d seconds\n", SLEEP_TIME * stry);
493 			(void) sleep(SLEEP_TIME * stry);
494 		} else {
495 			bam_print("WARNING: unable to sanitize HOME\n");
496 		}
497 	}
498 }
499 
500 int
501 main(int argc, char *argv[])
502 {
503 	error_t ret;
504 
505 	(void) setlocale(LC_ALL, "");
506 	(void) textdomain(TEXT_DOMAIN);
507 
508 	if ((prog = strrchr(argv[0], '/')) == NULL) {
509 		prog = argv[0];
510 	} else {
511 		prog++;
512 	}
513 
514 	INJECT_ERROR1("ASSERT_ON", assert(0))
515 
516 	sanitize_env();
517 
518 	parse_args(argc, argv);
519 
520 	switch (bam_cmd) {
521 		case BAM_MENU:
522 			ret = bam_menu(bam_subcmd, bam_opt, bam_argc, bam_argv);
523 			break;
524 		case BAM_ARCHIVE:
525 			ret = bam_archive(bam_subcmd, bam_opt);
526 			break;
527 		default:
528 			usage();
529 			bam_exit(1);
530 	}
531 
532 	if (ret != BAM_SUCCESS)
533 		bam_exit(1);
534 
535 	bam_unlock();
536 	return (0);
537 }
538 
539 /*
540  * Equivalence of public and internal commands:
541  *	update-archive  -- -a update
542  *	list-archive	-- -a list
543  *	set-menu	-- -m set_option
544  *	list-menu	-- -m list_entry
545  *	update-menu	-- -m update_entry
546  */
547 static struct cmd_map {
548 	char *bam_cmdname;
549 	int bam_cmd;
550 	char *bam_subcmd;
551 } cmd_map[] = {
552 	{ "update-archive",	BAM_ARCHIVE,	"update"},
553 	{ "list-archive",	BAM_ARCHIVE,	"list"},
554 	{ "set-menu",		BAM_MENU,	"set_option"},
555 	{ "list-menu",		BAM_MENU,	"list_entry"},
556 	{ "update-menu",	BAM_MENU,	"update_entry"},
557 	{ NULL,			0,		NULL}
558 };
559 
560 /*
561  * Commands syntax published in bootadm(1M) are parsed here
562  */
563 static void
564 parse_args(int argc, char *argv[])
565 {
566 	struct cmd_map *cmp = cmd_map;
567 
568 	/* command conforming to the final spec */
569 	if (argc > 1 && argv[1][0] != '-') {
570 		/*
571 		 * Map commands to internal table.
572 		 */
573 		while (cmp->bam_cmdname) {
574 			if (strcmp(argv[1], cmp->bam_cmdname) == 0) {
575 				bam_cmd = cmp->bam_cmd;
576 				bam_subcmd = cmp->bam_subcmd;
577 				break;
578 			}
579 			cmp++;
580 		}
581 		if (cmp->bam_cmdname == NULL) {
582 			usage();
583 			bam_exit(1);
584 		}
585 		argc--;
586 		argv++;
587 	}
588 
589 	parse_args_internal(argc, argv);
590 }
591 
592 /*
593  * A combination of public and private commands are parsed here.
594  * The internal syntax and the corresponding functionality are:
595  *	-a update	-- update-archive
596  *	-a list		-- list-archive
597  *	-a update-all	-- (reboot to sync all mounted OS archive)
598  *	-m update_entry	-- update-menu
599  *	-m list_entry	-- list-menu
600  *	-m update_temp	-- (reboot -- [boot-args])
601  *	-m delete_all_entries -- (called from install)
602  * A set of private flags is there too:
603  *	-F		-- purge the cache directories and rebuild them
604  *	-e		-- use the (faster) archive update approach (used by
605  *			   reboot)
606  */
607 static void
608 parse_args_internal(int argc, char *argv[])
609 {
610 	int c, error;
611 	extern char *optarg;
612 	extern int optind, opterr;
613 
614 	/* Suppress error message from getopt */
615 	opterr = 0;
616 
617 	error = 0;
618 	while ((c = getopt(argc, argv, "a:d:fm:no:veFCR:p:Z")) != -1) {
619 		switch (c) {
620 		case 'a':
621 			if (bam_cmd) {
622 				error = 1;
623 				bam_error(MULT_CMDS, c);
624 			}
625 			bam_cmd = BAM_ARCHIVE;
626 			bam_subcmd = optarg;
627 			break;
628 		case 'd':
629 			if (bam_debug) {
630 				error = 1;
631 				bam_error(DUP_OPT, c);
632 			}
633 			bam_debug = s_strtol(optarg);
634 			break;
635 		case 'f':
636 			bam_force = 1;
637 			break;
638 		case 'F':
639 			bam_purge = 1;
640 			break;
641 		case 'm':
642 			if (bam_cmd) {
643 				error = 1;
644 				bam_error(MULT_CMDS, c);
645 			}
646 			bam_cmd = BAM_MENU;
647 			bam_subcmd = optarg;
648 			break;
649 		case 'n':
650 			bam_check = 1;
651 			/*
652 			 * We save the original value of bam_check. The new
653 			 * approach in case of a read-only filesystem is to
654 			 * behave as a check, so we need a way to restore the
655 			 * original value after the evaluation of the read-only
656 			 * filesystem has been done.
657 			 * Even if we don't allow at the moment a check with
658 			 * update_all, this approach is more robust than
659 			 * simply resetting bam_check to zero.
660 			 */
661 			bam_saved_check = 1;
662 			break;
663 		case 'o':
664 			if (bam_opt) {
665 				error = 1;
666 				bam_error(DUP_OPT, c);
667 			}
668 			bam_opt = optarg;
669 			break;
670 		case 'v':
671 			bam_verbose = 1;
672 			break;
673 		case 'C':
674 			bam_smf_check = 1;
675 			break;
676 		case 'R':
677 			if (bam_root) {
678 				error = 1;
679 				bam_error(DUP_OPT, c);
680 				break;
681 			} else if (realpath(optarg, rootbuf) == NULL) {
682 				error = 1;
683 				bam_error(CANT_RESOLVE, optarg,
684 				    strerror(errno));
685 				break;
686 			}
687 			bam_alt_root = 1;
688 			bam_root = rootbuf;
689 			bam_rootlen = strlen(rootbuf);
690 			break;
691 		case 'p':
692 			bam_alt_platform = 1;
693 			bam_platform = optarg;
694 			if ((strcmp(bam_platform, "i86pc") != 0) &&
695 			    (strcmp(bam_platform, "sun4u") != 0) &&
696 			    (strcmp(bam_platform, "sun4v") != 0)) {
697 				error = 1;
698 				bam_error(INVALID_PLAT, bam_platform);
699 			}
700 			break;
701 		case 'Z':
702 			bam_zfs = 1;
703 			break;
704 		case 'e':
705 			bam_extend = 1;
706 			break;
707 		case '?':
708 			error = 1;
709 			bam_error(BAD_OPT, optopt);
710 			break;
711 		default :
712 			error = 1;
713 			bam_error(BAD_OPT, c);
714 			break;
715 		}
716 	}
717 
718 	/*
719 	 * An alternate platform requires an alternate root
720 	 */
721 	if (bam_alt_platform && bam_alt_root == 0) {
722 		usage();
723 		bam_exit(0);
724 	}
725 
726 	/*
727 	 * A command option must be specfied
728 	 */
729 	if (!bam_cmd) {
730 		if (bam_opt && strcmp(bam_opt, "all") == 0) {
731 			usage();
732 			bam_exit(0);
733 		}
734 		bam_error(NEED_CMD);
735 		error = 1;
736 	}
737 
738 	if (error) {
739 		usage();
740 		bam_exit(1);
741 	}
742 
743 	if (optind > argc) {
744 		bam_error(INT_ERROR, "parse_args");
745 		bam_exit(1);
746 	} else if (optind < argc) {
747 		bam_argv = &argv[optind];
748 		bam_argc = argc - optind;
749 	}
750 
751 	/*
752 	 * -n implies verbose mode
753 	 */
754 	if (bam_check)
755 		bam_verbose = 1;
756 }
757 
758 static error_t
759 check_subcmd_and_options(
760 	char *subcmd,
761 	char *opt,
762 	subcmd_defn_t *table,
763 	error_t (**fp)())
764 {
765 	int i;
766 
767 	if (subcmd == NULL) {
768 		bam_error(NEED_SUBCMD);
769 		return (BAM_ERROR);
770 	}
771 
772 	if (strcmp(subcmd, "set_option") == 0) {
773 		if (bam_argc == 0 || bam_argv == NULL || bam_argv[0] == NULL) {
774 			bam_error(MISSING_ARG);
775 			usage();
776 			return (BAM_ERROR);
777 		} else if (bam_argc > 1 || bam_argv[1] != NULL) {
778 			bam_error(TRAILING_ARGS);
779 			usage();
780 			return (BAM_ERROR);
781 		}
782 	} else if (strcmp(subcmd, "update_all") == 0) {
783 		/*
784 		 * The only option we accept for the "update_all"
785 		 * subcmd is "fastboot".
786 		 */
787 		if (bam_argc > 1 || (bam_argc == 1 &&
788 		    strcmp(bam_argv[0], "fastboot") != 0)) {
789 			bam_error(TRAILING_ARGS);
790 			usage();
791 			return (BAM_ERROR);
792 		}
793 		if (bam_argc == 1)
794 			sync_menu = 0;
795 	} else if (bam_argc || bam_argv) {
796 		bam_error(TRAILING_ARGS);
797 		usage();
798 		return (BAM_ERROR);
799 	}
800 
801 	if (bam_root == NULL) {
802 		bam_root = rootbuf;
803 		bam_rootlen = 1;
804 	}
805 
806 	/* verify that subcmd is valid */
807 	for (i = 0; table[i].subcmd != NULL; i++) {
808 		if (strcmp(table[i].subcmd, subcmd) == 0)
809 			break;
810 	}
811 
812 	if (table[i].subcmd == NULL) {
813 		bam_error(INVALID_SUBCMD, subcmd);
814 		return (BAM_ERROR);
815 	}
816 
817 	if (table[i].unpriv == 0 && geteuid() != 0) {
818 		bam_error(MUST_BE_ROOT);
819 		return (BAM_ERROR);
820 	}
821 
822 	/*
823 	 * Currently only privileged commands need a lock
824 	 */
825 	if (table[i].unpriv == 0)
826 		bam_lock();
827 
828 	/* subcmd verifies that opt is appropriate */
829 	if (table[i].option != OPT_OPTIONAL) {
830 		if ((table[i].option == OPT_REQ) ^ (opt != NULL)) {
831 			if (opt)
832 				bam_error(NO_OPT_REQ, subcmd);
833 			else
834 				bam_error(MISS_OPT, subcmd);
835 			return (BAM_ERROR);
836 		}
837 	}
838 
839 	*fp = table[i].handler;
840 
841 	return (BAM_SUCCESS);
842 }
843 
844 /*
845  * NOTE: A single "/" is also considered a trailing slash and will
846  * be deleted.
847  */
848 static void
849 elide_trailing_slash(const char *src, char *dst, size_t dstsize)
850 {
851 	size_t dstlen;
852 
853 	assert(src);
854 	assert(dst);
855 
856 	(void) strlcpy(dst, src, dstsize);
857 
858 	dstlen = strlen(dst);
859 	if (dst[dstlen - 1] == '/') {
860 		dst[dstlen - 1] = '\0';
861 	}
862 }
863 
864 static int
865 is_safe_exec(char *path)
866 {
867 	struct stat	sb;
868 
869 	if (lstat(path, &sb) != 0) {
870 		bam_error(STAT_FAIL, path, strerror(errno));
871 		return (BAM_ERROR);
872 	}
873 
874 	if (!S_ISREG(sb.st_mode)) {
875 		bam_error(PATH_EXEC_LINK, path);
876 		return (BAM_ERROR);
877 	}
878 
879 	if (sb.st_uid != getuid()) {
880 		bam_error(PATH_EXEC_OWNER, path, getuid());
881 		return (BAM_ERROR);
882 	}
883 
884 	if (sb.st_mode & S_IWOTH || sb.st_mode & S_IWGRP) {
885 		bam_error(PATH_EXEC_PERMS, path);
886 		return (BAM_ERROR);
887 	}
888 
889 	return (BAM_SUCCESS);
890 }
891 
892 static error_t
893 bam_menu(char *subcmd, char *opt, int largc, char *largv[])
894 {
895 	error_t			ret;
896 	char			menu_path[PATH_MAX];
897 	char			clean_menu_root[PATH_MAX];
898 	char			path[PATH_MAX];
899 	menu_t			*menu;
900 	char			menu_root[PATH_MAX];
901 	struct stat		sb;
902 	error_t (*f)(menu_t *mp, char *menu_path, char *opt);
903 	char			*special;
904 	char			*pool = NULL;
905 	zfs_mnted_t		zmnted;
906 	char			*zmntpt;
907 	char			*osdev;
908 	char			*osroot;
909 	const char		*fcn = "bam_menu()";
910 
911 	/*
912 	 * Menu sub-command only applies to GRUB (i.e. x86)
913 	 */
914 	if (!is_grub(bam_alt_root ? bam_root : "/")) {
915 		bam_error(NOT_GRUB_BOOT);
916 		return (BAM_ERROR);
917 	}
918 
919 	/*
920 	 * Check arguments
921 	 */
922 	ret = check_subcmd_and_options(subcmd, opt, menu_subcmds, &f);
923 	if (ret == BAM_ERROR) {
924 		return (BAM_ERROR);
925 	}
926 
927 	assert(bam_root);
928 
929 	(void) strlcpy(menu_root, bam_root, sizeof (menu_root));
930 	osdev = osroot = NULL;
931 
932 	if (strcmp(subcmd, "update_entry") == 0) {
933 		assert(opt);
934 
935 		osdev = strtok(opt, ",");
936 		assert(osdev);
937 		osroot = strtok(NULL, ",");
938 		if (osroot) {
939 			/* fixup bam_root so that it points at osroot */
940 			if (realpath(osroot, rootbuf) == NULL) {
941 				bam_error(CANT_RESOLVE, osroot,
942 				    strerror(errno));
943 				return (BAM_ERROR);
944 			}
945 			bam_alt_root = 1;
946 			bam_root  = rootbuf;
947 			bam_rootlen = strlen(rootbuf);
948 		}
949 	}
950 
951 	/*
952 	 * We support menu on PCFS (under certain conditions), but
953 	 * not the OS root
954 	 */
955 	if (is_pcfs(bam_root)) {
956 		bam_error(PCFS_ROOT_NOTSUP, bam_root);
957 		return (BAM_ERROR);
958 	}
959 
960 	if (stat(menu_root, &sb) == -1) {
961 		bam_error(CANNOT_LOCATE_GRUB_MENU);
962 		return (BAM_ERROR);
963 	}
964 
965 	BAM_DPRINTF((D_MENU_ROOT, fcn, menu_root));
966 
967 	/*
968 	 * We no longer use the GRUB slice file. If it exists, then
969 	 * the user is doing something that is unsupported (such as
970 	 * standard upgrading an old Live Upgrade BE). If that
971 	 * happens, mimic existing behavior i.e. pretend that it is
972 	 * not a BE. Emit a warning though.
973 	 */
974 	if (bam_alt_root) {
975 		(void) snprintf(path, sizeof (path), "%s%s", bam_root,
976 		    GRUB_slice);
977 	} else {
978 		(void) snprintf(path, sizeof (path), "%s", GRUB_slice);
979 	}
980 
981 	if (bam_verbose && stat(path, &sb) == 0)
982 		bam_error(GRUB_SLICE_FILE_EXISTS, path);
983 
984 	if (is_zfs(menu_root)) {
985 		assert(strcmp(menu_root, bam_root) == 0);
986 		special = get_special(menu_root);
987 		INJECT_ERROR1("Z_MENU_GET_SPECIAL", special = NULL);
988 		if (special == NULL) {
989 			bam_error(CANT_FIND_SPECIAL, menu_root);
990 			return (BAM_ERROR);
991 		}
992 		pool = strtok(special, "/");
993 		INJECT_ERROR1("Z_MENU_GET_POOL", pool = NULL);
994 		if (pool == NULL) {
995 			free(special);
996 			bam_error(CANT_FIND_POOL, menu_root);
997 			return (BAM_ERROR);
998 		}
999 		BAM_DPRINTF((D_Z_MENU_GET_POOL_FROM_SPECIAL, fcn, pool));
1000 
1001 		zmntpt = mount_top_dataset(pool, &zmnted);
1002 		INJECT_ERROR1("Z_MENU_MOUNT_TOP_DATASET", zmntpt = NULL);
1003 		if (zmntpt == NULL) {
1004 			bam_error(CANT_MOUNT_POOL_DATASET, pool);
1005 			free(special);
1006 			return (BAM_ERROR);
1007 		}
1008 		BAM_DPRINTF((D_Z_GET_MENU_MOUNT_TOP_DATASET, fcn, zmntpt));
1009 
1010 		(void) strlcpy(menu_root, zmntpt, sizeof (menu_root));
1011 		BAM_DPRINTF((D_Z_GET_MENU_MENU_ROOT, fcn, menu_root));
1012 	}
1013 
1014 	elide_trailing_slash(menu_root, clean_menu_root,
1015 	    sizeof (clean_menu_root));
1016 
1017 	BAM_DPRINTF((D_CLEAN_MENU_ROOT, fcn, clean_menu_root));
1018 
1019 	(void) strlcpy(menu_path, clean_menu_root, sizeof (menu_path));
1020 	(void) strlcat(menu_path, GRUB_MENU, sizeof (menu_path));
1021 
1022 	BAM_DPRINTF((D_MENU_PATH, fcn, menu_path));
1023 
1024 	/*
1025 	 * If listing the menu, display the menu location
1026 	 */
1027 	if (strcmp(subcmd, "list_entry") == 0) {
1028 		bam_print(GRUB_MENU_PATH, menu_path);
1029 	}
1030 
1031 
1032 	menu = menu_read(menu_path);
1033 	assert(menu);
1034 
1035 	/*
1036 	 * We already checked the following case in
1037 	 * check_subcmd_and_suboptions() above. Complete the
1038 	 * final step now.
1039 	 */
1040 	if (strcmp(subcmd, "set_option") == 0) {
1041 		assert(largc == 1 && largv[0] && largv[1] == NULL);
1042 		opt = largv[0];
1043 	} else {
1044 		assert(largc == 0 && largv == NULL);
1045 	}
1046 
1047 	ret = get_boot_cap(bam_root);
1048 	if (ret != BAM_SUCCESS) {
1049 		BAM_DPRINTF((D_BOOT_GET_CAP_FAILED, fcn));
1050 		goto out;
1051 	}
1052 
1053 	/*
1054 	 * Once the sub-cmd handler has run
1055 	 * only the line field is guaranteed to have valid values
1056 	 */
1057 	if (strcmp(subcmd, "update_entry") == 0)
1058 		ret = f(menu, menu_root, osdev);
1059 	else if (strcmp(subcmd, "upgrade") == 0)
1060 		ret = f(menu, bam_root, menu_root);
1061 	else if (strcmp(subcmd, "list_entry") == 0)
1062 		ret = f(menu, menu_path, opt);
1063 	else
1064 		ret = f(menu, NULL, opt);
1065 
1066 	if (ret == BAM_WRITE) {
1067 		BAM_DPRINTF((D_WRITING_MENU_ROOT, fcn, clean_menu_root));
1068 		ret = menu_write(clean_menu_root, menu);
1069 	}
1070 
1071 out:
1072 	INJECT_ERROR1("POOL_SET", pool = "/pooldata");
1073 	assert((is_zfs(menu_root)) ^ (pool == NULL));
1074 	if (pool) {
1075 		(void) umount_top_dataset(pool, zmnted, zmntpt);
1076 		free(special);
1077 	}
1078 	menu_free(menu);
1079 	return (ret);
1080 }
1081 
1082 
1083 static error_t
1084 bam_archive(
1085 	char *subcmd,
1086 	char *opt)
1087 {
1088 	error_t			ret;
1089 	error_t			(*f)(char *root, char *opt);
1090 	const char		*fcn = "bam_archive()";
1091 
1092 	/*
1093 	 * Add trailing / for archive subcommands
1094 	 */
1095 	if (rootbuf[strlen(rootbuf) - 1] != '/')
1096 		(void) strcat(rootbuf, "/");
1097 	bam_rootlen = strlen(rootbuf);
1098 
1099 	/*
1100 	 * Check arguments
1101 	 */
1102 	ret = check_subcmd_and_options(subcmd, opt, arch_subcmds, &f);
1103 	if (ret != BAM_SUCCESS) {
1104 		return (BAM_ERROR);
1105 	}
1106 
1107 	ret = get_boot_cap(rootbuf);
1108 	if (ret != BAM_SUCCESS) {
1109 		BAM_DPRINTF((D_BOOT_GET_CAP_FAILED, fcn));
1110 		return (ret);
1111 	}
1112 
1113 	/*
1114 	 * Check archive not supported with update_all
1115 	 * since it is awkward to display out-of-sync
1116 	 * information for each BE.
1117 	 */
1118 	if (bam_check && strcmp(subcmd, "update_all") == 0) {
1119 		bam_error(CHECK_NOT_SUPPORTED, subcmd);
1120 		return (BAM_ERROR);
1121 	}
1122 
1123 	if (strcmp(subcmd, "update_all") == 0)
1124 		bam_update_all = 1;
1125 
1126 #if !defined(_OPB)
1127 	ucode_install(bam_root);
1128 #endif
1129 
1130 	ret = f(bam_root, opt);
1131 
1132 	bam_update_all = 0;
1133 
1134 	return (ret);
1135 }
1136 
1137 /*PRINTFLIKE1*/
1138 void
1139 bam_error(char *format, ...)
1140 {
1141 	va_list ap;
1142 
1143 	va_start(ap, format);
1144 	(void) fprintf(stderr, "%s: ", prog);
1145 	(void) vfprintf(stderr, format, ap);
1146 	va_end(ap);
1147 }
1148 
1149 /*PRINTFLIKE1*/
1150 void
1151 bam_derror(char *format, ...)
1152 {
1153 	va_list ap;
1154 
1155 	assert(bam_debug);
1156 
1157 	va_start(ap, format);
1158 	(void) fprintf(stderr, "DEBUG: ");
1159 	(void) vfprintf(stderr, format, ap);
1160 	va_end(ap);
1161 }
1162 
1163 /*PRINTFLIKE1*/
1164 void
1165 bam_print(char *format, ...)
1166 {
1167 	va_list ap;
1168 
1169 	va_start(ap, format);
1170 	(void) vfprintf(stdout, format, ap);
1171 	va_end(ap);
1172 }
1173 
1174 /*PRINTFLIKE1*/
1175 void
1176 bam_print_stderr(char *format, ...)
1177 {
1178 	va_list ap;
1179 
1180 	va_start(ap, format);
1181 	(void) vfprintf(stderr, format, ap);
1182 	va_end(ap);
1183 }
1184 
1185 static void
1186 bam_exit(int excode)
1187 {
1188 	restore_env();
1189 	bam_unlock();
1190 	exit(excode);
1191 }
1192 
1193 static void
1194 bam_lock(void)
1195 {
1196 	struct flock lock;
1197 	pid_t pid;
1198 
1199 	bam_lock_fd = open(BAM_LOCK_FILE, O_CREAT|O_RDWR, LOCK_FILE_PERMS);
1200 	if (bam_lock_fd < 0) {
1201 		/*
1202 		 * We may be invoked early in boot for archive verification.
1203 		 * In this case, root is readonly and /var/run may not exist.
1204 		 * Proceed without the lock
1205 		 */
1206 		if (errno == EROFS || errno == ENOENT) {
1207 			bam_root_readonly = 1;
1208 			return;
1209 		}
1210 
1211 		bam_error(OPEN_FAIL, BAM_LOCK_FILE, strerror(errno));
1212 		bam_exit(1);
1213 	}
1214 
1215 	lock.l_type = F_WRLCK;
1216 	lock.l_whence = SEEK_SET;
1217 	lock.l_start = 0;
1218 	lock.l_len = 0;
1219 
1220 	if (fcntl(bam_lock_fd, F_SETLK, &lock) == -1) {
1221 		if (errno != EACCES && errno != EAGAIN) {
1222 			bam_error(LOCK_FAIL, BAM_LOCK_FILE, strerror(errno));
1223 			(void) close(bam_lock_fd);
1224 			bam_lock_fd = -1;
1225 			bam_exit(1);
1226 		}
1227 		pid = 0;
1228 		(void) pread(bam_lock_fd, &pid, sizeof (pid_t), 0);
1229 		bam_print(FILE_LOCKED, pid);
1230 
1231 		lock.l_type = F_WRLCK;
1232 		lock.l_whence = SEEK_SET;
1233 		lock.l_start = 0;
1234 		lock.l_len = 0;
1235 		if (fcntl(bam_lock_fd, F_SETLKW, &lock) == -1) {
1236 			bam_error(LOCK_FAIL, BAM_LOCK_FILE, strerror(errno));
1237 			(void) close(bam_lock_fd);
1238 			bam_lock_fd = -1;
1239 			bam_exit(1);
1240 		}
1241 	}
1242 
1243 	/* We own the lock now */
1244 	pid = getpid();
1245 	(void) write(bam_lock_fd, &pid, sizeof (pid));
1246 }
1247 
1248 static void
1249 bam_unlock(void)
1250 {
1251 	struct flock unlock;
1252 
1253 	/*
1254 	 * NOP if we don't hold the lock
1255 	 */
1256 	if (bam_lock_fd < 0) {
1257 		return;
1258 	}
1259 
1260 	unlock.l_type = F_UNLCK;
1261 	unlock.l_whence = SEEK_SET;
1262 	unlock.l_start = 0;
1263 	unlock.l_len = 0;
1264 
1265 	if (fcntl(bam_lock_fd, F_SETLK, &unlock) == -1) {
1266 		bam_error(UNLOCK_FAIL, BAM_LOCK_FILE, strerror(errno));
1267 	}
1268 
1269 	if (close(bam_lock_fd) == -1) {
1270 		bam_error(CLOSE_FAIL, BAM_LOCK_FILE, strerror(errno));
1271 	}
1272 	bam_lock_fd = -1;
1273 }
1274 
1275 static error_t
1276 list_archive(char *root, char *opt)
1277 {
1278 	filelist_t flist;
1279 	filelist_t *flistp = &flist;
1280 	line_t *lp;
1281 
1282 	assert(root);
1283 	assert(opt == NULL);
1284 
1285 	flistp->head = flistp->tail = NULL;
1286 	if (read_list(root, flistp) != BAM_SUCCESS) {
1287 		return (BAM_ERROR);
1288 	}
1289 	assert(flistp->head && flistp->tail);
1290 
1291 	for (lp = flistp->head; lp; lp = lp->next) {
1292 		bam_print(PRINT, lp->line);
1293 	}
1294 
1295 	filelist_free(flistp);
1296 
1297 	return (BAM_SUCCESS);
1298 }
1299 
1300 /*
1301  * This routine writes a list of lines to a file.
1302  * The list is *not* freed
1303  */
1304 static error_t
1305 list2file(char *root, char *tmp, char *final, line_t *start)
1306 {
1307 	char		tmpfile[PATH_MAX];
1308 	char		path[PATH_MAX];
1309 	FILE		*fp;
1310 	int		ret;
1311 	struct stat	sb;
1312 	mode_t		mode;
1313 	uid_t		root_uid;
1314 	gid_t		sys_gid;
1315 	struct passwd	*pw;
1316 	struct group	*gp;
1317 	const char	*fcn = "list2file()";
1318 
1319 	(void) snprintf(path, sizeof (path), "%s%s", root, final);
1320 
1321 	if (start == NULL) {
1322 		/* Empty GRUB menu */
1323 		if (stat(path, &sb) != -1) {
1324 			bam_print(UNLINK_EMPTY, path);
1325 			if (unlink(path) != 0) {
1326 				bam_error(UNLINK_FAIL, path, strerror(errno));
1327 				return (BAM_ERROR);
1328 			} else {
1329 				return (BAM_SUCCESS);
1330 			}
1331 		}
1332 		return (BAM_SUCCESS);
1333 	}
1334 
1335 	/*
1336 	 * Preserve attributes of existing file if possible,
1337 	 * otherwise ask the system for uid/gid of root/sys.
1338 	 * If all fails, fall back on hard-coded defaults.
1339 	 */
1340 	if (stat(path, &sb) != -1) {
1341 		mode = sb.st_mode;
1342 		root_uid = sb.st_uid;
1343 		sys_gid = sb.st_gid;
1344 	} else {
1345 		mode = DEFAULT_DEV_MODE;
1346 		if ((pw = getpwnam(DEFAULT_DEV_USER)) != NULL) {
1347 			root_uid = pw->pw_uid;
1348 		} else {
1349 			bam_error(CANT_FIND_USER,
1350 			    DEFAULT_DEV_USER, DEFAULT_DEV_UID);
1351 			root_uid = (uid_t)DEFAULT_DEV_UID;
1352 		}
1353 		if ((gp = getgrnam(DEFAULT_DEV_GROUP)) != NULL) {
1354 			sys_gid = gp->gr_gid;
1355 		} else {
1356 			bam_error(CANT_FIND_GROUP,
1357 			    DEFAULT_DEV_GROUP, DEFAULT_DEV_GID);
1358 			sys_gid = (gid_t)DEFAULT_DEV_GID;
1359 		}
1360 	}
1361 
1362 	(void) snprintf(tmpfile, sizeof (tmpfile), "%s%s", root, tmp);
1363 
1364 	/* Truncate tmpfile first */
1365 	fp = fopen(tmpfile, "w");
1366 	if (fp == NULL) {
1367 		bam_error(OPEN_FAIL, tmpfile, strerror(errno));
1368 		return (BAM_ERROR);
1369 	}
1370 	ret = fclose(fp);
1371 	INJECT_ERROR1("LIST2FILE_TRUNC_FCLOSE", ret = EOF);
1372 	if (ret == EOF) {
1373 		bam_error(CLOSE_FAIL, tmpfile, strerror(errno));
1374 		return (BAM_ERROR);
1375 	}
1376 
1377 	/* Now open it in append mode */
1378 	fp = fopen(tmpfile, "a");
1379 	if (fp == NULL) {
1380 		bam_error(OPEN_FAIL, tmpfile, strerror(errno));
1381 		return (BAM_ERROR);
1382 	}
1383 
1384 	for (; start; start = start->next) {
1385 		ret = s_fputs(start->line, fp);
1386 		INJECT_ERROR1("LIST2FILE_FPUTS", ret = EOF);
1387 		if (ret == EOF) {
1388 			bam_error(WRITE_FAIL, tmpfile, strerror(errno));
1389 			(void) fclose(fp);
1390 			return (BAM_ERROR);
1391 		}
1392 	}
1393 
1394 	ret = fclose(fp);
1395 	INJECT_ERROR1("LIST2FILE_APPEND_FCLOSE", ret = EOF);
1396 	if (ret == EOF) {
1397 		bam_error(CLOSE_FAIL, tmpfile, strerror(errno));
1398 		return (BAM_ERROR);
1399 	}
1400 
1401 	/*
1402 	 * Set up desired attributes.  Ignore failures on filesystems
1403 	 * not supporting these operations - pcfs reports unsupported
1404 	 * operations as EINVAL.
1405 	 */
1406 	ret = chmod(tmpfile, mode);
1407 	if (ret == -1 &&
1408 	    errno != EINVAL && errno != ENOTSUP) {
1409 		bam_error(CHMOD_FAIL, tmpfile, strerror(errno));
1410 		return (BAM_ERROR);
1411 	}
1412 
1413 	ret = chown(tmpfile, root_uid, sys_gid);
1414 	if (ret == -1 &&
1415 	    errno != EINVAL && errno != ENOTSUP) {
1416 		bam_error(CHOWN_FAIL, tmpfile, strerror(errno));
1417 		return (BAM_ERROR);
1418 	}
1419 
1420 
1421 	/*
1422 	 * Do an atomic rename
1423 	 */
1424 	ret = rename(tmpfile, path);
1425 	INJECT_ERROR1("LIST2FILE_RENAME", ret = -1);
1426 	if (ret != 0) {
1427 		bam_error(RENAME_FAIL, path, strerror(errno));
1428 		return (BAM_ERROR);
1429 	}
1430 
1431 	BAM_DPRINTF((D_WROTE_FILE, fcn, path));
1432 	return (BAM_SUCCESS);
1433 }
1434 
1435 /*
1436  * Checks if the path specified (without the file name at the end) exists
1437  * and creates it if not. If the path exists and is not a directory, an attempt
1438  * to unlink is made.
1439  */
1440 static int
1441 setup_path(char *path)
1442 {
1443 	char 		*p;
1444 	int		ret;
1445 	struct stat	sb;
1446 
1447 	p = strrchr(path, '/');
1448 	if (p != NULL) {
1449 		*p = '\0';
1450 		if (stat(path, &sb) != 0 || !(S_ISDIR(sb.st_mode))) {
1451 			/* best effort attempt, mkdirp will catch the error */
1452 			(void) unlink(path);
1453 			if (bam_verbose)
1454 				bam_print(NEED_DIRPATH, path);
1455 			ret = mkdirp(path, DIR_PERMS);
1456 			if (ret == -1) {
1457 				bam_error(MKDIR_FAILED, path, strerror(errno));
1458 				*p = '/';
1459 				return (BAM_ERROR);
1460 			}
1461 		}
1462 		*p = '/';
1463 		return (BAM_SUCCESS);
1464 	}
1465 	return (BAM_SUCCESS);
1466 }
1467 
1468 typedef union {
1469 	gzFile	gzfile;
1470 	int	fdfile;
1471 } outfile;
1472 
1473 typedef struct {
1474 	char		path[PATH_MAX];
1475 	outfile		out;
1476 } cachefile;
1477 
1478 static int
1479 setup_file(char *base, const char *path, cachefile *cf)
1480 {
1481 	int	ret;
1482 	char	*strip;
1483 
1484 	/* init gzfile or fdfile in case we fail before opening */
1485 	if (bam_direct == BAM_DIRECT_DBOOT)
1486 		cf->out.gzfile = NULL;
1487 	else
1488 		cf->out.fdfile = -1;
1489 
1490 	/* strip the trailing altroot path */
1491 	strip = (char *)path + strlen(rootbuf);
1492 
1493 	ret = snprintf(cf->path, sizeof (cf->path), "%s/%s", base, strip);
1494 	if (ret >= sizeof (cf->path)) {
1495 		bam_error(PATH_TOO_LONG, rootbuf);
1496 		return (BAM_ERROR);
1497 	}
1498 
1499 	/* Check if path is present in the archive cache directory */
1500 	if (setup_path(cf->path) == BAM_ERROR)
1501 		return (BAM_ERROR);
1502 
1503 	if (bam_direct == BAM_DIRECT_DBOOT) {
1504 		if ((cf->out.gzfile = gzopen(cf->path, "wb")) == NULL) {
1505 			bam_error(OPEN_FAIL, cf->path, strerror(errno));
1506 			return (BAM_ERROR);
1507 		}
1508 		(void) gzsetparams(cf->out.gzfile, Z_BEST_SPEED,
1509 		    Z_DEFAULT_STRATEGY);
1510 	} else {
1511 		if ((cf->out.fdfile = open(cf->path, O_WRONLY | O_CREAT, 0644))
1512 		    == -1) {
1513 			bam_error(OPEN_FAIL, cf->path, strerror(errno));
1514 			return (BAM_ERROR);
1515 		}
1516 	}
1517 
1518 	return (BAM_SUCCESS);
1519 }
1520 
1521 static int
1522 cache_write(cachefile cf, char *buf, int size)
1523 {
1524 	int	err;
1525 
1526 	if (bam_direct == BAM_DIRECT_DBOOT) {
1527 		if (gzwrite(cf.out.gzfile, buf, size) < 1) {
1528 			bam_error(GZ_WRITE_FAIL, gzerror(cf.out.gzfile, &err));
1529 			if (err == Z_ERRNO && bam_verbose) {
1530 				bam_error(WRITE_FAIL, cf.path, strerror(errno));
1531 			}
1532 			return (BAM_ERROR);
1533 		}
1534 	} else {
1535 		if (write(cf.out.fdfile, buf, size) < 1) {
1536 			bam_error(WRITE_FAIL, cf.path, strerror(errno));
1537 			return (BAM_ERROR);
1538 		}
1539 	}
1540 	return (BAM_SUCCESS);
1541 }
1542 
1543 static int
1544 cache_close(cachefile cf)
1545 {
1546 	int	ret;
1547 
1548 	if (bam_direct == BAM_DIRECT_DBOOT) {
1549 		if (cf.out.gzfile) {
1550 			ret = gzclose(cf.out.gzfile);
1551 			if (ret != Z_OK) {
1552 				bam_error(CLOSE_FAIL, cf.path, strerror(errno));
1553 				return (BAM_ERROR);
1554 			}
1555 		}
1556 	} else {
1557 		if (cf.out.fdfile != -1) {
1558 			ret = close(cf.out.fdfile);
1559 			if (ret != 0) {
1560 				bam_error(CLOSE_FAIL, cf.path, strerror(errno));
1561 				return (BAM_ERROR);
1562 			}
1563 		}
1564 	}
1565 
1566 	return (BAM_SUCCESS);
1567 }
1568 
1569 static int
1570 dircache_updatefile(const char *path, int what)
1571 {
1572 	int 		ret, exitcode;
1573 	char 		buf[4096 * 4];
1574 	FILE 		*infile;
1575 	cachefile 	outfile, outupdt;
1576 
1577 	if (bam_nowrite()) {
1578 		set_dir_flag(what, NEED_UPDATE);
1579 		return (BAM_SUCCESS);
1580 	}
1581 
1582 	if (!has_cachedir(what))
1583 		return (BAM_SUCCESS);
1584 
1585 	if ((infile = fopen(path, "rb")) == NULL) {
1586 		bam_error(OPEN_FAIL, path, strerror(errno));
1587 		return (BAM_ERROR);
1588 	}
1589 
1590 	ret = setup_file(get_cachedir(what), path, &outfile);
1591 	if (ret == BAM_ERROR) {
1592 		exitcode = BAM_ERROR;
1593 		goto out;
1594 	}
1595 	if (!is_dir_flag_on(what, NO_MULTI)) {
1596 		ret = setup_file(get_updatedir(what), path, &outupdt);
1597 		if (ret == BAM_ERROR)
1598 			set_dir_flag(what, NO_MULTI);
1599 	}
1600 
1601 	while ((ret = fread(buf, 1, sizeof (buf), infile)) > 0) {
1602 		if (cache_write(outfile, buf, ret) == BAM_ERROR) {
1603 			exitcode = BAM_ERROR;
1604 			goto out;
1605 		}
1606 		if (!is_dir_flag_on(what, NO_MULTI))
1607 			if (cache_write(outupdt, buf, ret) == BAM_ERROR)
1608 				set_dir_flag(what, NO_MULTI);
1609 	}
1610 
1611 	set_dir_flag(what, NEED_UPDATE);
1612 	get_count(what)++;
1613 	if (get_count(what) > COUNT_MAX)
1614 		set_dir_flag(what, NO_MULTI);
1615 	exitcode = BAM_SUCCESS;
1616 out:
1617 	(void) fclose(infile);
1618 	if (cache_close(outfile) == BAM_ERROR)
1619 		exitcode = BAM_ERROR;
1620 	if (!is_dir_flag_on(what, NO_MULTI) &&
1621 	    cache_close(outupdt) == BAM_ERROR)
1622 		exitcode = BAM_ERROR;
1623 	if (exitcode == BAM_ERROR)
1624 		set_flag(UPDATE_ERROR);
1625 	return (exitcode);
1626 }
1627 
1628 static int
1629 dircache_updatedir(const char *path, int what, int updt)
1630 {
1631 	int		ret;
1632 	char		dpath[PATH_MAX];
1633 	char		*strip;
1634 	struct stat	sb;
1635 
1636 	strip = (char *)path + strlen(rootbuf);
1637 
1638 	ret = snprintf(dpath, sizeof (dpath), "%s/%s", updt ?
1639 	    get_updatedir(what) : get_cachedir(what), strip);
1640 
1641 	if (ret >= sizeof (dpath)) {
1642 		bam_error(PATH_TOO_LONG, rootbuf);
1643 		set_flag(UPDATE_ERROR);
1644 		return (BAM_ERROR);
1645 	}
1646 
1647 	if (stat(dpath, &sb) == 0 && S_ISDIR(sb.st_mode))
1648 		return (BAM_SUCCESS);
1649 
1650 	if (updt) {
1651 		if (!is_dir_flag_on(what, NO_MULTI))
1652 			if (!bam_nowrite() && mkdirp(dpath, DIR_PERMS) == -1)
1653 				set_dir_flag(what, NO_MULTI);
1654 	} else {
1655 		if (!bam_nowrite() && mkdirp(dpath, DIR_PERMS) == -1) {
1656 			set_flag(UPDATE_ERROR);
1657 			return (BAM_ERROR);
1658 		}
1659 	}
1660 
1661 	set_dir_flag(what, NEED_UPDATE);
1662 	return (BAM_SUCCESS);
1663 }
1664 
1665 #define	DO_CACHE_DIR	0
1666 #define	DO_UPDATE_DIR	1
1667 
1668 #if defined(_LP64) || defined(_LONGLONG_TYPE)
1669 typedef		Elf64_Ehdr	_elfhdr;
1670 #else
1671 typedef		Elf32_Ehdr	_elfhdr;
1672 #endif
1673 
1674 /*
1675  * This routine updates the contents of the cache directory
1676  */
1677 static int
1678 update_dircache(const char *path, int flags)
1679 {
1680 	int rc = BAM_SUCCESS;
1681 
1682 	switch (flags) {
1683 	case FTW_F:
1684 		{
1685 		int	fd;
1686 		_elfhdr	elf;
1687 
1688 		if ((fd = open(path, O_RDONLY)) < 0) {
1689 			bam_error(OPEN_FAIL, path, strerror(errno));
1690 			set_flag(UPDATE_ERROR);
1691 			rc = BAM_ERROR;
1692 			break;
1693 		}
1694 
1695 		/*
1696 		 * libelf and gelf would be a cleaner and easier way to handle
1697 		 * this, but libelf fails compilation if _ILP32 is defined &&
1698 		 * _FILE_OFFSET_BITS is != 32 ...
1699 		 */
1700 		if (read(fd, (void *)&elf, sizeof (_elfhdr)) < 0) {
1701 			bam_error(READ_FAIL, path, strerror(errno));
1702 			set_flag(UPDATE_ERROR);
1703 			(void) close(fd);
1704 			rc = BAM_ERROR;
1705 			break;
1706 		}
1707 		(void) close(fd);
1708 
1709 		/*
1710 		 * If the file is not an executable and is not inside an amd64
1711 		 * directory, we copy it in both the cache directories,
1712 		 * otherwise, we only copy it inside the 64-bit one.
1713 		 */
1714 		if (memcmp(elf.e_ident, ELFMAG, 4) != 0) {
1715 			if (strstr(path, "/amd64")) {
1716 				rc = dircache_updatefile(path, FILE64);
1717 			} else {
1718 				rc = dircache_updatefile(path, FILE32);
1719 				if (rc == BAM_SUCCESS)
1720 					rc = dircache_updatefile(path, FILE64);
1721 			}
1722 		} else {
1723 			/*
1724 			 * Based on the ELF class we copy the file in the 32-bit
1725 			 * or the 64-bit cache directory.
1726 			 */
1727 			if (elf.e_ident[EI_CLASS] == ELFCLASS32) {
1728 				rc = dircache_updatefile(path, FILE32);
1729 			} else if (elf.e_ident[EI_CLASS] == ELFCLASS64) {
1730 				rc = dircache_updatefile(path, FILE64);
1731 			} else {
1732 				bam_print(NO3264ELF, path);
1733 				/* paranoid */
1734 				rc  = dircache_updatefile(path, FILE32);
1735 				if (rc == BAM_SUCCESS)
1736 					rc = dircache_updatefile(path, FILE64);
1737 			}
1738 		}
1739 		break;
1740 		}
1741 	case FTW_D:
1742 		if (strstr(path, "/amd64") == NULL) {
1743 			rc = dircache_updatedir(path, FILE32, DO_UPDATE_DIR);
1744 			if (rc == BAM_SUCCESS)
1745 				rc = dircache_updatedir(path, FILE32,
1746 				    DO_CACHE_DIR);
1747 		} else {
1748 			if (has_cachedir(FILE64)) {
1749 				rc = dircache_updatedir(path, FILE64,
1750 				    DO_UPDATE_DIR);
1751 				if (rc == BAM_SUCCESS)
1752 					rc = dircache_updatedir(path, FILE64,
1753 					    DO_CACHE_DIR);
1754 			}
1755 		}
1756 		break;
1757 	default:
1758 		rc = BAM_ERROR;
1759 		break;
1760 	}
1761 
1762 	return (rc);
1763 }
1764 
1765 /*ARGSUSED*/
1766 static int
1767 cmpstat(
1768 	const char *file,
1769 	const struct stat *st,
1770 	int flags,
1771 	struct FTW *ftw)
1772 {
1773 	uint_t 		sz;
1774 	uint64_t 	*value;
1775 	uint64_t 	filestat[2];
1776 	int 		error, ret;
1777 
1778 	struct safefile *safefilep;
1779 	FILE 		*fp;
1780 	struct stat	sb;
1781 
1782 	/*
1783 	 * On SPARC we create/update links too.
1784 	 */
1785 	if (flags != FTW_F && flags != FTW_D && (flags == FTW_SL &&
1786 	    !is_flag_on(IS_SPARC_TARGET)))
1787 		return (0);
1788 
1789 	/*
1790 	 * Ignore broken links
1791 	 */
1792 	if (flags == FTW_SL && stat(file, &sb) < 0)
1793 		return (0);
1794 
1795 	/*
1796 	 * new_nvlp may be NULL if there were errors earlier
1797 	 * but this is not fatal to update determination.
1798 	 */
1799 	if (walk_arg.new_nvlp) {
1800 		filestat[0] = st->st_size;
1801 		filestat[1] = st->st_mtime;
1802 		error = nvlist_add_uint64_array(walk_arg.new_nvlp,
1803 		    file + bam_rootlen, filestat, 2);
1804 		if (error)
1805 			bam_error(NVADD_FAIL, file, strerror(error));
1806 	}
1807 
1808 	/*
1809 	 * If we are invoked as part of system/filesystem/boot-archive, then
1810 	 * there are a number of things we should not worry about
1811 	 */
1812 	if (bam_smf_check) {
1813 		/* ignore amd64 modules unless we are booted amd64. */
1814 		if (!is_amd64() && strstr(file, "/amd64/") != 0)
1815 			return (0);
1816 
1817 		/* read in list of safe files */
1818 		if (safefiles == NULL)
1819 			if (fp = fopen("/boot/solaris/filelist.safe", "r")) {
1820 				safefiles = s_calloc(1,
1821 				    sizeof (struct safefile));
1822 				safefilep = safefiles;
1823 				safefilep->name = s_calloc(1, MAXPATHLEN +
1824 				    MAXNAMELEN);
1825 				safefilep->next = NULL;
1826 				while (s_fgets(safefilep->name, MAXPATHLEN +
1827 				    MAXNAMELEN, fp) != NULL) {
1828 					safefilep->next = s_calloc(1,
1829 					    sizeof (struct safefile));
1830 					safefilep = safefilep->next;
1831 					safefilep->name = s_calloc(1,
1832 					    MAXPATHLEN + MAXNAMELEN);
1833 					safefilep->next = NULL;
1834 				}
1835 				(void) fclose(fp);
1836 			}
1837 	}
1838 
1839 	/*
1840 	 * On SPARC we create a -path-list file for mkisofs
1841 	 */
1842 	if (is_flag_on(IS_SPARC_TARGET) && !bam_nowrite()) {
1843 		if (flags != FTW_D) {
1844 			char	*strip;
1845 
1846 			strip = (char *)file + strlen(rootbuf);
1847 			(void) fprintf(walk_arg.sparcfile, "/%s=%s\n", strip,
1848 			    file);
1849 		}
1850 	}
1851 
1852 	/*
1853 	 * We are transitioning from the old model to the dircache or the cache
1854 	 * directory was removed: create the entry without further checkings.
1855 	 */
1856 	if (is_flag_on(NEED_CACHE_DIR)) {
1857 		if (bam_verbose)
1858 			bam_print(PARSEABLE_NEW_FILE, file);
1859 
1860 		if (is_flag_on(IS_SPARC_TARGET)) {
1861 			set_dir_flag(FILE64, NEED_UPDATE);
1862 			return (0);
1863 		}
1864 
1865 		ret = update_dircache(file, flags);
1866 		if (ret == BAM_ERROR) {
1867 			bam_error(UPDT_CACHE_FAIL, file);
1868 			return (-1);
1869 		}
1870 
1871 		return (0);
1872 	}
1873 
1874 	/*
1875 	 * We need an update if file doesn't exist in old archive
1876 	 */
1877 	if (walk_arg.old_nvlp == NULL ||
1878 	    nvlist_lookup_uint64_array(walk_arg.old_nvlp,
1879 	    file + bam_rootlen, &value, &sz) != 0) {
1880 		if (bam_smf_check)	/* ignore new during smf check */
1881 			return (0);
1882 
1883 		if (is_flag_on(IS_SPARC_TARGET)) {
1884 			set_dir_flag(FILE64, NEED_UPDATE);
1885 		} else {
1886 			ret = update_dircache(file, flags);
1887 			if (ret == BAM_ERROR) {
1888 				bam_error(UPDT_CACHE_FAIL, file);
1889 				return (-1);
1890 			}
1891 		}
1892 
1893 		if (bam_verbose)
1894 			bam_print(PARSEABLE_NEW_FILE, file);
1895 		return (0);
1896 	}
1897 
1898 	/*
1899 	 * If we got there, the file is already listed as to be included in the
1900 	 * iso image. We just need to know if we are going to rebuild it or not
1901 	 */
1902 	if (is_flag_on(IS_SPARC_TARGET) &&
1903 	    is_dir_flag_on(FILE64, NEED_UPDATE) && !bam_nowrite())
1904 		return (0);
1905 	/*
1906 	 * File exists in old archive. Check if file has changed
1907 	 */
1908 	assert(sz == 2);
1909 	bcopy(value, filestat, sizeof (filestat));
1910 
1911 	if (flags != FTW_D && (filestat[0] != st->st_size ||
1912 	    filestat[1] != st->st_mtime)) {
1913 		if (bam_smf_check) {
1914 			safefilep = safefiles;
1915 			while (safefilep != NULL) {
1916 				if (strcmp(file + bam_rootlen,
1917 				    safefilep->name) == 0) {
1918 					(void) creat(NEED_UPDATE_FILE, 0644);
1919 					return (0);
1920 				}
1921 				safefilep = safefilep->next;
1922 			}
1923 		}
1924 
1925 		if (is_flag_on(IS_SPARC_TARGET)) {
1926 			set_dir_flag(FILE64, NEED_UPDATE);
1927 		} else {
1928 			ret = update_dircache(file, flags);
1929 			if (ret == BAM_ERROR) {
1930 				bam_error(UPDT_CACHE_FAIL, file);
1931 				return (-1);
1932 			}
1933 		}
1934 
1935 		if (bam_verbose)
1936 			if (bam_smf_check)
1937 				bam_print("    %s\n", file);
1938 			else
1939 				bam_print(PARSEABLE_OUT_DATE, file);
1940 	}
1941 
1942 	return (0);
1943 }
1944 
1945 /*
1946  * Remove a directory path recursively
1947  */
1948 static int
1949 rmdir_r(char *path)
1950 {
1951 	struct dirent 	*d = NULL;
1952 	DIR 		*dir = NULL;
1953 	char 		tpath[PATH_MAX];
1954 	struct stat 	sb;
1955 
1956 	if ((dir = opendir(path)) == NULL)
1957 		return (-1);
1958 
1959 	while (d = readdir(dir)) {
1960 		if ((strcmp(d->d_name, ".") != 0) &&
1961 		    (strcmp(d->d_name, "..") != 0)) {
1962 			(void) snprintf(tpath, sizeof (tpath), "%s/%s",
1963 			    path, d->d_name);
1964 			if (stat(tpath, &sb) == 0) {
1965 				if (sb.st_mode & S_IFDIR)
1966 					(void) rmdir_r(tpath);
1967 				else
1968 					(void) remove(tpath);
1969 			}
1970 		}
1971 	}
1972 	return (remove(path));
1973 }
1974 
1975 /*
1976  * Check if cache directory exists and, if not, create it and update flags
1977  * accordingly. If the path exists, but it's not a directory, a best effort
1978  * attempt to remove and recreate it is made.
1979  * If the user requested a 'purge', always recreate the directory from scratch.
1980  */
1981 static int
1982 set_cache_dir(char *root, int what)
1983 {
1984 	struct stat	sb;
1985 	int		ret = 0;
1986 
1987 	ret = snprintf(get_cachedir(what), sizeof (get_cachedir(what)),
1988 	    "%s%s%s%s%s", root, ARCHIVE_PREFIX, get_machine(), what == FILE64 ?
1989 	    "/amd64" : "", CACHEDIR_SUFFIX);
1990 
1991 	if (ret >= sizeof (get_cachedir(what))) {
1992 		bam_error(PATH_TOO_LONG, rootbuf);
1993 		return (BAM_ERROR);
1994 	}
1995 
1996 	if (bam_purge || is_flag_on(INVALIDATE_CACHE))
1997 		(void) rmdir_r(get_cachedir(what));
1998 
1999 	if (stat(get_cachedir(what), &sb) != 0 || !(S_ISDIR(sb.st_mode))) {
2000 		/* best effort unlink attempt, mkdir will catch errors */
2001 		(void) unlink(get_cachedir(what));
2002 
2003 		if (bam_verbose)
2004 			bam_print(UPDATE_CDIR_MISS, get_cachedir(what));
2005 		ret = mkdir(get_cachedir(what), DIR_PERMS);
2006 		if (ret < 0) {
2007 			bam_error(MKDIR_FAILED, get_cachedir(what),
2008 			    strerror(errno));
2009 			get_cachedir(what)[0] = '\0';
2010 			return (ret);
2011 		}
2012 		set_flag(NEED_CACHE_DIR);
2013 		set_dir_flag(what, NO_MULTI);
2014 	}
2015 
2016 	return (BAM_SUCCESS);
2017 }
2018 
2019 static int
2020 set_update_dir(char *root, int what)
2021 {
2022 	struct stat	sb;
2023 	int		ret;
2024 
2025 	if (is_dir_flag_on(what, NO_MULTI))
2026 		return (BAM_SUCCESS);
2027 
2028 	if (!bam_extend) {
2029 		set_dir_flag(what, NO_MULTI);
2030 		return (BAM_SUCCESS);
2031 	}
2032 
2033 	if (what == FILE64 && !is_flag_on(IS_SPARC_TARGET))
2034 		ret = snprintf(get_updatedir(what),
2035 		    sizeof (get_updatedir(what)), "%s%s%s/amd64%s", root,
2036 		    ARCHIVE_PREFIX, get_machine(), UPDATEDIR_SUFFIX);
2037 	else
2038 		ret = snprintf(get_updatedir(what),
2039 		    sizeof (get_updatedir(what)), "%s%s%s%s", root,
2040 		    ARCHIVE_PREFIX, get_machine(), UPDATEDIR_SUFFIX);
2041 
2042 	if (ret >= sizeof (get_updatedir(what))) {
2043 		bam_error(PATH_TOO_LONG, rootbuf);
2044 		return (BAM_ERROR);
2045 	}
2046 
2047 	if (stat(get_updatedir(what), &sb) == 0) {
2048 		if (S_ISDIR(sb.st_mode))
2049 			ret = rmdir_r(get_updatedir(what));
2050 		else
2051 			ret = unlink(get_updatedir(what));
2052 
2053 		if (ret != 0)
2054 			set_dir_flag(what, NO_MULTI);
2055 	}
2056 
2057 	if (mkdir(get_updatedir(what), DIR_PERMS) < 0)
2058 		set_dir_flag(what, NO_MULTI);
2059 
2060 	return (BAM_SUCCESS);
2061 }
2062 
2063 static int
2064 is_valid_archive(char *root, int what)
2065 {
2066 	char 		archive_path[PATH_MAX];
2067 	char		timestamp_path[PATH_MAX];
2068 	struct stat 	sb, timestamp;
2069 	int 		ret;
2070 
2071 	if (what == FILE64 && !is_flag_on(IS_SPARC_TARGET))
2072 		ret = snprintf(archive_path, sizeof (archive_path),
2073 		    "%s%s%s/amd64%s", root, ARCHIVE_PREFIX, get_machine(),
2074 		    ARCHIVE_SUFFIX);
2075 	else
2076 		ret = snprintf(archive_path, sizeof (archive_path), "%s%s%s%s",
2077 		    root, ARCHIVE_PREFIX, get_machine(), ARCHIVE_SUFFIX);
2078 
2079 	if (ret >= sizeof (archive_path)) {
2080 		bam_error(PATH_TOO_LONG, rootbuf);
2081 		return (BAM_ERROR);
2082 	}
2083 
2084 	if (stat(archive_path, &sb) != 0) {
2085 		if (bam_verbose && !bam_check)
2086 			bam_print(UPDATE_ARCH_MISS, archive_path);
2087 		set_dir_flag(what, NEED_UPDATE);
2088 		set_dir_flag(what, NO_MULTI);
2089 		return (BAM_SUCCESS);
2090 	}
2091 
2092 	/*
2093 	 * The timestamp file is used to prevent stale files in the archive
2094 	 * cache.
2095 	 * Stale files can happen if the system is booted back and forth across
2096 	 * the transition from bootadm-before-the-cache to
2097 	 * bootadm-after-the-cache, since older versions of bootadm don't know
2098 	 * about the existence of the archive cache.
2099 	 *
2100 	 * Since only bootadm-after-the-cache versions know about about this
2101 	 * file, we require that the boot archive be older than this file.
2102 	 */
2103 	ret = snprintf(timestamp_path, sizeof (timestamp_path), "%s%s", root,
2104 	    FILE_STAT_TIMESTAMP);
2105 
2106 	if (ret >= sizeof (timestamp_path)) {
2107 		bam_error(PATH_TOO_LONG, rootbuf);
2108 		return (BAM_ERROR);
2109 	}
2110 
2111 	if (stat(timestamp_path, &timestamp) != 0 ||
2112 	    sb.st_mtime > timestamp.st_mtime) {
2113 		if (bam_verbose && !bam_check)
2114 			bam_print(UPDATE_CACHE_OLD, timestamp);
2115 		/*
2116 		 * Don't generate a false positive for the boot-archive service
2117 		 * but trigger an update of the archive cache in
2118 		 * boot-archive-update.
2119 		 */
2120 		if (bam_smf_check) {
2121 			(void) creat(NEED_UPDATE_FILE, 0644);
2122 			return (BAM_SUCCESS);
2123 		}
2124 
2125 		set_flag(INVALIDATE_CACHE);
2126 		set_dir_flag(what, NEED_UPDATE);
2127 		set_dir_flag(what, NO_MULTI);
2128 		return (BAM_SUCCESS);
2129 	}
2130 
2131 	if (is_flag_on(IS_SPARC_TARGET))
2132 		return (BAM_SUCCESS);
2133 
2134 	if (bam_extend && sb.st_size > BA_SIZE_MAX) {
2135 		if (bam_verbose && !bam_check)
2136 			bam_print(MULTI_SIZE, archive_path, BA_SIZE_MAX);
2137 		set_dir_flag(what, NO_MULTI);
2138 	}
2139 
2140 	return (BAM_SUCCESS);
2141 }
2142 
2143 /*
2144  * Check flags and presence of required files and directories.
2145  * The force flag and/or absence of files should
2146  * trigger an update.
2147  * Suppress stdout output if check (-n) option is set
2148  * (as -n should only produce parseable output.)
2149  */
2150 static int
2151 check_flags_and_files(char *root)
2152 {
2153 
2154 	struct stat 	sb;
2155 	int 		ret;
2156 
2157 	/*
2158 	 * If archive is missing, create archive
2159 	 */
2160 	if (is_flag_on(IS_SPARC_TARGET)) {
2161 		ret = is_valid_archive(root, FILE64);
2162 		if (ret == BAM_ERROR)
2163 			return (BAM_ERROR);
2164 	} else {
2165 		int	what = FILE32;
2166 		do {
2167 			ret = is_valid_archive(root, what);
2168 			if (ret == BAM_ERROR)
2169 				return (BAM_ERROR);
2170 			what++;
2171 		} while (bam_direct == BAM_DIRECT_DBOOT && what < CACHEDIR_NUM);
2172 	}
2173 
2174 	if (bam_nowrite())
2175 		return (BAM_SUCCESS);
2176 
2177 
2178 	/*
2179 	 * check if cache directories exist on x86.
2180 	 * check (and always open) the cache file on SPARC.
2181 	 */
2182 	if (is_sparc()) {
2183 		ret = snprintf(get_cachedir(FILE64),
2184 		    sizeof (get_cachedir(FILE64)), "%s%s%s/%s", root,
2185 		    ARCHIVE_PREFIX, get_machine(), CACHEDIR_SUFFIX);
2186 
2187 		if (ret >= sizeof (get_cachedir(FILE64))) {
2188 			bam_error(PATH_TOO_LONG, rootbuf);
2189 			return (BAM_ERROR);
2190 		}
2191 
2192 		if (stat(get_cachedir(FILE64), &sb) != 0) {
2193 			set_flag(NEED_CACHE_DIR);
2194 			set_dir_flag(FILE64, NEED_UPDATE);
2195 		}
2196 
2197 		walk_arg.sparcfile = fopen(get_cachedir(FILE64), "w");
2198 		if (walk_arg.sparcfile == NULL) {
2199 			bam_error(OPEN_FAIL, get_cachedir(FILE64),
2200 			    strerror(errno));
2201 			return (BAM_ERROR);
2202 		}
2203 
2204 		set_dir_present(FILE64);
2205 	} else {
2206 		int	what = FILE32;
2207 
2208 		do {
2209 			if (set_cache_dir(root, what) != 0)
2210 				return (BAM_ERROR);
2211 
2212 			set_dir_present(what);
2213 
2214 			if (set_update_dir(root, what) != 0)
2215 				return (BAM_ERROR);
2216 			what++;
2217 		} while (bam_direct == BAM_DIRECT_DBOOT && what < CACHEDIR_NUM);
2218 	}
2219 
2220 	/*
2221 	 * if force, create archive unconditionally
2222 	 */
2223 	if (bam_force) {
2224 		if (!is_sparc())
2225 			set_dir_flag(FILE32, NEED_UPDATE);
2226 		set_dir_flag(FILE64, NEED_UPDATE);
2227 		if (bam_verbose)
2228 			bam_print(UPDATE_FORCE);
2229 		return (BAM_SUCCESS);
2230 	}
2231 
2232 	return (BAM_SUCCESS);
2233 }
2234 
2235 static error_t
2236 read_one_list(char *root, filelist_t  *flistp, char *filelist)
2237 {
2238 	char 		path[PATH_MAX];
2239 	FILE 		*fp;
2240 	char 		buf[BAM_MAXLINE];
2241 	const char 	*fcn = "read_one_list()";
2242 
2243 	(void) snprintf(path, sizeof (path), "%s%s", root, filelist);
2244 
2245 	fp = fopen(path, "r");
2246 	if (fp == NULL) {
2247 		BAM_DPRINTF((D_FLIST_FAIL, fcn, path, strerror(errno)));
2248 		return (BAM_ERROR);
2249 	}
2250 	while (s_fgets(buf, sizeof (buf), fp) != NULL) {
2251 		/* skip blank lines */
2252 		if (strspn(buf, " \t") == strlen(buf))
2253 			continue;
2254 		append_to_flist(flistp, buf);
2255 	}
2256 	if (fclose(fp) != 0) {
2257 		bam_error(CLOSE_FAIL, path, strerror(errno));
2258 		return (BAM_ERROR);
2259 	}
2260 	return (BAM_SUCCESS);
2261 }
2262 
2263 static error_t
2264 read_list(char *root, filelist_t  *flistp)
2265 {
2266 	char 		path[PATH_MAX];
2267 	char 		cmd[PATH_MAX];
2268 	struct stat 	sb;
2269 	int 		n, rval;
2270 	const char 	*fcn = "read_list()";
2271 
2272 	flistp->head = flistp->tail = NULL;
2273 
2274 	/*
2275 	 * build and check path to extract_boot_filelist.ksh
2276 	 */
2277 	n = snprintf(path, sizeof (path), "%s%s", root, EXTRACT_BOOT_FILELIST);
2278 	if (n >= sizeof (path)) {
2279 		bam_error(NO_FLIST);
2280 		return (BAM_ERROR);
2281 	}
2282 
2283 	if (is_safe_exec(path) == BAM_ERROR)
2284 		return (BAM_ERROR);
2285 
2286 	/*
2287 	 * If extract_boot_filelist is present, exec it, otherwise read
2288 	 * the filelists directly, for compatibility with older images.
2289 	 */
2290 	if (stat(path, &sb) == 0) {
2291 		/*
2292 		 * build arguments to exec extract_boot_filelist.ksh
2293 		 */
2294 		char *rootarg, *platarg;
2295 		int platarglen = 1, rootarglen = 1;
2296 		if (strlen(root) > 1)
2297 			rootarglen += strlen(root) + strlen("-R ");
2298 		if (bam_alt_platform)
2299 			platarglen += strlen(bam_platform) + strlen("-p ");
2300 		platarg = s_calloc(1, platarglen);
2301 		rootarg = s_calloc(1, rootarglen);
2302 		*platarg = 0;
2303 		*rootarg = 0;
2304 
2305 		if (strlen(root) > 1) {
2306 			(void) snprintf(rootarg, rootarglen,
2307 			    "-R %s", root);
2308 		}
2309 		if (bam_alt_platform) {
2310 			(void) snprintf(platarg, platarglen,
2311 			    "-p %s", bam_platform);
2312 		}
2313 		n = snprintf(cmd, sizeof (cmd), "%s %s %s /%s /%s",
2314 		    path, rootarg, platarg, BOOT_FILE_LIST, ETC_FILE_LIST);
2315 		free(platarg);
2316 		free(rootarg);
2317 		if (n >= sizeof (cmd)) {
2318 			bam_error(NO_FLIST);
2319 			return (BAM_ERROR);
2320 		}
2321 		if (exec_cmd(cmd, flistp) != 0) {
2322 			BAM_DPRINTF((D_FLIST_FAIL, fcn, path, strerror(errno)));
2323 			return (BAM_ERROR);
2324 		}
2325 	} else {
2326 		/*
2327 		 * Read current lists of files - only the first is mandatory
2328 		 */
2329 		rval = read_one_list(root, flistp, BOOT_FILE_LIST);
2330 		if (rval != BAM_SUCCESS)
2331 			return (rval);
2332 		(void) read_one_list(root, flistp, ETC_FILE_LIST);
2333 	}
2334 
2335 	if (flistp->head == NULL) {
2336 		bam_error(NO_FLIST);
2337 		return (BAM_ERROR);
2338 	}
2339 
2340 	return (BAM_SUCCESS);
2341 }
2342 
2343 static void
2344 getoldstat(char *root)
2345 {
2346 	char 		path[PATH_MAX];
2347 	int 		fd, error;
2348 	struct stat 	sb;
2349 	char 		*ostat;
2350 
2351 	(void) snprintf(path, sizeof (path), "%s%s", root, FILE_STAT);
2352 	fd = open(path, O_RDONLY);
2353 	if (fd == -1) {
2354 		if (bam_verbose)
2355 			bam_print(OPEN_FAIL, path, strerror(errno));
2356 		goto out_err;
2357 	}
2358 
2359 	if (fstat(fd, &sb) != 0) {
2360 		bam_error(STAT_FAIL, path, strerror(errno));
2361 		goto out_err;
2362 	}
2363 
2364 	ostat = s_calloc(1, sb.st_size);
2365 
2366 	if (read(fd, ostat, sb.st_size) != sb.st_size) {
2367 		bam_error(READ_FAIL, path, strerror(errno));
2368 		free(ostat);
2369 		goto out_err;
2370 	}
2371 
2372 	(void) close(fd);
2373 	fd = -1;
2374 
2375 	walk_arg.old_nvlp = NULL;
2376 	error = nvlist_unpack(ostat, sb.st_size, &walk_arg.old_nvlp, 0);
2377 
2378 	free(ostat);
2379 
2380 	if (error) {
2381 		bam_error(UNPACK_FAIL, path, strerror(error));
2382 		walk_arg.old_nvlp = NULL;
2383 		goto out_err;
2384 	} else {
2385 		return;
2386 	}
2387 
2388 out_err:
2389 	if (fd != -1)
2390 		(void) close(fd);
2391 	if (!is_flag_on(IS_SPARC_TARGET))
2392 		set_dir_flag(FILE32, NEED_UPDATE);
2393 	set_dir_flag(FILE64, NEED_UPDATE);
2394 }
2395 
2396 /* Best effort stale entry removal */
2397 static void
2398 delete_stale(char *file, int what)
2399 {
2400 	char		path[PATH_MAX];
2401 	struct stat	sb;
2402 
2403 	(void) snprintf(path, sizeof (path), "%s/%s", get_cachedir(what), file);
2404 	if (!bam_check && stat(path, &sb) == 0) {
2405 		if (sb.st_mode & S_IFDIR)
2406 			(void) rmdir_r(path);
2407 		else
2408 			(void) unlink(path);
2409 
2410 		set_dir_flag(what, (NEED_UPDATE | NO_MULTI));
2411 	}
2412 }
2413 
2414 /*
2415  * Checks if a file in the current (old) archive has
2416  * been deleted from the root filesystem. This is needed for
2417  * software like Trusted Extensions (TX) that switch early
2418  * in boot based on presence/absence of a kernel module.
2419  */
2420 static void
2421 check4stale(char *root)
2422 {
2423 	nvpair_t	*nvp;
2424 	nvlist_t	*nvlp;
2425 	char 		*file;
2426 	char		path[PATH_MAX];
2427 
2428 	/*
2429 	 * Skip stale file check during smf check
2430 	 */
2431 	if (bam_smf_check)
2432 		return;
2433 
2434 	/*
2435 	 * If we need to (re)create the cache, there's no need to check for
2436 	 * stale files
2437 	 */
2438 	if (is_flag_on(NEED_CACHE_DIR))
2439 		return;
2440 
2441 	/* Nothing to do if no old stats */
2442 	if ((nvlp = walk_arg.old_nvlp) == NULL)
2443 		return;
2444 
2445 	for (nvp = nvlist_next_nvpair(nvlp, NULL); nvp;
2446 	    nvp = nvlist_next_nvpair(nvlp, nvp)) {
2447 		file = nvpair_name(nvp);
2448 		if (file == NULL)
2449 			continue;
2450 		(void) snprintf(path, sizeof (path), "%s/%s",
2451 		    root, file);
2452 		if (access(path, F_OK) < 0) {
2453 			int	what;
2454 
2455 			if (bam_verbose)
2456 				bam_print(PARSEABLE_STALE_FILE, path);
2457 
2458 			if (is_flag_on(IS_SPARC_TARGET)) {
2459 				set_dir_flag(FILE64, NEED_UPDATE);
2460 			} else {
2461 				for (what = FILE32; what < CACHEDIR_NUM; what++)
2462 					if (has_cachedir(what))
2463 						delete_stale(file, what);
2464 			}
2465 		}
2466 	}
2467 }
2468 
2469 static void
2470 create_newstat(void)
2471 {
2472 	int error;
2473 
2474 	error = nvlist_alloc(&walk_arg.new_nvlp, NV_UNIQUE_NAME, 0);
2475 	if (error) {
2476 		/*
2477 		 * Not fatal - we can still create archive
2478 		 */
2479 		walk_arg.new_nvlp = NULL;
2480 		bam_error(NVALLOC_FAIL, strerror(error));
2481 	}
2482 }
2483 
2484 static int
2485 walk_list(char *root, filelist_t *flistp)
2486 {
2487 	char path[PATH_MAX];
2488 	line_t *lp;
2489 
2490 	for (lp = flistp->head; lp; lp = lp->next) {
2491 		/*
2492 		 * Don't follow symlinks.  A symlink must refer to
2493 		 * a file that would appear in the archive through
2494 		 * a direct reference.  This matches the archive
2495 		 * construction behavior.
2496 		 */
2497 		(void) snprintf(path, sizeof (path), "%s%s", root, lp->line);
2498 		if (nftw(path, cmpstat, 20, FTW_PHYS) == -1) {
2499 			if (is_flag_on(UPDATE_ERROR))
2500 				return (BAM_ERROR);
2501 			/*
2502 			 * Some files may not exist.
2503 			 * For example: etc/rtc_config on a x86 diskless system
2504 			 * Emit verbose message only
2505 			 */
2506 			if (bam_verbose)
2507 				bam_print(NFTW_FAIL, path, strerror(errno));
2508 		}
2509 	}
2510 
2511 	return (BAM_SUCCESS);
2512 }
2513 
2514 /*
2515  * Update the timestamp file.
2516  */
2517 static void
2518 update_timestamp(char *root)
2519 {
2520 	char	timestamp_path[PATH_MAX];
2521 
2522 	/* this path length has already been checked in check_flags_and_files */
2523 	(void) snprintf(timestamp_path, sizeof (timestamp_path), "%s%s", root,
2524 	    FILE_STAT_TIMESTAMP);
2525 
2526 	/*
2527 	 * recreate the timestamp file. Since an outdated or absent timestamp
2528 	 * file translates in a complete rebuild of the archive cache, notify
2529 	 * the user of the performance issue.
2530 	 */
2531 	if (creat(timestamp_path, FILE_STAT_MODE) < 0) {
2532 		bam_error(OPEN_FAIL, timestamp_path, strerror(errno));
2533 		bam_error(TIMESTAMP_FAIL, rootbuf);
2534 	}
2535 }
2536 
2537 
2538 static void
2539 savenew(char *root)
2540 {
2541 	char 	path[PATH_MAX];
2542 	char 	path2[PATH_MAX];
2543 	size_t 	sz;
2544 	char 	*nstat;
2545 	int 	fd, wrote, error;
2546 
2547 	nstat = NULL;
2548 	sz = 0;
2549 	error = nvlist_pack(walk_arg.new_nvlp, &nstat, &sz,
2550 	    NV_ENCODE_XDR, 0);
2551 	if (error) {
2552 		bam_error(PACK_FAIL, strerror(error));
2553 		return;
2554 	}
2555 
2556 	(void) snprintf(path, sizeof (path), "%s%s", root, FILE_STAT_TMP);
2557 	fd = open(path, O_RDWR|O_CREAT|O_TRUNC, FILE_STAT_MODE);
2558 	if (fd == -1) {
2559 		bam_error(OPEN_FAIL, path, strerror(errno));
2560 		free(nstat);
2561 		return;
2562 	}
2563 	wrote = write(fd, nstat, sz);
2564 	if (wrote != sz) {
2565 		bam_error(WRITE_FAIL, path, strerror(errno));
2566 		(void) close(fd);
2567 		free(nstat);
2568 		return;
2569 	}
2570 	(void) close(fd);
2571 	free(nstat);
2572 
2573 	(void) snprintf(path2, sizeof (path2), "%s%s", root, FILE_STAT);
2574 	if (rename(path, path2) != 0) {
2575 		bam_error(RENAME_FAIL, path2, strerror(errno));
2576 	}
2577 }
2578 
2579 #define	init_walk_args()	bzero(&walk_arg, sizeof (walk_arg))
2580 
2581 static void
2582 clear_walk_args(void)
2583 {
2584 	if (walk_arg.old_nvlp)
2585 		nvlist_free(walk_arg.old_nvlp);
2586 	if (walk_arg.new_nvlp)
2587 		nvlist_free(walk_arg.new_nvlp);
2588 	if (walk_arg.sparcfile)
2589 		(void) fclose(walk_arg.sparcfile);
2590 	walk_arg.old_nvlp = NULL;
2591 	walk_arg.new_nvlp = NULL;
2592 	walk_arg.sparcfile = NULL;
2593 }
2594 
2595 /*
2596  * Returns:
2597  *	0 - no update necessary
2598  *	1 - update required.
2599  *	BAM_ERROR (-1) - An error occurred
2600  *
2601  * Special handling for check (-n):
2602  * ================================
2603  * The check (-n) option produces parseable output.
2604  * To do this, we suppress all stdout messages unrelated
2605  * to out of sync files.
2606  * All stderr messages are still printed though.
2607  *
2608  */
2609 static int
2610 update_required(char *root)
2611 {
2612 	struct stat 	sb;
2613 	char 		path[PATH_MAX];
2614 	filelist_t 	flist;
2615 	filelist_t 	*flistp = &flist;
2616 	int 		ret;
2617 
2618 	flistp->head = flistp->tail = NULL;
2619 
2620 	if (is_sparc())
2621 		set_flag(IS_SPARC_TARGET);
2622 
2623 	/*
2624 	 * Check if cache directories and archives are present
2625 	 */
2626 
2627 	ret = check_flags_and_files(root);
2628 	if (ret < 0)
2629 		return (BAM_ERROR);
2630 
2631 	/*
2632 	 * In certain deployment scenarios, filestat may not
2633 	 * exist. Ignore it during boot-archive SMF check.
2634 	 */
2635 	if (bam_smf_check) {
2636 		(void) snprintf(path, sizeof (path), "%s%s", root, FILE_STAT);
2637 		if (stat(path, &sb) != 0)
2638 			return (0);
2639 	}
2640 
2641 	getoldstat(root);
2642 
2643 	/*
2644 	 * Check if the archive contains files that are no longer
2645 	 * present on the root filesystem.
2646 	 */
2647 	check4stale(root);
2648 
2649 	/*
2650 	 * read list of files
2651 	 */
2652 	if (read_list(root, flistp) != BAM_SUCCESS) {
2653 		clear_walk_args();
2654 		return (BAM_ERROR);
2655 	}
2656 
2657 	assert(flistp->head && flistp->tail);
2658 
2659 	/*
2660 	 * At this point either the update is required
2661 	 * or the decision is pending. In either case
2662 	 * we need to create new stat nvlist
2663 	 */
2664 	create_newstat();
2665 	/*
2666 	 * This walk does 2 things:
2667 	 *  	- gets new stat data for every file
2668 	 *	- (optional) compare old and new stat data
2669 	 */
2670 	ret = walk_list(root, &flist);
2671 
2672 	/* done with the file list */
2673 	filelist_free(flistp);
2674 
2675 	/* something went wrong */
2676 
2677 	if (ret == BAM_ERROR) {
2678 		bam_error(CACHE_FAIL);
2679 		return (BAM_ERROR);
2680 	}
2681 
2682 	if (walk_arg.new_nvlp == NULL) {
2683 		if (walk_arg.sparcfile != NULL)
2684 			(void) fclose(walk_arg.sparcfile);
2685 		bam_error(NO_NEW_STAT);
2686 	}
2687 
2688 	/* If nothing was updated, discard newstat. */
2689 
2690 	if (!is_dir_flag_on(FILE32, NEED_UPDATE) &&
2691 	    !is_dir_flag_on(FILE64, NEED_UPDATE)) {
2692 		clear_walk_args();
2693 		return (0);
2694 	}
2695 
2696 	if (walk_arg.sparcfile != NULL)
2697 		(void) fclose(walk_arg.sparcfile);
2698 
2699 	return (1);
2700 }
2701 
2702 static int
2703 flushfs(char *root)
2704 {
2705 	char	cmd[PATH_MAX + 30];
2706 
2707 	(void) snprintf(cmd, sizeof (cmd), "%s -f \"%s\" 2>/dev/null",
2708 	    LOCKFS_PATH, root);
2709 
2710 	return (exec_cmd(cmd, NULL));
2711 }
2712 
2713 static int
2714 do_archive_copy(char *source, char *dest)
2715 {
2716 
2717 	sync();
2718 
2719 	/* the equivalent of mv archive-new-$pid boot_archive */
2720 	if (rename(source, dest) != 0) {
2721 		(void) unlink(source);
2722 		return (BAM_ERROR);
2723 	}
2724 
2725 	if (flushfs(bam_root) != 0)
2726 		sync();
2727 
2728 	return (BAM_SUCCESS);
2729 }
2730 
2731 static int
2732 check_cmdline(filelist_t flist)
2733 {
2734 	line_t	*lp;
2735 
2736 	for (lp = flist.head; lp; lp = lp->next) {
2737 		if (strstr(lp->line, "Error:") != NULL ||
2738 		    strstr(lp->line, "Inode number overflow") != NULL) {
2739 			(void) fprintf(stderr, "%s\n", lp->line);
2740 			return (BAM_ERROR);
2741 		}
2742 	}
2743 
2744 	return (BAM_SUCCESS);
2745 }
2746 
2747 static void
2748 dump_errormsg(filelist_t flist)
2749 {
2750 	line_t	*lp;
2751 
2752 	for (lp = flist.head; lp; lp = lp->next)
2753 		(void) fprintf(stderr, "%s\n", lp->line);
2754 }
2755 
2756 static int
2757 check_archive(char *dest)
2758 {
2759 	struct stat	sb;
2760 
2761 	if (stat(dest, &sb) != 0 || !S_ISREG(sb.st_mode) ||
2762 	    sb.st_size < 10000) {
2763 		bam_error(ARCHIVE_BAD, dest);
2764 		(void) unlink(dest);
2765 		return (BAM_ERROR);
2766 	}
2767 
2768 	return (BAM_SUCCESS);
2769 }
2770 
2771 /*
2772  * Returns 1 if mkiso is in the expected PATH, 0 otherwise
2773  */
2774 static int
2775 is_mkisofs()
2776 {
2777 	if (access(MKISOFS_PATH, X_OK) == 0)
2778 		return (1);
2779 	return (0);
2780 }
2781 
2782 #define	MKISO_PARAMS	" -quiet -graft-points -dlrDJN -relaxed-filenames "
2783 
2784 static int
2785 create_sparc_archive(char *archive, char *tempname, char *bootblk, char *list)
2786 {
2787 	int		ret;
2788 	char		cmdline[3 * PATH_MAX + 64];
2789 	filelist_t	flist = {0};
2790 	const char	*func = "create_sparc_archive()";
2791 
2792 	if (access(bootblk, R_OK) == 1) {
2793 		bam_error(BOOTBLK_FAIL, bootblk);
2794 		return (BAM_ERROR);
2795 	}
2796 
2797 	/*
2798 	 * Prepare mkisofs command line and execute it
2799 	 */
2800 	(void) snprintf(cmdline, sizeof (cmdline), "%s %s -G %s -o \"%s\" "
2801 	    "-path-list \"%s\" 2>&1", MKISOFS_PATH, MKISO_PARAMS, bootblk,
2802 	    tempname, list);
2803 
2804 	BAM_DPRINTF((D_CMDLINE, func, cmdline));
2805 
2806 	ret = exec_cmd(cmdline, &flist);
2807 	if (ret != 0 || check_cmdline(flist) == BAM_ERROR) {
2808 		dump_errormsg(flist);
2809 		goto out_err;
2810 	}
2811 
2812 	filelist_free(&flist);
2813 
2814 	/*
2815 	 * Prepare dd command line to copy the bootblk on the new archive and
2816 	 * execute it
2817 	 */
2818 	(void) snprintf(cmdline, sizeof (cmdline), "%s if=\"%s\" of=\"%s\""
2819 	    " bs=1b oseek=1 count=15 conv=notrunc conv=sync 2>&1", DD_PATH_USR,
2820 	    bootblk, tempname);
2821 
2822 	BAM_DPRINTF((D_CMDLINE, func, cmdline));
2823 
2824 	ret = exec_cmd(cmdline, &flist);
2825 	if (ret != 0 || check_cmdline(flist) == BAM_ERROR)
2826 		goto out_err;
2827 
2828 	filelist_free(&flist);
2829 
2830 	/* Did we get a valid archive ? */
2831 	if (check_archive(tempname) == BAM_ERROR)
2832 		return (BAM_ERROR);
2833 
2834 	return (do_archive_copy(tempname, archive));
2835 
2836 out_err:
2837 	filelist_free(&flist);
2838 	bam_error(ARCHIVE_FAIL, cmdline);
2839 	(void) unlink(tempname);
2840 	return (BAM_ERROR);
2841 }
2842 
2843 static unsigned int
2844 from_733(unsigned char *s)
2845 {
2846 	int		i;
2847 	unsigned int	ret = 0;
2848 
2849 	for (i = 0; i < 4; i++)
2850 		ret |= s[i] << (8 * i);
2851 
2852 	return (ret);
2853 }
2854 
2855 static void
2856 to_733(unsigned char *s, unsigned int val)
2857 {
2858 	int	i;
2859 
2860 	for (i = 0; i < 4; i++)
2861 		s[i] = s[7-i] = (val >> (8 * i)) & 0xFF;
2862 }
2863 
2864 /*
2865  * Extends the current boot archive without recreating it from scratch
2866  */
2867 static int
2868 extend_iso_archive(char *archive, char *tempname, char *update_dir)
2869 {
2870 	int			fd = -1, newfd = -1, ret, i;
2871 	int			next_session = 0, new_size = 0;
2872 	char			cmdline[3 * PATH_MAX + 64];
2873 	const char		*func = "extend_iso_archive()";
2874 	filelist_t		flist = {0};
2875 	struct iso_pdesc	saved_desc[MAX_IVDs];
2876 
2877 	fd = open(archive, O_RDWR);
2878 	if (fd == -1) {
2879 		if (bam_verbose)
2880 			bam_error(OPEN_FAIL, archive, strerror(errno));
2881 		goto out_err;
2882 	}
2883 
2884 	/*
2885 	 * A partial read is likely due to a corrupted file
2886 	 */
2887 	ret = pread64(fd, saved_desc, sizeof (saved_desc),
2888 	    VOLDESC_OFF * CD_BLOCK);
2889 	if (ret != sizeof (saved_desc)) {
2890 		if (bam_verbose)
2891 			bam_error(READ_FAIL, archive, strerror(errno));
2892 		goto out_err;
2893 	}
2894 
2895 	if (memcmp(saved_desc[0].type, "\1CD001", 6)) {
2896 		if (bam_verbose)
2897 			bam_error(SIGN_FAIL, archive);
2898 		goto out_err;
2899 	}
2900 
2901 	/*
2902 	 * Read primary descriptor and locate next_session offset (it should
2903 	 * point to the end of the archive)
2904 	 */
2905 	next_session = P2ROUNDUP(from_733(saved_desc[0].volume_space_size), 16);
2906 
2907 	(void) snprintf(cmdline, sizeof (cmdline), "%s -C 16,%d -M %s %s -o \""
2908 	    "%s\" \"%s\" 2>&1", MKISOFS_PATH, next_session, archive,
2909 	    MKISO_PARAMS, tempname, update_dir);
2910 
2911 	BAM_DPRINTF((D_CMDLINE, func, cmdline));
2912 
2913 	ret = exec_cmd(cmdline, &flist);
2914 	if (ret != 0 || check_cmdline(flist) == BAM_ERROR) {
2915 		if (bam_verbose) {
2916 			bam_error(MULTI_FAIL, cmdline);
2917 			dump_errormsg(flist);
2918 		}
2919 		goto out_flist_err;
2920 	}
2921 	filelist_free(&flist);
2922 
2923 	newfd = open(tempname, O_RDONLY);
2924 	if (newfd == -1) {
2925 		if (bam_verbose)
2926 			bam_error(OPEN_FAIL, archive, strerror(errno));
2927 		goto out_err;
2928 	}
2929 
2930 	ret = pread64(newfd, saved_desc, sizeof (saved_desc),
2931 	    VOLDESC_OFF * CD_BLOCK);
2932 	if (ret != sizeof (saved_desc)) {
2933 		if (bam_verbose)
2934 			bam_error(READ_FAIL, archive, strerror(errno));
2935 		goto out_err;
2936 	}
2937 
2938 	if (memcmp(saved_desc[0].type, "\1CD001", 6)) {
2939 		if (bam_verbose)
2940 			bam_error(SIGN_FAIL, archive);
2941 		goto out_err;
2942 	}
2943 
2944 	new_size = from_733(saved_desc[0].volume_space_size) + next_session;
2945 	to_733(saved_desc[0].volume_space_size, new_size);
2946 
2947 	for (i = 1; i < MAX_IVDs; i++) {
2948 		if (saved_desc[i].type[0] == (unsigned char)255)
2949 			break;
2950 		if (memcmp(saved_desc[i].id, "CD001", 5))
2951 			break;
2952 
2953 		if (bam_verbose)
2954 			bam_print("%s: Updating descriptor entry [%d]\n", func,
2955 			    i);
2956 
2957 		to_733(saved_desc[i].volume_space_size, new_size);
2958 	}
2959 
2960 	ret = pwrite64(fd, saved_desc, DVD_BLOCK, VOLDESC_OFF*CD_BLOCK);
2961 	if (ret != DVD_BLOCK) {
2962 		if (bam_verbose)
2963 			bam_error(WRITE_FAIL, archive, strerror(errno));
2964 		goto out_err;
2965 	}
2966 	(void) close(newfd);
2967 	newfd = -1;
2968 
2969 	ret = fsync(fd);
2970 	if (ret != 0)
2971 		sync();
2972 
2973 	ret = close(fd);
2974 	if (ret != 0) {
2975 		if (bam_verbose)
2976 			bam_error(CLOSE_FAIL, archive, strerror(errno));
2977 		return (BAM_ERROR);
2978 	}
2979 	fd = -1;
2980 
2981 	(void) snprintf(cmdline, sizeof (cmdline), "%s if=%s of=%s bs=32k "
2982 	    "seek=%d conv=sync 2>&1", DD_PATH_USR, tempname, archive,
2983 	    (next_session/16));
2984 
2985 	BAM_DPRINTF((D_CMDLINE, func, cmdline));
2986 
2987 	ret = exec_cmd(cmdline, &flist);
2988 	if (ret != 0 || check_cmdline(flist) == BAM_ERROR) {
2989 		if (bam_verbose)
2990 			bam_error(MULTI_FAIL, cmdline);
2991 		goto out_flist_err;
2992 	}
2993 	filelist_free(&flist);
2994 
2995 	(void) unlink(tempname);
2996 
2997 	if (flushfs(bam_root) != 0)
2998 		sync();
2999 
3000 	if (bam_verbose)
3001 		bam_print("boot archive updated successfully\n");
3002 
3003 	return (BAM_SUCCESS);
3004 
3005 out_flist_err:
3006 	filelist_free(&flist);
3007 out_err:
3008 	if (fd != -1)
3009 		(void) close(fd);
3010 	if (newfd != -1)
3011 		(void) close(newfd);
3012 	return (BAM_ERROR);
3013 }
3014 
3015 static int
3016 create_x86_archive(char *archive, char *tempname, char *update_dir)
3017 {
3018 	int		ret;
3019 	char		cmdline[3 * PATH_MAX + 64];
3020 	filelist_t	flist = {0};
3021 	const char	*func = "create_x86_archive()";
3022 
3023 	(void) snprintf(cmdline, sizeof (cmdline), "%s %s -o \"%s\" \"%s\" "
3024 	    "2>&1", MKISOFS_PATH, MKISO_PARAMS, tempname, update_dir);
3025 
3026 	BAM_DPRINTF((D_CMDLINE, func, cmdline));
3027 
3028 	ret = exec_cmd(cmdline, &flist);
3029 	if (ret != 0 || check_cmdline(flist) == BAM_ERROR) {
3030 		bam_error(ARCHIVE_FAIL, cmdline);
3031 		dump_errormsg(flist);
3032 		filelist_free(&flist);
3033 		(void) unlink(tempname);
3034 		return (BAM_ERROR);
3035 	}
3036 
3037 	filelist_free(&flist);
3038 
3039 	if (check_archive(tempname) == BAM_ERROR)
3040 		return (BAM_ERROR);
3041 
3042 	return (do_archive_copy(tempname, archive));
3043 }
3044 
3045 static int
3046 mkisofs_archive(char *root, int what)
3047 {
3048 	int		ret;
3049 	char		temp[PATH_MAX];
3050 	char 		bootblk[PATH_MAX];
3051 	char		boot_archive[PATH_MAX];
3052 
3053 	if (what == FILE64 && !is_flag_on(IS_SPARC_TARGET))
3054 		ret = snprintf(temp, sizeof (temp),
3055 		    "%s%s%s/amd64/archive-new-%d", root, ARCHIVE_PREFIX,
3056 		    get_machine(), getpid());
3057 	else
3058 		ret = snprintf(temp, sizeof (temp), "%s%s%s/archive-new-%d",
3059 		    root, ARCHIVE_PREFIX, get_machine(), getpid());
3060 
3061 	if (ret >= sizeof (temp))
3062 		goto out_path_err;
3063 
3064 	if (what == FILE64 && !is_flag_on(IS_SPARC_TARGET))
3065 		ret = snprintf(boot_archive, sizeof (boot_archive),
3066 		    "%s%s%s/amd64%s", root, ARCHIVE_PREFIX, get_machine(),
3067 		    ARCHIVE_SUFFIX);
3068 	else
3069 		ret = snprintf(boot_archive, sizeof (boot_archive),
3070 		    "%s%s%s%s", root, ARCHIVE_PREFIX, get_machine(),
3071 		    ARCHIVE_SUFFIX);
3072 
3073 	if (ret >= sizeof (boot_archive))
3074 		goto out_path_err;
3075 
3076 	bam_print("updating %s\n", boot_archive);
3077 
3078 	if (is_flag_on(IS_SPARC_TARGET)) {
3079 		ret = snprintf(bootblk, sizeof (bootblk),
3080 		    "%s/platform/%s/lib/fs/hsfs/bootblk", root, get_machine());
3081 		if (ret >= sizeof (bootblk))
3082 			goto out_path_err;
3083 
3084 		ret = create_sparc_archive(boot_archive, temp, bootblk,
3085 		    get_cachedir(what));
3086 	} else {
3087 		if (!is_dir_flag_on(what, NO_MULTI)) {
3088 			if (bam_verbose)
3089 				bam_print("Attempting to extend x86 archive: "
3090 				    "%s\n", boot_archive);
3091 
3092 			ret = extend_iso_archive(boot_archive, temp,
3093 			    get_updatedir(what));
3094 			if (ret == BAM_SUCCESS) {
3095 				if (bam_verbose)
3096 					bam_print("Successfully extended %s\n",
3097 					    boot_archive);
3098 
3099 				(void) rmdir_r(get_updatedir(what));
3100 				return (BAM_SUCCESS);
3101 			}
3102 		}
3103 		/*
3104 		 * The boot archive will be recreated from scratch. We get here
3105 		 * if at least one of these conditions is true:
3106 		 * - bootadm was called without the -e switch
3107 		 * - the archive (or the archive cache) doesn't exist
3108 		 * - archive size is bigger than BA_SIZE_MAX
3109 		 * - more than COUNT_MAX files need to be updated
3110 		 * - an error occourred either populating the /updates directory
3111 		 *   or extend_iso_archive() failed
3112 		 */
3113 		if (bam_verbose)
3114 			bam_print("Unable to extend %s... rebuilding archive\n",
3115 			    boot_archive);
3116 
3117 		if (get_updatedir(what)[0] != '\0')
3118 			(void) rmdir_r(get_updatedir(what));
3119 
3120 
3121 		ret = create_x86_archive(boot_archive, temp,
3122 		    get_cachedir(what));
3123 	}
3124 
3125 	if (ret == BAM_SUCCESS && bam_verbose)
3126 		bam_print("Successfully created %s\n", boot_archive);
3127 
3128 	return (ret);
3129 
3130 out_path_err:
3131 	bam_error(PATH_TOO_LONG, root);
3132 	return (BAM_ERROR);
3133 }
3134 
3135 static error_t
3136 create_ramdisk(char *root)
3137 {
3138 	char *cmdline, path[PATH_MAX];
3139 	size_t len;
3140 	struct stat sb;
3141 	int ret, what, status = BAM_SUCCESS;
3142 
3143 	/* If there is mkisofs, use it to create the required archives */
3144 	if (is_mkisofs()) {
3145 		for (what = FILE32; what < CACHEDIR_NUM; what++) {
3146 			if (has_cachedir(what) && is_dir_flag_on(what,
3147 			    NEED_UPDATE)) {
3148 				ret = mkisofs_archive(root, what);
3149 				if (ret != 0)
3150 					status = BAM_ERROR;
3151 			}
3152 		}
3153 		return (status);
3154 	}
3155 
3156 	/*
3157 	 * Else setup command args for create_ramdisk.ksh for the UFS archives
3158 	 */
3159 	if (bam_verbose)
3160 		bam_print("mkisofs not found, creating UFS archive\n");
3161 
3162 	(void) snprintf(path, sizeof (path), "%s/%s", root, CREATE_RAMDISK);
3163 	if (stat(path, &sb) != 0) {
3164 		bam_error(ARCH_EXEC_MISS, path, strerror(errno));
3165 		return (BAM_ERROR);
3166 	}
3167 
3168 	if (is_safe_exec(path) == BAM_ERROR)
3169 		return (BAM_ERROR);
3170 
3171 	len = strlen(path) + strlen(root) + 10;	/* room for space + -R */
3172 	if (bam_alt_platform)
3173 		len += strlen(bam_platform) + strlen("-p ");
3174 	cmdline = s_calloc(1, len);
3175 
3176 	if (bam_alt_platform) {
3177 		assert(strlen(root) > 1);
3178 		(void) snprintf(cmdline, len, "%s -p %s -R %s",
3179 		    path, bam_platform, root);
3180 		/* chop off / at the end */
3181 		cmdline[strlen(cmdline) - 1] = '\0';
3182 	} else if (strlen(root) > 1) {
3183 		(void) snprintf(cmdline, len, "%s -R %s", path, root);
3184 		/* chop off / at the end */
3185 		cmdline[strlen(cmdline) - 1] = '\0';
3186 	} else
3187 		(void) snprintf(cmdline, len, "%s", path);
3188 
3189 	if (exec_cmd(cmdline, NULL) != 0) {
3190 		bam_error(ARCHIVE_FAIL, cmdline);
3191 		free(cmdline);
3192 		return (BAM_ERROR);
3193 	}
3194 	free(cmdline);
3195 	/*
3196 	 * The existence of the expected archives used to be
3197 	 * verified here. This check is done in create_ramdisk as
3198 	 * it needs to be in sync with the altroot operated upon.
3199 	 */
3200 	return (BAM_SUCCESS);
3201 }
3202 
3203 /*
3204  * Checks if target filesystem is on a ramdisk
3205  * 1 - is miniroot
3206  * 0 - is not
3207  * When in doubt assume it is not a ramdisk.
3208  */
3209 static int
3210 is_ramdisk(char *root)
3211 {
3212 	struct extmnttab mnt;
3213 	FILE *fp;
3214 	int found;
3215 	char mntpt[PATH_MAX];
3216 	char *cp;
3217 
3218 	/*
3219 	 * There are 3 situations where creating archive is
3220 	 * of dubious value:
3221 	 *	- create boot_archive on a lofi-mounted boot_archive
3222 	 *	- create it on a ramdisk which is the root filesystem
3223 	 *	- create it on a ramdisk mounted somewhere else
3224 	 * The first is not easy to detect and checking for it is not
3225 	 * worth it.
3226 	 * The other two conditions are handled here
3227 	 */
3228 	fp = fopen(MNTTAB, "r");
3229 	if (fp == NULL) {
3230 		bam_error(OPEN_FAIL, MNTTAB, strerror(errno));
3231 		return (0);
3232 	}
3233 
3234 	resetmnttab(fp);
3235 
3236 	/*
3237 	 * Remove any trailing / from the mount point
3238 	 */
3239 	(void) strlcpy(mntpt, root, sizeof (mntpt));
3240 	if (strcmp(root, "/") != 0) {
3241 		cp = mntpt + strlen(mntpt) - 1;
3242 		if (*cp == '/')
3243 			*cp = '\0';
3244 	}
3245 	found = 0;
3246 	while (getextmntent(fp, &mnt, sizeof (mnt)) == 0) {
3247 		if (strcmp(mnt.mnt_mountp, mntpt) == 0) {
3248 			found = 1;
3249 			break;
3250 		}
3251 	}
3252 
3253 	if (!found) {
3254 		if (bam_verbose)
3255 			bam_error(NOT_IN_MNTTAB, mntpt);
3256 		(void) fclose(fp);
3257 		return (0);
3258 	}
3259 
3260 	if (strstr(mnt.mnt_special, RAMDISK_SPECIAL) != NULL) {
3261 		if (bam_verbose)
3262 			bam_error(IS_RAMDISK, bam_root);
3263 		(void) fclose(fp);
3264 		return (1);
3265 	}
3266 
3267 	(void) fclose(fp);
3268 
3269 	return (0);
3270 }
3271 
3272 static int
3273 is_boot_archive(char *root)
3274 {
3275 	char		path[PATH_MAX];
3276 	struct stat	sb;
3277 	int		error;
3278 	const char	*fcn = "is_boot_archive()";
3279 
3280 	/*
3281 	 * We can't create an archive without the create_ramdisk script
3282 	 */
3283 	(void) snprintf(path, sizeof (path), "%s/%s", root, CREATE_RAMDISK);
3284 	error = stat(path, &sb);
3285 	INJECT_ERROR1("NOT_ARCHIVE_BASED", error = -1);
3286 	if (error == -1) {
3287 		if (bam_verbose)
3288 			bam_print(FILE_MISS, path);
3289 		BAM_DPRINTF((D_NOT_ARCHIVE_BOOT, fcn, root));
3290 		return (0);
3291 	}
3292 
3293 	BAM_DPRINTF((D_IS_ARCHIVE_BOOT, fcn, root));
3294 	return (1);
3295 }
3296 
3297 /*
3298  * Need to call this for anything that operates on the GRUB menu
3299  * In the x86 live upgrade case the directory /boot/grub may be present
3300  * even on pre-newboot BEs. The authoritative way to check for a GRUB target
3301  * is to check for the presence of the stage2 binary which is present
3302  * only on GRUB targets (even on x86 boot partitions). Checking for the
3303  * presence of the multiboot binary is not correct as it is not present
3304  * on x86 boot partitions.
3305  */
3306 int
3307 is_grub(const char *root)
3308 {
3309 	char path[PATH_MAX];
3310 	struct stat sb;
3311 	const char *fcn = "is_grub()";
3312 
3313 	(void) snprintf(path, sizeof (path), "%s%s", root, GRUB_STAGE2);
3314 	if (stat(path, &sb) == -1) {
3315 		BAM_DPRINTF((D_NO_GRUB_DIR, fcn, path));
3316 		return (0);
3317 	}
3318 
3319 	return (1);
3320 }
3321 
3322 static int
3323 is_zfs(char *root)
3324 {
3325 	struct statvfs		vfs;
3326 	int			ret;
3327 	const char		*fcn = "is_zfs()";
3328 
3329 	ret = statvfs(root, &vfs);
3330 	INJECT_ERROR1("STATVFS_ZFS", ret = 1);
3331 	if (ret != 0) {
3332 		bam_error(STATVFS_FAIL, root, strerror(errno));
3333 		return (0);
3334 	}
3335 
3336 	if (strncmp(vfs.f_basetype, "zfs", strlen("zfs")) == 0) {
3337 		BAM_DPRINTF((D_IS_ZFS, fcn, root));
3338 		return (1);
3339 	} else {
3340 		BAM_DPRINTF((D_IS_NOT_ZFS, fcn, root));
3341 		return (0);
3342 	}
3343 }
3344 
3345 static int
3346 is_ufs(char *root)
3347 {
3348 	struct statvfs		vfs;
3349 	int			ret;
3350 	const char		*fcn = "is_ufs()";
3351 
3352 	ret = statvfs(root, &vfs);
3353 	INJECT_ERROR1("STATVFS_UFS", ret = 1);
3354 	if (ret != 0) {
3355 		bam_error(STATVFS_FAIL, root, strerror(errno));
3356 		return (0);
3357 	}
3358 
3359 	if (strncmp(vfs.f_basetype, "ufs", strlen("ufs")) == 0) {
3360 		BAM_DPRINTF((D_IS_UFS, fcn, root));
3361 		return (1);
3362 	} else {
3363 		BAM_DPRINTF((D_IS_NOT_UFS, fcn, root));
3364 		return (0);
3365 	}
3366 }
3367 
3368 static int
3369 is_pcfs(char *root)
3370 {
3371 	struct statvfs		vfs;
3372 	int			ret;
3373 	const char		*fcn = "is_pcfs()";
3374 
3375 	ret = statvfs(root, &vfs);
3376 	INJECT_ERROR1("STATVFS_PCFS", ret = 1);
3377 	if (ret != 0) {
3378 		bam_error(STATVFS_FAIL, root, strerror(errno));
3379 		return (0);
3380 	}
3381 
3382 	if (strncmp(vfs.f_basetype, "pcfs", strlen("pcfs")) == 0) {
3383 		BAM_DPRINTF((D_IS_PCFS, fcn, root));
3384 		return (1);
3385 	} else {
3386 		BAM_DPRINTF((D_IS_NOT_PCFS, fcn, root));
3387 		return (0);
3388 	}
3389 }
3390 
3391 static int
3392 is_readonly(char *root)
3393 {
3394 	int		fd;
3395 	int		error;
3396 	char		testfile[PATH_MAX];
3397 	const char	*fcn = "is_readonly()";
3398 
3399 	/*
3400 	 * Using statvfs() to check for a read-only filesystem is not
3401 	 * reliable. The only way to reliably test is to attempt to
3402 	 * create a file
3403 	 */
3404 	(void) snprintf(testfile, sizeof (testfile), "%s/%s.%d",
3405 	    root, BOOTADM_RDONLY_TEST, getpid());
3406 
3407 	(void) unlink(testfile);
3408 
3409 	errno = 0;
3410 	fd = open(testfile, O_RDWR|O_CREAT|O_EXCL, 0644);
3411 	error = errno;
3412 	INJECT_ERROR2("RDONLY_TEST_ERROR", fd = -1, error = EACCES);
3413 	if (fd == -1 && error == EROFS) {
3414 		BAM_DPRINTF((D_RDONLY_FS, fcn, root));
3415 		return (1);
3416 	} else if (fd == -1) {
3417 		bam_error(RDONLY_TEST_ERROR, root, strerror(error));
3418 	}
3419 
3420 	(void) close(fd);
3421 	(void) unlink(testfile);
3422 
3423 	BAM_DPRINTF((D_RDWR_FS, fcn, root));
3424 	return (0);
3425 }
3426 
3427 static error_t
3428 update_archive(char *root, char *opt)
3429 {
3430 	error_t ret;
3431 
3432 	assert(root);
3433 	assert(opt == NULL);
3434 
3435 	init_walk_args();
3436 	(void) umask(022);
3437 
3438 	/*
3439 	 * root must belong to a boot archive based OS,
3440 	 */
3441 	if (!is_boot_archive(root)) {
3442 		/*
3443 		 * Emit message only if not in context of update_all.
3444 		 * If in update_all, emit only if verbose flag is set.
3445 		 */
3446 		if (!bam_update_all || bam_verbose)
3447 			bam_print(NOT_ARCHIVE_BOOT, root);
3448 		return (BAM_ERROR);
3449 	}
3450 
3451 	/*
3452 	 * If smf check is requested when / is writable (can happen
3453 	 * on first reboot following an upgrade because service
3454 	 * dependency is messed up), skip the check.
3455 	 */
3456 	if (bam_smf_check && !bam_root_readonly && !is_zfs(root))
3457 		return (BAM_SUCCESS);
3458 
3459 	/*
3460 	 * Don't generate archive on ramdisk.
3461 	 */
3462 	if (is_ramdisk(root))
3463 		return (BAM_SUCCESS);
3464 
3465 	/*
3466 	 * root must be writable. This check applies to alternate
3467 	 * root (-R option); bam_root_readonly applies to '/' only.
3468 	 * The behaviour translates into being the one of a 'check'.
3469 	 */
3470 	if (!bam_smf_check && !bam_check && is_readonly(root)) {
3471 		set_flag(RDONLY_FSCHK);
3472 		bam_check = 1;
3473 	}
3474 
3475 	/*
3476 	 * Now check if an update is really needed.
3477 	 */
3478 	ret = update_required(root);
3479 
3480 	/*
3481 	 * The check command (-n) is *not* a dry run.
3482 	 * It only checks if the archive is in sync.
3483 	 * A readonly filesystem has to be considered an error only if an update
3484 	 * is required.
3485 	 */
3486 	if (bam_nowrite()) {
3487 		if (is_flag_on(RDONLY_FSCHK)) {
3488 			bam_check = bam_saved_check;
3489 			if (ret > 0)
3490 				bam_error(RDONLY_FS, root);
3491 			if (bam_update_all)
3492 				return ((ret != 0) ? BAM_ERROR : BAM_SUCCESS);
3493 		}
3494 
3495 		bam_exit((ret != 0) ? 1 : 0);
3496 	}
3497 
3498 	if (ret == 1) {
3499 		/* create the ramdisk */
3500 		ret = create_ramdisk(root);
3501 	}
3502 
3503 	/*
3504 	 * if the archive is updated, save the new stat data and update the
3505 	 * timestamp file
3506 	 */
3507 	if (ret == 0 && walk_arg.new_nvlp != NULL) {
3508 		savenew(root);
3509 		update_timestamp(root);
3510 	}
3511 
3512 	clear_walk_args();
3513 
3514 	return (ret);
3515 }
3516 
3517 static error_t
3518 synchronize_BE_menu(void)
3519 {
3520 	struct stat	sb;
3521 	char		cmdline[PATH_MAX];
3522 	char		cksum_line[PATH_MAX];
3523 	filelist_t	flist = {0};
3524 	char		*old_cksum_str;
3525 	char		*old_size_str;
3526 	char		*old_file;
3527 	char		*curr_cksum_str;
3528 	char		*curr_size_str;
3529 	char		*curr_file;
3530 	FILE		*cfp;
3531 	int		found;
3532 	int		ret;
3533 	const char	*fcn = "synchronize_BE_menu()";
3534 
3535 	BAM_DPRINTF((D_FUNC_ENTRY0, fcn));
3536 
3537 	/* Check if findroot enabled LU BE */
3538 	if (stat(FINDROOT_INSTALLGRUB, &sb) != 0) {
3539 		BAM_DPRINTF((D_NOT_LU_BE, fcn));
3540 		return (BAM_SUCCESS);
3541 	}
3542 
3543 	if (stat(LU_MENU_CKSUM, &sb) != 0) {
3544 		BAM_DPRINTF((D_NO_CKSUM_FILE, fcn, LU_MENU_CKSUM));
3545 		goto menu_sync;
3546 	}
3547 
3548 	cfp = fopen(LU_MENU_CKSUM, "r");
3549 	INJECT_ERROR1("CKSUM_FILE_MISSING", cfp = NULL);
3550 	if (cfp == NULL) {
3551 		bam_error(CANNOT_READ_LU_CKSUM, LU_MENU_CKSUM);
3552 		goto menu_sync;
3553 	}
3554 	BAM_DPRINTF((D_CKSUM_FILE_OPENED, fcn, LU_MENU_CKSUM));
3555 
3556 	found = 0;
3557 	while (s_fgets(cksum_line, sizeof (cksum_line), cfp) != NULL) {
3558 		INJECT_ERROR1("MULTIPLE_CKSUM", found = 1);
3559 		if (found) {
3560 			bam_error(MULTIPLE_LU_CKSUM, LU_MENU_CKSUM);
3561 			(void) fclose(cfp);
3562 			goto menu_sync;
3563 		}
3564 		found = 1;
3565 	}
3566 	BAM_DPRINTF((D_CKSUM_FILE_READ, fcn, LU_MENU_CKSUM));
3567 
3568 
3569 	old_cksum_str = strtok(cksum_line, " \t");
3570 	old_size_str = strtok(NULL, " \t");
3571 	old_file = strtok(NULL, " \t");
3572 
3573 	INJECT_ERROR1("OLD_CKSUM_NULL", old_cksum_str = NULL);
3574 	INJECT_ERROR1("OLD_SIZE_NULL", old_size_str = NULL);
3575 	INJECT_ERROR1("OLD_FILE_NULL", old_file = NULL);
3576 	if (old_cksum_str == NULL || old_size_str == NULL || old_file == NULL) {
3577 		bam_error(CANNOT_PARSE_LU_CKSUM, LU_MENU_CKSUM);
3578 		goto menu_sync;
3579 	}
3580 	BAM_DPRINTF((D_CKSUM_FILE_PARSED, fcn, LU_MENU_CKSUM));
3581 
3582 	/* Get checksum of current menu */
3583 	(void) snprintf(cmdline, sizeof (cmdline), "%s %s",
3584 	    CKSUM, GRUB_MENU);
3585 	ret = exec_cmd(cmdline, &flist);
3586 	INJECT_ERROR1("GET_CURR_CKSUM", ret = 1);
3587 	if (ret != 0) {
3588 		bam_error(MENU_CKSUM_FAIL);
3589 		return (BAM_ERROR);
3590 	}
3591 	BAM_DPRINTF((D_CKSUM_GEN_SUCCESS, fcn));
3592 
3593 	INJECT_ERROR1("GET_CURR_CKSUM_OUTPUT", flist.head = NULL);
3594 	if ((flist.head == NULL) || (flist.head != flist.tail)) {
3595 		bam_error(BAD_CKSUM);
3596 		filelist_free(&flist);
3597 		return (BAM_ERROR);
3598 	}
3599 	BAM_DPRINTF((D_CKSUM_GEN_OUTPUT_VALID, fcn));
3600 
3601 	curr_cksum_str = strtok(flist.head->line, " \t");
3602 	curr_size_str = strtok(NULL, " \t");
3603 	curr_file = strtok(NULL, " \t");
3604 
3605 	INJECT_ERROR1("CURR_CKSUM_NULL", curr_cksum_str = NULL);
3606 	INJECT_ERROR1("CURR_SIZE_NULL", curr_size_str = NULL);
3607 	INJECT_ERROR1("CURR_FILE_NULL", curr_file = NULL);
3608 	if (curr_cksum_str == NULL || curr_size_str == NULL ||
3609 	    curr_file == NULL) {
3610 		bam_error(BAD_CKSUM_PARSE);
3611 		filelist_free(&flist);
3612 		return (BAM_ERROR);
3613 	}
3614 	BAM_DPRINTF((D_CKSUM_GEN_PARSED, fcn));
3615 
3616 	if (strcmp(old_cksum_str, curr_cksum_str) == 0 &&
3617 	    strcmp(old_size_str, curr_size_str) == 0 &&
3618 	    strcmp(old_file, curr_file) == 0) {
3619 		filelist_free(&flist);
3620 		BAM_DPRINTF((D_CKSUM_NO_CHANGE, fcn));
3621 		return (BAM_SUCCESS);
3622 	}
3623 
3624 	filelist_free(&flist);
3625 
3626 	/* cksum doesn't match - the menu has changed */
3627 	BAM_DPRINTF((D_CKSUM_HAS_CHANGED, fcn));
3628 
3629 menu_sync:
3630 	bam_print(PROP_GRUB_MENU);
3631 
3632 	(void) snprintf(cmdline, sizeof (cmdline),
3633 	    "/bin/sh -c '. %s > /dev/null; %s %s yes > /dev/null'",
3634 	    LULIB, LULIB_PROPAGATE_FILE, GRUB_MENU);
3635 	ret = exec_cmd(cmdline, NULL);
3636 	INJECT_ERROR1("PROPAGATE_MENU", ret = 1);
3637 	if (ret != 0) {
3638 		bam_error(MENU_PROP_FAIL);
3639 		return (BAM_ERROR);
3640 	}
3641 	BAM_DPRINTF((D_PROPAGATED_MENU, fcn));
3642 
3643 	(void) snprintf(cmdline, sizeof (cmdline), "/bin/cp %s %s > /dev/null",
3644 	    GRUB_MENU, GRUB_BACKUP_MENU);
3645 	ret = exec_cmd(cmdline, NULL);
3646 	INJECT_ERROR1("CREATE_BACKUP", ret = 1);
3647 	if (ret != 0) {
3648 		bam_error(MENU_BACKUP_FAIL, GRUB_BACKUP_MENU);
3649 		return (BAM_ERROR);
3650 	}
3651 	BAM_DPRINTF((D_CREATED_BACKUP, fcn, GRUB_BACKUP_MENU));
3652 
3653 	(void) snprintf(cmdline, sizeof (cmdline),
3654 	    "/bin/sh -c '. %s > /dev/null; %s %s no > /dev/null'",
3655 	    LULIB, LULIB_PROPAGATE_FILE, GRUB_BACKUP_MENU);
3656 	ret = exec_cmd(cmdline, NULL);
3657 	INJECT_ERROR1("PROPAGATE_BACKUP", ret = 1);
3658 	if (ret != 0) {
3659 		bam_error(BACKUP_PROP_FAIL, GRUB_BACKUP_MENU);
3660 		return (BAM_ERROR);
3661 	}
3662 	BAM_DPRINTF((D_PROPAGATED_BACKUP, fcn, GRUB_BACKUP_MENU));
3663 
3664 	(void) snprintf(cmdline, sizeof (cmdline), "%s %s > %s",
3665 	    CKSUM, GRUB_MENU, LU_MENU_CKSUM);
3666 	ret = exec_cmd(cmdline, NULL);
3667 	INJECT_ERROR1("CREATE_CKSUM_FILE", ret = 1);
3668 	if (ret != 0) {
3669 		bam_error(MENU_CKSUM_WRITE_FAIL, LU_MENU_CKSUM);
3670 		return (BAM_ERROR);
3671 	}
3672 	BAM_DPRINTF((D_CREATED_CKSUM_FILE, fcn, LU_MENU_CKSUM));
3673 
3674 	(void) snprintf(cmdline, sizeof (cmdline),
3675 	    "/bin/sh -c '. %s > /dev/null; %s %s no > /dev/null'",
3676 	    LULIB, LULIB_PROPAGATE_FILE, LU_MENU_CKSUM);
3677 	ret = exec_cmd(cmdline, NULL);
3678 	INJECT_ERROR1("PROPAGATE_MENU_CKSUM_FILE", ret = 1);
3679 	if (ret != 0) {
3680 		bam_error(MENU_CKSUM_PROP_FAIL, LU_MENU_CKSUM);
3681 		return (BAM_ERROR);
3682 	}
3683 	BAM_DPRINTF((D_PROPAGATED_CKSUM_FILE, fcn, LU_MENU_CKSUM));
3684 
3685 	return (BAM_SUCCESS);
3686 }
3687 
3688 static error_t
3689 update_all(char *root, char *opt)
3690 {
3691 	struct extmnttab mnt;
3692 	struct stat sb;
3693 	FILE *fp;
3694 	char multibt[PATH_MAX];
3695 	char creatram[PATH_MAX];
3696 	error_t ret = BAM_SUCCESS;
3697 
3698 	assert(root);
3699 	assert(opt == NULL);
3700 
3701 	if (bam_rootlen != 1 || *root != '/') {
3702 		elide_trailing_slash(root, multibt, sizeof (multibt));
3703 		bam_error(ALT_ROOT_INVALID, multibt);
3704 		return (BAM_ERROR);
3705 	}
3706 
3707 	/*
3708 	 * Check to see if we are in the midst of safemode patching
3709 	 * If so skip building the archive for /. Instead build it
3710 	 * against the latest bits obtained by creating a fresh lofs
3711 	 * mount of root.
3712 	 */
3713 	if (stat(LOFS_PATCH_FILE, &sb) == 0)  {
3714 		if (mkdir(LOFS_PATCH_MNT, DIR_PERMS) == -1 &&
3715 		    errno != EEXIST) {
3716 			bam_error(MKDIR_FAILED, "%s", LOFS_PATCH_MNT,
3717 			    strerror(errno));
3718 			ret = BAM_ERROR;
3719 			goto out;
3720 		}
3721 		(void) snprintf(multibt, sizeof (multibt),
3722 		    "/sbin/mount -F lofs -o nosub /  %s", LOFS_PATCH_MNT);
3723 		if (exec_cmd(multibt, NULL) != 0) {
3724 			bam_error(MOUNT_FAILED, LOFS_PATCH_MNT, "lofs");
3725 			ret = BAM_ERROR;
3726 		}
3727 		if (ret != BAM_ERROR) {
3728 			(void) snprintf(rootbuf, sizeof (rootbuf), "%s/",
3729 			    LOFS_PATCH_MNT);
3730 			bam_rootlen = strlen(rootbuf);
3731 			if (update_archive(rootbuf, opt) != BAM_SUCCESS)
3732 				ret = BAM_ERROR;
3733 			/*
3734 			 * unmount the lofs mount since there could be
3735 			 * multiple invocations of bootadm -a update_all
3736 			 */
3737 			(void) snprintf(multibt, sizeof (multibt),
3738 			    "/sbin/umount %s", LOFS_PATCH_MNT);
3739 			if (exec_cmd(multibt, NULL) != 0) {
3740 				bam_error(UMOUNT_FAILED, LOFS_PATCH_MNT);
3741 				ret = BAM_ERROR;
3742 			}
3743 		}
3744 	} else {
3745 		/*
3746 		 * First update archive for current root
3747 		 */
3748 		if (update_archive(root, opt) != BAM_SUCCESS)
3749 			ret = BAM_ERROR;
3750 	}
3751 
3752 	if (ret == BAM_ERROR)
3753 		goto out;
3754 
3755 	/*
3756 	 * Now walk the mount table, performing archive update
3757 	 * for all mounted Newboot root filesystems
3758 	 */
3759 	fp = fopen(MNTTAB, "r");
3760 	if (fp == NULL) {
3761 		bam_error(OPEN_FAIL, MNTTAB, strerror(errno));
3762 		ret = BAM_ERROR;
3763 		goto out;
3764 	}
3765 
3766 	resetmnttab(fp);
3767 
3768 	while (getextmntent(fp, &mnt, sizeof (mnt)) == 0) {
3769 		if (mnt.mnt_special == NULL)
3770 			continue;
3771 		if ((strcmp(mnt.mnt_fstype, MNTTYPE_ZFS) != 0) &&
3772 		    (strncmp(mnt.mnt_special, "/dev/", strlen("/dev/")) != 0))
3773 			continue;
3774 		if (strcmp(mnt.mnt_mountp, "/") == 0)
3775 			continue;
3776 
3777 		(void) snprintf(creatram, sizeof (creatram), "%s/%s",
3778 		    mnt.mnt_mountp, CREATE_RAMDISK);
3779 
3780 		if (stat(creatram, &sb) == -1)
3781 			continue;
3782 
3783 		/*
3784 		 * We put a trailing slash to be consistent with root = "/"
3785 		 * case, such that we don't have to print // in some cases.
3786 		 */
3787 		(void) snprintf(rootbuf, sizeof (rootbuf), "%s/",
3788 		    mnt.mnt_mountp);
3789 		bam_rootlen = strlen(rootbuf);
3790 
3791 		/*
3792 		 * It's possible that other mounts may be an alternate boot
3793 		 * architecture, so check it again.
3794 		 */
3795 		if ((get_boot_cap(rootbuf) != BAM_SUCCESS) ||
3796 		    (update_archive(rootbuf, opt) != BAM_SUCCESS))
3797 			ret = BAM_ERROR;
3798 	}
3799 
3800 	(void) fclose(fp);
3801 
3802 out:
3803 	/*
3804 	 * We no longer use biosdev for Live Upgrade. Hence
3805 	 * there is no need to defer (to shutdown time) any fdisk
3806 	 * updates
3807 	 */
3808 	if (stat(GRUB_fdisk, &sb) == 0 || stat(GRUB_fdisk_target, &sb) == 0) {
3809 		bam_error(FDISK_FILES_FOUND, GRUB_fdisk, GRUB_fdisk_target);
3810 	}
3811 
3812 	/*
3813 	 * If user has updated menu in current BE, propagate the
3814 	 * updates to all BEs.
3815 	 */
3816 	if (sync_menu && synchronize_BE_menu() != BAM_SUCCESS)
3817 		ret = BAM_ERROR;
3818 
3819 	return (ret);
3820 }
3821 
3822 static void
3823 append_line(menu_t *mp, line_t *lp)
3824 {
3825 	if (mp->start == NULL) {
3826 		mp->start = lp;
3827 	} else {
3828 		mp->end->next = lp;
3829 		lp->prev = mp->end;
3830 	}
3831 	mp->end = lp;
3832 }
3833 
3834 void
3835 unlink_line(menu_t *mp, line_t *lp)
3836 {
3837 	/* unlink from list */
3838 	if (lp->prev)
3839 		lp->prev->next = lp->next;
3840 	else
3841 		mp->start = lp->next;
3842 	if (lp->next)
3843 		lp->next->prev = lp->prev;
3844 	else
3845 		mp->end = lp->prev;
3846 }
3847 
3848 static entry_t *
3849 boot_entry_new(menu_t *mp, line_t *start, line_t *end)
3850 {
3851 	entry_t *ent, *prev;
3852 	const char *fcn = "boot_entry_new()";
3853 
3854 	assert(mp);
3855 	assert(start);
3856 	assert(end);
3857 
3858 	ent = s_calloc(1, sizeof (entry_t));
3859 	BAM_DPRINTF((D_ENTRY_NEW, fcn));
3860 	ent->start = start;
3861 	ent->end = end;
3862 
3863 	if (mp->entries == NULL) {
3864 		mp->entries = ent;
3865 		BAM_DPRINTF((D_ENTRY_NEW_FIRST, fcn));
3866 		return (ent);
3867 	}
3868 
3869 	prev = mp->entries;
3870 	while (prev->next)
3871 		prev = prev->next;
3872 	prev->next = ent;
3873 	ent->prev = prev;
3874 	BAM_DPRINTF((D_ENTRY_NEW_LINKED, fcn));
3875 	return (ent);
3876 }
3877 
3878 static void
3879 boot_entry_addline(entry_t *ent, line_t *lp)
3880 {
3881 	if (ent)
3882 		ent->end = lp;
3883 }
3884 
3885 /*
3886  * Check whether cmd matches the one indexed by which, and whether arg matches
3887  * str.  which must be either KERNEL_CMD or MODULE_CMD, and a match to the
3888  * respective *_DOLLAR_CMD is also acceptable.  The arg is searched using
3889  * strstr(), so it can be a partial match.
3890  */
3891 static int
3892 check_cmd(const char *cmd, const int which, const char *arg, const char *str)
3893 {
3894 	int			ret;
3895 	const char		*fcn = "check_cmd()";
3896 
3897 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, arg, str));
3898 
3899 	if ((strcmp(cmd, menu_cmds[which]) != 0) &&
3900 	    (strcmp(cmd, menu_cmds[which + 1]) != 0)) {
3901 		BAM_DPRINTF((D_CHECK_CMD_CMD_NOMATCH,
3902 		    fcn, cmd, menu_cmds[which]));
3903 		return (0);
3904 	}
3905 	ret = (strstr(arg, str) != NULL);
3906 
3907 	if (ret) {
3908 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
3909 	} else {
3910 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
3911 	}
3912 
3913 	return (ret);
3914 }
3915 
3916 static error_t
3917 kernel_parser(entry_t *entry, char *cmd, char *arg, int linenum)
3918 {
3919 	const char		*fcn  = "kernel_parser()";
3920 
3921 	assert(entry);
3922 	assert(cmd);
3923 	assert(arg);
3924 
3925 	if (strcmp(cmd, menu_cmds[KERNEL_CMD]) != 0 &&
3926 	    strcmp(cmd, menu_cmds[KERNEL_DOLLAR_CMD]) != 0) {
3927 		BAM_DPRINTF((D_NOT_KERNEL_CMD, fcn, cmd));
3928 		return (BAM_ERROR);
3929 	}
3930 
3931 	if (strncmp(arg, DIRECT_BOOT_32, sizeof (DIRECT_BOOT_32) - 1) == 0) {
3932 		BAM_DPRINTF((D_SET_DBOOT_32, fcn, arg));
3933 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_32BIT;
3934 	} else if (strncmp(arg, DIRECT_BOOT_KERNEL,
3935 	    sizeof (DIRECT_BOOT_KERNEL) - 1) == 0) {
3936 		BAM_DPRINTF((D_SET_DBOOT, fcn, arg));
3937 		entry->flags |= BAM_ENTRY_DBOOT;
3938 	} else if (strncmp(arg, DIRECT_BOOT_64,
3939 	    sizeof (DIRECT_BOOT_64) - 1) == 0) {
3940 		BAM_DPRINTF((D_SET_DBOOT_64, fcn, arg));
3941 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_64BIT;
3942 	} else if (strncmp(arg, DIRECT_BOOT_FAILSAFE_KERNEL,
3943 	    sizeof (DIRECT_BOOT_FAILSAFE_KERNEL) - 1) == 0) {
3944 		BAM_DPRINTF((D_SET_DBOOT_FAILSAFE, fcn, arg));
3945 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_FAILSAFE;
3946 	} else if (strncmp(arg, DIRECT_BOOT_FAILSAFE_32,
3947 	    sizeof (DIRECT_BOOT_FAILSAFE_32) - 1) == 0) {
3948 		BAM_DPRINTF((D_SET_DBOOT_FAILSAFE_32, fcn, arg));
3949 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_FAILSAFE
3950 		    | BAM_ENTRY_32BIT;
3951 	} else if (strncmp(arg, DIRECT_BOOT_FAILSAFE_64,
3952 	    sizeof (DIRECT_BOOT_FAILSAFE_64) - 1) == 0) {
3953 		BAM_DPRINTF((D_SET_DBOOT_FAILSAFE_64, fcn, arg));
3954 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_FAILSAFE
3955 		    | BAM_ENTRY_64BIT;
3956 	} else if (strncmp(arg, MULTI_BOOT, sizeof (MULTI_BOOT) - 1) == 0) {
3957 		BAM_DPRINTF((D_SET_MULTIBOOT, fcn, arg));
3958 		entry->flags |= BAM_ENTRY_MULTIBOOT;
3959 	} else if (strncmp(arg, MULTI_BOOT_FAILSAFE,
3960 	    sizeof (MULTI_BOOT_FAILSAFE) - 1) == 0) {
3961 		BAM_DPRINTF((D_SET_MULTIBOOT_FAILSAFE, fcn, arg));
3962 		entry->flags |= BAM_ENTRY_MULTIBOOT | BAM_ENTRY_FAILSAFE;
3963 	} else if (strstr(arg, XEN_KERNEL_SUBSTR)) {
3964 		BAM_DPRINTF((D_SET_HV, fcn, arg));
3965 		entry->flags |= BAM_ENTRY_HV;
3966 	} else if (!(entry->flags & (BAM_ENTRY_BOOTADM|BAM_ENTRY_LU))) {
3967 		BAM_DPRINTF((D_SET_HAND_KERNEL, fcn, arg));
3968 		return (BAM_ERROR);
3969 	} else if (strncmp(arg, KERNEL_PREFIX, strlen(KERNEL_PREFIX)) == 0 &&
3970 	    strstr(arg, UNIX_SPACE)) {
3971 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_32BIT;
3972 	} else if (strncmp(arg, KERNEL_PREFIX, strlen(KERNEL_PREFIX)) == 0 &&
3973 	    strstr(arg, AMD_UNIX_SPACE)) {
3974 		entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_64BIT;
3975 	} else {
3976 		BAM_DPRINTF((D_IS_UNKNOWN_KERNEL, fcn, arg));
3977 		bam_error(UNKNOWN_KERNEL_LINE, linenum);
3978 		return (BAM_ERROR);
3979 	}
3980 
3981 	return (BAM_SUCCESS);
3982 }
3983 
3984 static error_t
3985 module_parser(entry_t *entry, char *cmd, char *arg, int linenum)
3986 {
3987 	const char		*fcn = "module_parser()";
3988 
3989 	assert(entry);
3990 	assert(cmd);
3991 	assert(arg);
3992 
3993 	if (strcmp(cmd, menu_cmds[MODULE_CMD]) != 0 &&
3994 	    strcmp(cmd, menu_cmds[MODULE_DOLLAR_CMD]) != 0) {
3995 		BAM_DPRINTF((D_NOT_MODULE_CMD, fcn, cmd));
3996 		return (BAM_ERROR);
3997 	}
3998 
3999 	if (strcmp(arg, DIRECT_BOOT_ARCHIVE) == 0 ||
4000 	    strcmp(arg, DIRECT_BOOT_ARCHIVE_32) == 0 ||
4001 	    strcmp(arg, DIRECT_BOOT_ARCHIVE_64) == 0 ||
4002 	    strcmp(arg, MULTIBOOT_ARCHIVE) == 0 ||
4003 	    strcmp(arg, FAILSAFE_ARCHIVE) == 0 ||
4004 	    strcmp(arg, FAILSAFE_ARCHIVE_32) == 0 ||
4005 	    strcmp(arg, FAILSAFE_ARCHIVE_64) == 0 ||
4006 	    strcmp(arg, XEN_KERNEL_MODULE_LINE) == 0 ||
4007 	    strcmp(arg, XEN_KERNEL_MODULE_LINE_ZFS) == 0) {
4008 		BAM_DPRINTF((D_BOOTADM_LU_MODULE, fcn, arg));
4009 		return (BAM_SUCCESS);
4010 	} else if (!(entry->flags & BAM_ENTRY_BOOTADM) &&
4011 	    !(entry->flags & BAM_ENTRY_LU)) {
4012 		/* don't emit warning for hand entries */
4013 		BAM_DPRINTF((D_IS_HAND_MODULE, fcn, arg));
4014 		return (BAM_ERROR);
4015 	} else {
4016 		BAM_DPRINTF((D_IS_UNKNOWN_MODULE, fcn, arg));
4017 		bam_error(UNKNOWN_MODULE_LINE, linenum);
4018 		return (BAM_ERROR);
4019 	}
4020 }
4021 
4022 /*
4023  * A line in menu.lst looks like
4024  * [ ]*<cmd>[ \t=]*<arg>*
4025  */
4026 static void
4027 line_parser(menu_t *mp, char *str, int *lineNum, int *entryNum)
4028 {
4029 	/*
4030 	 * save state across calls. This is so that
4031 	 * header gets the right entry# after title has
4032 	 * been processed
4033 	 */
4034 	static line_t *prev = NULL;
4035 	static entry_t *curr_ent = NULL;
4036 	static int in_liveupgrade = 0;
4037 
4038 	line_t	*lp;
4039 	char *cmd, *sep, *arg;
4040 	char save, *cp, *line;
4041 	menu_flag_t flag = BAM_INVALID;
4042 	const char *fcn = "line_parser()";
4043 
4044 	if (str == NULL) {
4045 		return;
4046 	}
4047 
4048 	/*
4049 	 * First save a copy of the entire line.
4050 	 * We use this later to set the line field.
4051 	 */
4052 	line = s_strdup(str);
4053 
4054 	/* Eat up leading whitespace */
4055 	while (*str == ' ' || *str == '\t')
4056 		str++;
4057 
4058 	if (*str == '#') {		/* comment */
4059 		cmd = s_strdup("#");
4060 		sep = NULL;
4061 		arg = s_strdup(str + 1);
4062 		flag = BAM_COMMENT;
4063 		if (strstr(arg, BAM_LU_HDR) != NULL) {
4064 			in_liveupgrade = 1;
4065 		} else if (strstr(arg, BAM_LU_FTR) != NULL) {
4066 			in_liveupgrade = 0;
4067 		}
4068 	} else if (*str == '\0') {	/* blank line */
4069 		cmd = sep = arg = NULL;
4070 		flag = BAM_EMPTY;
4071 	} else {
4072 		/*
4073 		 * '=' is not a documented separator in grub syntax.
4074 		 * However various development bits use '=' as a
4075 		 * separator. In addition, external users also
4076 		 * use = as a separator. So we will allow that usage.
4077 		 */
4078 		cp = str;
4079 		while (*str != ' ' && *str != '\t' && *str != '=') {
4080 			if (*str == '\0') {
4081 				cmd = s_strdup(cp);
4082 				sep = arg = NULL;
4083 				break;
4084 			}
4085 			str++;
4086 		}
4087 
4088 		if (*str != '\0') {
4089 			save = *str;
4090 			*str = '\0';
4091 			cmd = s_strdup(cp);
4092 			*str = save;
4093 
4094 			str++;
4095 			save = *str;
4096 			*str = '\0';
4097 			sep = s_strdup(str - 1);
4098 			*str = save;
4099 
4100 			while (*str == ' ' || *str == '\t')
4101 				str++;
4102 			if (*str == '\0')
4103 				arg = NULL;
4104 			else
4105 				arg = s_strdup(str);
4106 		}
4107 	}
4108 
4109 	lp = s_calloc(1, sizeof (line_t));
4110 
4111 	lp->cmd = cmd;
4112 	lp->sep = sep;
4113 	lp->arg = arg;
4114 	lp->line = line;
4115 	lp->lineNum = ++(*lineNum);
4116 	if (cmd && strcmp(cmd, menu_cmds[TITLE_CMD]) == 0) {
4117 		lp->entryNum = ++(*entryNum);
4118 		lp->flags = BAM_TITLE;
4119 		if (prev && prev->flags == BAM_COMMENT &&
4120 		    prev->arg && strcmp(prev->arg, BAM_BOOTADM_HDR) == 0) {
4121 			prev->entryNum = lp->entryNum;
4122 			curr_ent = boot_entry_new(mp, prev, lp);
4123 			curr_ent->flags |= BAM_ENTRY_BOOTADM;
4124 			BAM_DPRINTF((D_IS_BOOTADM_ENTRY, fcn, arg));
4125 		} else {
4126 			curr_ent = boot_entry_new(mp, lp, lp);
4127 			if (in_liveupgrade) {
4128 				curr_ent->flags |= BAM_ENTRY_LU;
4129 				BAM_DPRINTF((D_IS_LU_ENTRY, fcn, arg));
4130 			}
4131 		}
4132 		curr_ent->entryNum = *entryNum;
4133 	} else if (flag != BAM_INVALID) {
4134 		/*
4135 		 * For header comments, the entry# is "fixed up"
4136 		 * by the subsequent title
4137 		 */
4138 		lp->entryNum = *entryNum;
4139 		lp->flags = flag;
4140 	} else {
4141 		lp->entryNum = *entryNum;
4142 
4143 		if (*entryNum == ENTRY_INIT) {
4144 			lp->flags = BAM_GLOBAL;
4145 		} else {
4146 			lp->flags = BAM_ENTRY;
4147 
4148 			if (cmd && arg) {
4149 				if (strcmp(cmd, menu_cmds[ROOT_CMD]) == 0) {
4150 					BAM_DPRINTF((D_IS_ROOT_CMD, fcn, arg));
4151 					curr_ent->flags |= BAM_ENTRY_ROOT;
4152 				} else if (strcmp(cmd, menu_cmds[FINDROOT_CMD])
4153 				    == 0) {
4154 					BAM_DPRINTF((D_IS_FINDROOT_CMD, fcn,
4155 					    arg));
4156 					curr_ent->flags |= BAM_ENTRY_FINDROOT;
4157 				} else if (strcmp(cmd,
4158 				    menu_cmds[CHAINLOADER_CMD]) == 0) {
4159 					BAM_DPRINTF((D_IS_CHAINLOADER_CMD, fcn,
4160 					    arg));
4161 					curr_ent->flags |=
4162 					    BAM_ENTRY_CHAINLOADER;
4163 				} else if (kernel_parser(curr_ent, cmd, arg,
4164 				    lp->lineNum) != BAM_SUCCESS) {
4165 					(void) module_parser(curr_ent, cmd,
4166 					    arg, lp->lineNum);
4167 				}
4168 			}
4169 		}
4170 	}
4171 
4172 	/* record default, old default, and entry line ranges */
4173 	if (lp->flags == BAM_GLOBAL &&
4174 	    strcmp(lp->cmd, menu_cmds[DEFAULT_CMD]) == 0) {
4175 		mp->curdefault = lp;
4176 	} else if (lp->flags == BAM_COMMENT &&
4177 	    strncmp(lp->arg, BAM_OLDDEF, strlen(BAM_OLDDEF)) == 0) {
4178 		mp->olddefault = lp;
4179 	} else if (lp->flags == BAM_COMMENT &&
4180 	    strncmp(lp->arg, BAM_OLD_RC_DEF, strlen(BAM_OLD_RC_DEF)) == 0) {
4181 		mp->old_rc_default = lp;
4182 	} else if (lp->flags == BAM_ENTRY ||
4183 	    (lp->flags == BAM_COMMENT &&
4184 	    strcmp(lp->arg, BAM_BOOTADM_FTR) == 0)) {
4185 		boot_entry_addline(curr_ent, lp);
4186 	}
4187 	append_line(mp, lp);
4188 
4189 	prev = lp;
4190 }
4191 
4192 void
4193 update_numbering(menu_t *mp)
4194 {
4195 	int lineNum;
4196 	int entryNum;
4197 	int old_default_value;
4198 	line_t *lp, *prev, *default_lp, *default_entry;
4199 	char buf[PATH_MAX];
4200 
4201 	if (mp->start == NULL) {
4202 		return;
4203 	}
4204 
4205 	lineNum = LINE_INIT;
4206 	entryNum = ENTRY_INIT;
4207 	old_default_value = ENTRY_INIT;
4208 	lp = default_lp = default_entry = NULL;
4209 
4210 	prev = NULL;
4211 	for (lp = mp->start; lp; prev = lp, lp = lp->next) {
4212 		lp->lineNum = ++lineNum;
4213 
4214 		/*
4215 		 * Get the value of the default command
4216 		 */
4217 		if (lp->entryNum == ENTRY_INIT && lp->cmd &&
4218 		    strcmp(lp->cmd, menu_cmds[DEFAULT_CMD]) == 0 &&
4219 		    lp->arg) {
4220 			old_default_value = atoi(lp->arg);
4221 			default_lp = lp;
4222 		}
4223 
4224 		/*
4225 		 * If not a booting entry, nothing else to fix for this
4226 		 * entry
4227 		 */
4228 		if (lp->entryNum == ENTRY_INIT)
4229 			continue;
4230 
4231 		/*
4232 		 * Record the position of the default entry.
4233 		 * The following works because global
4234 		 * commands like default and timeout should precede
4235 		 * actual boot entries, so old_default_value
4236 		 * is already known (or default cmd is missing).
4237 		 */
4238 		if (default_entry == NULL &&
4239 		    old_default_value != ENTRY_INIT &&
4240 		    lp->entryNum == old_default_value) {
4241 			default_entry = lp;
4242 		}
4243 
4244 		/*
4245 		 * Now fixup the entry number
4246 		 */
4247 		if (lp->cmd && strcmp(lp->cmd, menu_cmds[TITLE_CMD]) == 0) {
4248 			lp->entryNum = ++entryNum;
4249 			/* fixup the bootadm header */
4250 			if (prev && prev->flags == BAM_COMMENT &&
4251 			    prev->arg &&
4252 			    strcmp(prev->arg, BAM_BOOTADM_HDR) == 0) {
4253 				prev->entryNum = lp->entryNum;
4254 			}
4255 		} else {
4256 			lp->entryNum = entryNum;
4257 		}
4258 	}
4259 
4260 	/*
4261 	 * No default command in menu, simply return
4262 	 */
4263 	if (default_lp == NULL) {
4264 		return;
4265 	}
4266 
4267 	free(default_lp->arg);
4268 	free(default_lp->line);
4269 
4270 	if (default_entry == NULL) {
4271 		default_lp->arg = s_strdup("0");
4272 	} else {
4273 		(void) snprintf(buf, sizeof (buf), "%d",
4274 		    default_entry->entryNum);
4275 		default_lp->arg = s_strdup(buf);
4276 	}
4277 
4278 	/*
4279 	 * The following is required since only the line field gets
4280 	 * written back to menu.lst
4281 	 */
4282 	(void) snprintf(buf, sizeof (buf), "%s%s%s",
4283 	    menu_cmds[DEFAULT_CMD], menu_cmds[SEP_CMD], default_lp->arg);
4284 	default_lp->line = s_strdup(buf);
4285 }
4286 
4287 
4288 static menu_t *
4289 menu_read(char *menu_path)
4290 {
4291 	FILE *fp;
4292 	char buf[BAM_MAXLINE], *cp;
4293 	menu_t *mp;
4294 	int line, entry, len, n;
4295 
4296 	mp = s_calloc(1, sizeof (menu_t));
4297 
4298 	fp = fopen(menu_path, "r");
4299 	if (fp == NULL) { /* Let the caller handle this error */
4300 		return (mp);
4301 	}
4302 
4303 
4304 	/* Note: GRUB boot entry number starts with 0 */
4305 	line = LINE_INIT;
4306 	entry = ENTRY_INIT;
4307 	cp = buf;
4308 	len = sizeof (buf);
4309 	while (s_fgets(cp, len, fp) != NULL) {
4310 		n = strlen(cp);
4311 		if (cp[n - 1] == '\\') {
4312 			len -= n - 1;
4313 			assert(len >= 2);
4314 			cp += n - 1;
4315 			continue;
4316 		}
4317 		line_parser(mp, buf, &line, &entry);
4318 		cp = buf;
4319 		len = sizeof (buf);
4320 	}
4321 
4322 	if (fclose(fp) == EOF) {
4323 		bam_error(CLOSE_FAIL, menu_path, strerror(errno));
4324 	}
4325 
4326 	return (mp);
4327 }
4328 
4329 static error_t
4330 selector(menu_t *mp, char *opt, int *entry, char **title)
4331 {
4332 	char *eq;
4333 	char *opt_dup;
4334 	int entryNum;
4335 
4336 	assert(mp);
4337 	assert(mp->start);
4338 	assert(opt);
4339 
4340 	opt_dup = s_strdup(opt);
4341 
4342 	if (entry)
4343 		*entry = ENTRY_INIT;
4344 	if (title)
4345 		*title = NULL;
4346 
4347 	eq = strchr(opt_dup, '=');
4348 	if (eq == NULL) {
4349 		bam_error(INVALID_OPT, opt);
4350 		free(opt_dup);
4351 		return (BAM_ERROR);
4352 	}
4353 
4354 	*eq = '\0';
4355 	if (entry && strcmp(opt_dup, OPT_ENTRY_NUM) == 0) {
4356 		assert(mp->end);
4357 		entryNum = s_strtol(eq + 1);
4358 		if (entryNum < 0 || entryNum > mp->end->entryNum) {
4359 			bam_error(INVALID_ENTRY, eq + 1);
4360 			free(opt_dup);
4361 			return (BAM_ERROR);
4362 		}
4363 		*entry = entryNum;
4364 	} else if (title && strcmp(opt_dup, menu_cmds[TITLE_CMD]) == 0) {
4365 		*title = opt + (eq - opt_dup) + 1;
4366 	} else {
4367 		bam_error(INVALID_OPT, opt);
4368 		free(opt_dup);
4369 		return (BAM_ERROR);
4370 	}
4371 
4372 	free(opt_dup);
4373 	return (BAM_SUCCESS);
4374 }
4375 
4376 /*
4377  * If invoked with no titles/entries (opt == NULL)
4378  * only title lines in file are printed.
4379  *
4380  * If invoked with a title or entry #, all
4381  * lines in *every* matching entry are listed
4382  */
4383 static error_t
4384 list_entry(menu_t *mp, char *menu_path, char *opt)
4385 {
4386 	line_t *lp;
4387 	int entry = ENTRY_INIT;
4388 	int found;
4389 	char *title = NULL;
4390 
4391 	assert(mp);
4392 	assert(menu_path);
4393 
4394 	/* opt is optional */
4395 	BAM_DPRINTF((D_FUNC_ENTRY2, "list_entry", menu_path,
4396 	    opt ? opt : "<NULL>"));
4397 
4398 	if (mp->start == NULL) {
4399 		bam_error(NO_MENU, menu_path);
4400 		return (BAM_ERROR);
4401 	}
4402 
4403 	if (opt != NULL) {
4404 		if (selector(mp, opt, &entry, &title) != BAM_SUCCESS) {
4405 			return (BAM_ERROR);
4406 		}
4407 		assert((entry != ENTRY_INIT) ^ (title != NULL));
4408 	} else {
4409 		(void) read_globals(mp, menu_path, menu_cmds[DEFAULT_CMD], 0);
4410 		(void) read_globals(mp, menu_path, menu_cmds[TIMEOUT_CMD], 0);
4411 	}
4412 
4413 	found = 0;
4414 	for (lp = mp->start; lp; lp = lp->next) {
4415 		if (lp->flags == BAM_COMMENT || lp->flags == BAM_EMPTY)
4416 			continue;
4417 		if (opt == NULL && lp->flags == BAM_TITLE) {
4418 			bam_print(PRINT_TITLE, lp->entryNum,
4419 			    lp->arg);
4420 			found = 1;
4421 			continue;
4422 		}
4423 		if (entry != ENTRY_INIT && lp->entryNum == entry) {
4424 			bam_print(PRINT, lp->line);
4425 			found = 1;
4426 			continue;
4427 		}
4428 
4429 		/*
4430 		 * We set the entry value here so that all lines
4431 		 * in entry get printed. If we subsequently match
4432 		 * title in other entries, all lines in those
4433 		 * entries get printed as well.
4434 		 */
4435 		if (title && lp->flags == BAM_TITLE && lp->arg &&
4436 		    strncmp(title, lp->arg, strlen(title)) == 0) {
4437 			bam_print(PRINT, lp->line);
4438 			entry = lp->entryNum;
4439 			found = 1;
4440 			continue;
4441 		}
4442 	}
4443 
4444 	if (!found) {
4445 		bam_error(NO_MATCH_ENTRY);
4446 		return (BAM_ERROR);
4447 	}
4448 
4449 	return (BAM_SUCCESS);
4450 }
4451 
4452 int
4453 add_boot_entry(menu_t *mp,
4454 	char *title,
4455 	char *findroot,
4456 	char *kernel,
4457 	char *mod_kernel,
4458 	char *module)
4459 {
4460 	int		lineNum;
4461 	int		entryNum;
4462 	char		linebuf[BAM_MAXLINE];
4463 	menu_cmd_t	k_cmd;
4464 	menu_cmd_t	m_cmd;
4465 	const char	*fcn = "add_boot_entry()";
4466 
4467 	assert(mp);
4468 
4469 	INJECT_ERROR1("ADD_BOOT_ENTRY_FINDROOT_NULL", findroot = NULL);
4470 	if (findroot == NULL) {
4471 		bam_error(NULL_FINDROOT);
4472 		return (BAM_ERROR);
4473 	}
4474 
4475 	if (title == NULL) {
4476 		title = "Solaris";	/* default to Solaris */
4477 	}
4478 	if (kernel == NULL) {
4479 		bam_error(SUBOPT_MISS, menu_cmds[KERNEL_CMD]);
4480 		return (BAM_ERROR);
4481 	}
4482 	if (module == NULL) {
4483 		if (bam_direct != BAM_DIRECT_DBOOT) {
4484 			bam_error(SUBOPT_MISS, menu_cmds[MODULE_CMD]);
4485 			return (BAM_ERROR);
4486 		}
4487 
4488 		/* Figure the commands out from the kernel line */
4489 		if (strstr(kernel, "$ISADIR") != NULL) {
4490 			module = DIRECT_BOOT_ARCHIVE;
4491 			k_cmd = KERNEL_DOLLAR_CMD;
4492 			m_cmd = MODULE_DOLLAR_CMD;
4493 		} else if (strstr(kernel, "amd64") != NULL) {
4494 			module = DIRECT_BOOT_ARCHIVE_64;
4495 			k_cmd = KERNEL_CMD;
4496 			m_cmd = MODULE_CMD;
4497 		} else {
4498 			module = DIRECT_BOOT_ARCHIVE_32;
4499 			k_cmd = KERNEL_CMD;
4500 			m_cmd = MODULE_CMD;
4501 		}
4502 	} else if ((bam_direct == BAM_DIRECT_DBOOT) &&
4503 	    (strstr(kernel, "$ISADIR") != NULL)) {
4504 		/*
4505 		 * If it's a non-failsafe dboot kernel, use the "kernel$"
4506 		 * command.  Otherwise, use "kernel".
4507 		 */
4508 		k_cmd = KERNEL_DOLLAR_CMD;
4509 		m_cmd = MODULE_DOLLAR_CMD;
4510 	} else {
4511 		k_cmd = KERNEL_CMD;
4512 		m_cmd = MODULE_CMD;
4513 	}
4514 
4515 	if (mp->start) {
4516 		lineNum = mp->end->lineNum;
4517 		entryNum = mp->end->entryNum;
4518 	} else {
4519 		lineNum = LINE_INIT;
4520 		entryNum = ENTRY_INIT;
4521 	}
4522 
4523 	/*
4524 	 * No separator for comment (HDR/FTR) commands
4525 	 * The syntax for comments is #<comment>
4526 	 */
4527 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s",
4528 	    menu_cmds[COMMENT_CMD], BAM_BOOTADM_HDR);
4529 	line_parser(mp, linebuf, &lineNum, &entryNum);
4530 
4531 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
4532 	    menu_cmds[TITLE_CMD], menu_cmds[SEP_CMD], title);
4533 	line_parser(mp, linebuf, &lineNum, &entryNum);
4534 
4535 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
4536 	    menu_cmds[FINDROOT_CMD], menu_cmds[SEP_CMD], findroot);
4537 	line_parser(mp, linebuf, &lineNum, &entryNum);
4538 	BAM_DPRINTF((D_ADD_FINDROOT_NUM, fcn, lineNum, entryNum));
4539 
4540 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
4541 	    menu_cmds[k_cmd], menu_cmds[SEP_CMD], kernel);
4542 	line_parser(mp, linebuf, &lineNum, &entryNum);
4543 
4544 	if (mod_kernel != NULL) {
4545 		(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
4546 		    menu_cmds[m_cmd], menu_cmds[SEP_CMD], mod_kernel);
4547 		line_parser(mp, linebuf, &lineNum, &entryNum);
4548 	}
4549 
4550 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
4551 	    menu_cmds[m_cmd], menu_cmds[SEP_CMD], module);
4552 	line_parser(mp, linebuf, &lineNum, &entryNum);
4553 
4554 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s",
4555 	    menu_cmds[COMMENT_CMD], BAM_BOOTADM_FTR);
4556 	line_parser(mp, linebuf, &lineNum, &entryNum);
4557 
4558 	return (entryNum);
4559 }
4560 
4561 static error_t
4562 do_delete(menu_t *mp, int entryNum)
4563 {
4564 	line_t		*lp;
4565 	line_t		*freed;
4566 	entry_t		*ent;
4567 	entry_t		*tmp;
4568 	int		deleted;
4569 	const char	*fcn = "do_delete()";
4570 
4571 	assert(entryNum != ENTRY_INIT);
4572 
4573 	tmp = NULL;
4574 
4575 	ent = mp->entries;
4576 	while (ent) {
4577 		lp = ent->start;
4578 		/* check entry number and make sure it's a bootadm entry */
4579 		if (lp->flags != BAM_COMMENT ||
4580 		    strcmp(lp->arg, BAM_BOOTADM_HDR) != 0 ||
4581 		    (entryNum != ALL_ENTRIES && lp->entryNum != entryNum)) {
4582 			ent = ent->next;
4583 			continue;
4584 		}
4585 
4586 		/* free the entry content */
4587 		do {
4588 			freed = lp;
4589 			lp = lp->next;	/* prev stays the same */
4590 			BAM_DPRINTF((D_FREEING_LINE, fcn, freed->lineNum));
4591 			unlink_line(mp, freed);
4592 			line_free(freed);
4593 		} while (freed != ent->end);
4594 
4595 		/* free the entry_t structure */
4596 		assert(tmp == NULL);
4597 		tmp = ent;
4598 		ent = ent->next;
4599 		if (tmp->prev)
4600 			tmp->prev->next = ent;
4601 		else
4602 			mp->entries = ent;
4603 		if (ent)
4604 			ent->prev = tmp->prev;
4605 		BAM_DPRINTF((D_FREEING_ENTRY, fcn, tmp->entryNum));
4606 		free(tmp);
4607 		tmp = NULL;
4608 		deleted = 1;
4609 	}
4610 
4611 	assert(tmp == NULL);
4612 
4613 	if (!deleted && entryNum != ALL_ENTRIES) {
4614 		bam_error(NO_BOOTADM_MATCH);
4615 		return (BAM_ERROR);
4616 	}
4617 
4618 	/*
4619 	 * Now that we have deleted an entry, update
4620 	 * the entry numbering and the default cmd.
4621 	 */
4622 	update_numbering(mp);
4623 
4624 	return (BAM_SUCCESS);
4625 }
4626 
4627 static error_t
4628 delete_all_entries(menu_t *mp, char *dummy, char *opt)
4629 {
4630 	assert(mp);
4631 	assert(dummy == NULL);
4632 	assert(opt == NULL);
4633 
4634 	BAM_DPRINTF((D_FUNC_ENTRY0, "delete_all_entries"));
4635 
4636 	if (mp->start == NULL) {
4637 		bam_print(EMPTY_MENU);
4638 		return (BAM_SUCCESS);
4639 	}
4640 
4641 	if (do_delete(mp, ALL_ENTRIES) != BAM_SUCCESS) {
4642 		return (BAM_ERROR);
4643 	}
4644 
4645 	return (BAM_WRITE);
4646 }
4647 
4648 static FILE *
4649 create_diskmap(char *osroot)
4650 {
4651 	FILE *fp;
4652 	char cmd[PATH_MAX + 16];
4653 	char path[PATH_MAX];
4654 	const char *fcn = "create_diskmap()";
4655 
4656 	/* make sure we have a map file */
4657 	fp = fopen(GRUBDISK_MAP, "r");
4658 	if (fp == NULL) {
4659 		int	ret;
4660 
4661 		ret = snprintf(path, sizeof (path), "%s/%s", osroot,
4662 		    CREATE_DISKMAP);
4663 		if (ret >= sizeof (path)) {
4664 			bam_error(PATH_TOO_LONG, osroot);
4665 			return (NULL);
4666 		}
4667 		if (is_safe_exec(path) == BAM_ERROR)
4668 			return (NULL);
4669 
4670 		(void) snprintf(cmd, sizeof (cmd),
4671 		    "%s/%s > /dev/null", osroot, CREATE_DISKMAP);
4672 		if (exec_cmd(cmd, NULL) != 0)
4673 			return (NULL);
4674 		fp = fopen(GRUBDISK_MAP, "r");
4675 		INJECT_ERROR1("DISKMAP_CREATE_FAIL", fp = NULL);
4676 		if (fp) {
4677 			BAM_DPRINTF((D_CREATED_DISKMAP, fcn, GRUBDISK_MAP));
4678 		} else {
4679 			BAM_DPRINTF((D_CREATE_DISKMAP_FAIL, fcn, GRUBDISK_MAP));
4680 		}
4681 	}
4682 	return (fp);
4683 }
4684 
4685 #define	SECTOR_SIZE	512
4686 
4687 static int
4688 get_partition(char *device)
4689 {
4690 	int i, fd, is_pcfs, partno = -1;
4691 	struct mboot *mboot;
4692 	char boot_sect[SECTOR_SIZE];
4693 	char *wholedisk, *slice;
4694 
4695 	/* form whole disk (p0) */
4696 	slice = device + strlen(device) - 2;
4697 	is_pcfs = (*slice != 's');
4698 	if (!is_pcfs)
4699 		*slice = '\0';
4700 	wholedisk = s_calloc(1, strlen(device) + 3);
4701 	(void) snprintf(wholedisk, strlen(device) + 3, "%sp0", device);
4702 	if (!is_pcfs)
4703 		*slice = 's';
4704 
4705 	/* read boot sector */
4706 	fd = open(wholedisk, O_RDONLY);
4707 	free(wholedisk);
4708 	if (fd == -1 || read(fd, boot_sect, SECTOR_SIZE) != SECTOR_SIZE) {
4709 		return (partno);
4710 	}
4711 	(void) close(fd);
4712 
4713 	/* parse fdisk table */
4714 	mboot = (struct mboot *)((void *)boot_sect);
4715 	for (i = 0; i < FD_NUMPART; i++) {
4716 		struct ipart *part =
4717 		    (struct ipart *)(uintptr_t)mboot->parts + i;
4718 		if (is_pcfs) {	/* looking for solaris boot part */
4719 			if (part->systid == 0xbe) {
4720 				partno = i;
4721 				break;
4722 			}
4723 		} else {	/* look for solaris partition, old and new */
4724 			if (part->systid == SUNIXOS ||
4725 			    part->systid == SUNIXOS2) {
4726 				partno = i;
4727 				break;
4728 			}
4729 		}
4730 	}
4731 	return (partno);
4732 }
4733 
4734 char *
4735 get_grubroot(char *osroot, char *osdev, char *menu_root)
4736 {
4737 	char		*grubroot;	/* (hd#,#,#) */
4738 	char		*slice;
4739 	char		*grubhd;
4740 	int		fdiskpart;
4741 	int		found = 0;
4742 	char		*devname;
4743 	char		*ctdname = strstr(osdev, "dsk/");
4744 	char		linebuf[PATH_MAX];
4745 	FILE		*fp;
4746 
4747 	INJECT_ERROR1("GRUBROOT_INVALID_OSDEV", ctdname = NULL);
4748 	if (ctdname == NULL) {
4749 		bam_error(INVALID_DEV_DSK, osdev);
4750 		return (NULL);
4751 	}
4752 
4753 	if (menu_root && !menu_on_bootdisk(osroot, menu_root)) {
4754 		/* menu bears no resemblance to our reality */
4755 		bam_error(CANNOT_GRUBROOT_BOOTDISK, osdev);
4756 		return (NULL);
4757 	}
4758 
4759 	ctdname += strlen("dsk/");
4760 	slice = strrchr(ctdname, 's');
4761 	if (slice)
4762 		*slice = '\0';
4763 
4764 	fp = create_diskmap(osroot);
4765 	if (fp == NULL) {
4766 		bam_error(DISKMAP_FAIL, osroot);
4767 		return (NULL);
4768 	}
4769 
4770 	rewind(fp);
4771 	while (s_fgets(linebuf, sizeof (linebuf), fp) != NULL) {
4772 		grubhd = strtok(linebuf, " \t\n");
4773 		if (grubhd)
4774 			devname = strtok(NULL, " \t\n");
4775 		else
4776 			devname = NULL;
4777 		if (devname && strcmp(devname, ctdname) == 0) {
4778 			found = 1;
4779 			break;
4780 		}
4781 	}
4782 
4783 	if (slice)
4784 		*slice = 's';
4785 
4786 	(void) fclose(fp);
4787 	fp = NULL;
4788 
4789 	INJECT_ERROR1("GRUBROOT_BIOSDEV_FAIL", found = 0);
4790 	if (found == 0) {
4791 		bam_error(BIOSDEV_SKIP, osdev);
4792 		return (NULL);
4793 	}
4794 
4795 	fdiskpart = get_partition(osdev);
4796 	INJECT_ERROR1("GRUBROOT_FDISK_FAIL", fdiskpart = -1);
4797 	if (fdiskpart == -1) {
4798 		bam_error(FDISKPART_FAIL, osdev);
4799 		return (NULL);
4800 	}
4801 
4802 	grubroot = s_calloc(1, 10);
4803 	if (slice) {
4804 		(void) snprintf(grubroot, 10, "(hd%s,%d,%c)",
4805 		    grubhd, fdiskpart, slice[1] + 'a' - '0');
4806 	} else
4807 		(void) snprintf(grubroot, 10, "(hd%s,%d)",
4808 		    grubhd, fdiskpart);
4809 
4810 	assert(fp == NULL);
4811 	assert(strncmp(grubroot, "(hd", strlen("(hd")) == 0);
4812 	return (grubroot);
4813 }
4814 
4815 static char *
4816 find_primary_common(char *mntpt, char *fstype)
4817 {
4818 	char		signdir[PATH_MAX];
4819 	char		tmpsign[MAXNAMELEN + 1];
4820 	char		*lu;
4821 	char		*ufs;
4822 	char		*zfs;
4823 	DIR		*dirp = NULL;
4824 	struct dirent	*entp;
4825 	struct stat	sb;
4826 	const char	*fcn = "find_primary_common()";
4827 
4828 	(void) snprintf(signdir, sizeof (signdir), "%s/%s",
4829 	    mntpt, GRUBSIGN_DIR);
4830 
4831 	if (stat(signdir, &sb) == -1) {
4832 		BAM_DPRINTF((D_NO_SIGNDIR, fcn, signdir));
4833 		return (NULL);
4834 	}
4835 
4836 	dirp = opendir(signdir);
4837 	INJECT_ERROR1("SIGNDIR_OPENDIR_FAIL", dirp = NULL);
4838 	if (dirp == NULL) {
4839 		bam_error(OPENDIR_FAILED, signdir, strerror(errno));
4840 		return (NULL);
4841 	}
4842 
4843 	ufs = zfs = lu = NULL;
4844 
4845 	while (entp = readdir(dirp)) {
4846 		if (strcmp(entp->d_name, ".") == 0 ||
4847 		    strcmp(entp->d_name, "..") == 0)
4848 			continue;
4849 
4850 		(void) snprintf(tmpsign, sizeof (tmpsign), "%s", entp->d_name);
4851 
4852 		if (lu == NULL &&
4853 		    strncmp(tmpsign, GRUBSIGN_LU_PREFIX,
4854 		    strlen(GRUBSIGN_LU_PREFIX)) == 0) {
4855 			lu = s_strdup(tmpsign);
4856 		}
4857 
4858 		if (ufs == NULL &&
4859 		    strncmp(tmpsign, GRUBSIGN_UFS_PREFIX,
4860 		    strlen(GRUBSIGN_UFS_PREFIX)) == 0) {
4861 			ufs = s_strdup(tmpsign);
4862 		}
4863 
4864 		if (zfs == NULL &&
4865 		    strncmp(tmpsign, GRUBSIGN_ZFS_PREFIX,
4866 		    strlen(GRUBSIGN_ZFS_PREFIX)) == 0) {
4867 			zfs = s_strdup(tmpsign);
4868 		}
4869 	}
4870 
4871 	BAM_DPRINTF((D_EXIST_PRIMARY_SIGNS, fcn,
4872 	    zfs ? zfs : "NULL",
4873 	    ufs ? ufs : "NULL",
4874 	    lu ? lu : "NULL"));
4875 
4876 	if (dirp) {
4877 		(void) closedir(dirp);
4878 		dirp = NULL;
4879 	}
4880 
4881 	if (strcmp(fstype, "ufs") == 0 && zfs) {
4882 		bam_error(SIGN_FSTYPE_MISMATCH, zfs, "ufs");
4883 		free(zfs);
4884 		zfs = NULL;
4885 	} else if (strcmp(fstype, "zfs") == 0 && ufs) {
4886 		bam_error(SIGN_FSTYPE_MISMATCH, ufs, "zfs");
4887 		free(ufs);
4888 		ufs = NULL;
4889 	}
4890 
4891 	assert(dirp == NULL);
4892 
4893 	/* For now, we let Live Upgrade take care of its signature itself */
4894 	if (lu) {
4895 		BAM_DPRINTF((D_FREEING_LU_SIGNS, fcn, lu));
4896 		free(lu);
4897 		lu = NULL;
4898 	}
4899 
4900 	return (zfs ? zfs : ufs);
4901 }
4902 
4903 static char *
4904 find_backup_common(char *mntpt, char *fstype)
4905 {
4906 	FILE		*bfp = NULL;
4907 	char		tmpsign[MAXNAMELEN + 1];
4908 	char		backup[PATH_MAX];
4909 	char		*ufs;
4910 	char		*zfs;
4911 	char		*lu;
4912 	int		error;
4913 	const char	*fcn = "find_backup_common()";
4914 
4915 	/*
4916 	 * We didn't find it in the primary directory.
4917 	 * Look at the backup
4918 	 */
4919 	(void) snprintf(backup, sizeof (backup), "%s%s",
4920 	    mntpt, GRUBSIGN_BACKUP);
4921 
4922 	bfp = fopen(backup, "r");
4923 	if (bfp == NULL) {
4924 		error = errno;
4925 		if (bam_verbose) {
4926 			bam_error(OPEN_FAIL, backup, strerror(error));
4927 		}
4928 		BAM_DPRINTF((D_OPEN_FAIL, fcn, backup, strerror(error)));
4929 		return (NULL);
4930 	}
4931 
4932 	ufs = zfs = lu = NULL;
4933 
4934 	while (s_fgets(tmpsign, sizeof (tmpsign), bfp) != NULL) {
4935 
4936 		if (lu == NULL &&
4937 		    strncmp(tmpsign, GRUBSIGN_LU_PREFIX,
4938 		    strlen(GRUBSIGN_LU_PREFIX)) == 0) {
4939 			lu = s_strdup(tmpsign);
4940 		}
4941 
4942 		if (ufs == NULL &&
4943 		    strncmp(tmpsign, GRUBSIGN_UFS_PREFIX,
4944 		    strlen(GRUBSIGN_UFS_PREFIX)) == 0) {
4945 			ufs = s_strdup(tmpsign);
4946 		}
4947 
4948 		if (zfs == NULL &&
4949 		    strncmp(tmpsign, GRUBSIGN_ZFS_PREFIX,
4950 		    strlen(GRUBSIGN_ZFS_PREFIX)) == 0) {
4951 			zfs = s_strdup(tmpsign);
4952 		}
4953 	}
4954 
4955 	BAM_DPRINTF((D_EXIST_BACKUP_SIGNS, fcn,
4956 	    zfs ? zfs : "NULL",
4957 	    ufs ? ufs : "NULL",
4958 	    lu ? lu : "NULL"));
4959 
4960 	if (bfp) {
4961 		(void) fclose(bfp);
4962 		bfp = NULL;
4963 	}
4964 
4965 	if (strcmp(fstype, "ufs") == 0 && zfs) {
4966 		bam_error(SIGN_FSTYPE_MISMATCH, zfs, "ufs");
4967 		free(zfs);
4968 		zfs = NULL;
4969 	} else if (strcmp(fstype, "zfs") == 0 && ufs) {
4970 		bam_error(SIGN_FSTYPE_MISMATCH, ufs, "zfs");
4971 		free(ufs);
4972 		ufs = NULL;
4973 	}
4974 
4975 	assert(bfp == NULL);
4976 
4977 	/* For now, we let Live Upgrade take care of its signature itself */
4978 	if (lu) {
4979 		BAM_DPRINTF((D_FREEING_LU_SIGNS, fcn, lu));
4980 		free(lu);
4981 		lu = NULL;
4982 	}
4983 
4984 	return (zfs ? zfs : ufs);
4985 }
4986 
4987 static char *
4988 find_ufs_existing(char *osroot)
4989 {
4990 	char		*sign;
4991 	const char	*fcn = "find_ufs_existing()";
4992 
4993 	sign = find_primary_common(osroot, "ufs");
4994 	if (sign == NULL) {
4995 		sign = find_backup_common(osroot, "ufs");
4996 		BAM_DPRINTF((D_EXIST_BACKUP_SIGN, fcn, sign ? sign : "NULL"));
4997 	} else {
4998 		BAM_DPRINTF((D_EXIST_PRIMARY_SIGN, fcn, sign));
4999 	}
5000 
5001 	return (sign);
5002 }
5003 
5004 char *
5005 get_mountpoint(char *special, char *fstype)
5006 {
5007 	FILE		*mntfp;
5008 	struct mnttab	mp = {0};
5009 	struct mnttab	mpref = {0};
5010 	int		error;
5011 	int		ret;
5012 	const char	*fcn = "get_mountpoint()";
5013 
5014 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, special, fstype));
5015 
5016 	mntfp = fopen(MNTTAB, "r");
5017 	error = errno;
5018 	INJECT_ERROR1("MNTTAB_ERR_GET_MNTPT", mntfp = NULL);
5019 	if (mntfp == NULL) {
5020 		bam_error(OPEN_FAIL, MNTTAB, strerror(error));
5021 		return (NULL);
5022 	}
5023 
5024 	mpref.mnt_special = special;
5025 	mpref.mnt_fstype = fstype;
5026 
5027 	ret = getmntany(mntfp, &mp, &mpref);
5028 	INJECT_ERROR1("GET_MOUNTPOINT_MNTANY", ret = 1);
5029 	if (ret != 0) {
5030 		(void) fclose(mntfp);
5031 		BAM_DPRINTF((D_NO_MNTPT, fcn, special, fstype));
5032 		return (NULL);
5033 	}
5034 	(void) fclose(mntfp);
5035 
5036 	assert(mp.mnt_mountp);
5037 
5038 	BAM_DPRINTF((D_GET_MOUNTPOINT_RET, fcn, special, mp.mnt_mountp));
5039 
5040 	return (s_strdup(mp.mnt_mountp));
5041 }
5042 
5043 /*
5044  * Mounts a "legacy" top dataset (if needed)
5045  * Returns:	The mountpoint of the legacy top dataset or NULL on error
5046  * 		mnted returns one of the above values defined for zfs_mnted_t
5047  */
5048 static char *
5049 mount_legacy_dataset(char *pool, zfs_mnted_t *mnted)
5050 {
5051 	char		cmd[PATH_MAX];
5052 	char		tmpmnt[PATH_MAX];
5053 	filelist_t	flist = {0};
5054 	char		*is_mounted;
5055 	struct stat	sb;
5056 	int		ret;
5057 	const char	*fcn = "mount_legacy_dataset()";
5058 
5059 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, pool));
5060 
5061 	*mnted = ZFS_MNT_ERROR;
5062 
5063 	(void) snprintf(cmd, sizeof (cmd),
5064 	    "/sbin/zfs get -Ho value mounted %s",
5065 	    pool);
5066 
5067 	ret = exec_cmd(cmd, &flist);
5068 	INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_CMD", ret = 1);
5069 	if (ret != 0) {
5070 		bam_error(ZFS_MNTED_FAILED, pool);
5071 		return (NULL);
5072 	}
5073 
5074 	INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_OUT", flist.head = NULL);
5075 	if ((flist.head == NULL) || (flist.head != flist.tail)) {
5076 		bam_error(BAD_ZFS_MNTED, pool);
5077 		filelist_free(&flist);
5078 		return (NULL);
5079 	}
5080 
5081 	is_mounted = strtok(flist.head->line, " \t\n");
5082 	INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_STRTOK_YES", is_mounted = "yes");
5083 	INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_STRTOK_NO", is_mounted = "no");
5084 	if (strcmp(is_mounted, "no") != 0) {
5085 		filelist_free(&flist);
5086 		*mnted = LEGACY_ALREADY;
5087 		/* get_mountpoint returns a strdup'ed string */
5088 		BAM_DPRINTF((D_Z_MOUNT_TOP_LEG_ALREADY, fcn, pool));
5089 		return (get_mountpoint(pool, "zfs"));
5090 	}
5091 
5092 	filelist_free(&flist);
5093 
5094 	/*
5095 	 * legacy top dataset is not mounted. Mount it now
5096 	 * First create a mountpoint.
5097 	 */
5098 	(void) snprintf(tmpmnt, sizeof (tmpmnt), "%s.%d",
5099 	    ZFS_LEGACY_MNTPT, getpid());
5100 
5101 	ret = stat(tmpmnt, &sb);
5102 	if (ret == -1) {
5103 		BAM_DPRINTF((D_Z_MOUNT_TOP_LEG_MNTPT_ABS, fcn, pool, tmpmnt));
5104 		ret = mkdirp(tmpmnt, DIR_PERMS);
5105 		INJECT_ERROR1("Z_MOUNT_TOP_LEG_MNTPT_MKDIRP", ret = -1);
5106 		if (ret == -1) {
5107 			bam_error(MKDIR_FAILED, tmpmnt, strerror(errno));
5108 			return (NULL);
5109 		}
5110 	} else {
5111 		BAM_DPRINTF((D_Z_MOUNT_TOP_LEG_MNTPT_PRES, fcn, pool, tmpmnt));
5112 	}
5113 
5114 	(void) snprintf(cmd, sizeof (cmd),
5115 	    "/sbin/mount -F zfs %s %s",
5116 	    pool, tmpmnt);
5117 
5118 	ret = exec_cmd(cmd, NULL);
5119 	INJECT_ERROR1("Z_MOUNT_TOP_LEG_MOUNT_CMD", ret = 1);
5120 	if (ret != 0) {
5121 		bam_error(ZFS_MOUNT_FAILED, pool);
5122 		(void) rmdir(tmpmnt);
5123 		return (NULL);
5124 	}
5125 
5126 	*mnted = LEGACY_MOUNTED;
5127 	BAM_DPRINTF((D_Z_MOUNT_TOP_LEG_MOUNTED, fcn, pool, tmpmnt));
5128 	return (s_strdup(tmpmnt));
5129 }
5130 
5131 /*
5132  * Mounts the top dataset (if needed)
5133  * Returns:	The mountpoint of the top dataset or NULL on error
5134  * 		mnted returns one of the above values defined for zfs_mnted_t
5135  */
5136 static char *
5137 mount_top_dataset(char *pool, zfs_mnted_t *mnted)
5138 {
5139 	char		cmd[PATH_MAX];
5140 	filelist_t	flist = {0};
5141 	char		*is_mounted;
5142 	char		*mntpt;
5143 	char		*zmntpt;
5144 	int		ret;
5145 	const char	*fcn = "mount_top_dataset()";
5146 
5147 	*mnted = ZFS_MNT_ERROR;
5148 
5149 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, pool));
5150 
5151 	/*
5152 	 * First check if the top dataset is a "legacy" dataset
5153 	 */
5154 	(void) snprintf(cmd, sizeof (cmd),
5155 	    "/sbin/zfs get -Ho value mountpoint %s",
5156 	    pool);
5157 	ret = exec_cmd(cmd, &flist);
5158 	INJECT_ERROR1("Z_MOUNT_TOP_GET_MNTPT", ret = 1);
5159 	if (ret != 0) {
5160 		bam_error(ZFS_MNTPT_FAILED, pool);
5161 		return (NULL);
5162 	}
5163 
5164 	if (flist.head && (flist.head == flist.tail)) {
5165 		char *legacy = strtok(flist.head->line, " \t\n");
5166 		if (legacy && strcmp(legacy, "legacy") == 0) {
5167 			filelist_free(&flist);
5168 			BAM_DPRINTF((D_Z_IS_LEGACY, fcn, pool));
5169 			return (mount_legacy_dataset(pool, mnted));
5170 		}
5171 	}
5172 
5173 	filelist_free(&flist);
5174 
5175 	BAM_DPRINTF((D_Z_IS_NOT_LEGACY, fcn, pool));
5176 
5177 	(void) snprintf(cmd, sizeof (cmd),
5178 	    "/sbin/zfs get -Ho value mounted %s",
5179 	    pool);
5180 
5181 	ret = exec_cmd(cmd, &flist);
5182 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED", ret = 1);
5183 	if (ret != 0) {
5184 		bam_error(ZFS_MNTED_FAILED, pool);
5185 		return (NULL);
5186 	}
5187 
5188 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED_VAL", flist.head = NULL);
5189 	if ((flist.head == NULL) || (flist.head != flist.tail)) {
5190 		bam_error(BAD_ZFS_MNTED, pool);
5191 		filelist_free(&flist);
5192 		return (NULL);
5193 	}
5194 
5195 	is_mounted = strtok(flist.head->line, " \t\n");
5196 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED_YES", is_mounted = "yes");
5197 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED_NO", is_mounted = "no");
5198 	if (strcmp(is_mounted, "no") != 0) {
5199 		filelist_free(&flist);
5200 		*mnted = ZFS_ALREADY;
5201 		BAM_DPRINTF((D_Z_MOUNT_TOP_NONLEG_MOUNTED_ALREADY, fcn, pool));
5202 		goto mounted;
5203 	}
5204 
5205 	filelist_free(&flist);
5206 	BAM_DPRINTF((D_Z_MOUNT_TOP_NONLEG_MOUNTED_NOT_ALREADY, fcn, pool));
5207 
5208 	/* top dataset is not mounted. Mount it now */
5209 	(void) snprintf(cmd, sizeof (cmd),
5210 	    "/sbin/zfs mount %s", pool);
5211 	ret = exec_cmd(cmd, NULL);
5212 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_MOUNT_CMD", ret = 1);
5213 	if (ret != 0) {
5214 		bam_error(ZFS_MOUNT_FAILED, pool);
5215 		return (NULL);
5216 	}
5217 	*mnted = ZFS_MOUNTED;
5218 	BAM_DPRINTF((D_Z_MOUNT_TOP_NONLEG_MOUNTED_NOW, fcn, pool));
5219 	/*FALLTHRU*/
5220 mounted:
5221 	/*
5222 	 * Now get the mountpoint
5223 	 */
5224 	(void) snprintf(cmd, sizeof (cmd),
5225 	    "/sbin/zfs get -Ho value mountpoint %s",
5226 	    pool);
5227 
5228 	ret = exec_cmd(cmd, &flist);
5229 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MNTPT_CMD", ret = 1);
5230 	if (ret != 0) {
5231 		bam_error(ZFS_MNTPT_FAILED, pool);
5232 		goto error;
5233 	}
5234 
5235 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MNTPT_OUT", flist.head = NULL);
5236 	if ((flist.head == NULL) || (flist.head != flist.tail)) {
5237 		bam_error(NULL_ZFS_MNTPT, pool);
5238 		goto error;
5239 	}
5240 
5241 	mntpt = strtok(flist.head->line, " \t\n");
5242 	INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MNTPT_STRTOK", mntpt = "foo");
5243 	if (*mntpt != '/') {
5244 		bam_error(BAD_ZFS_MNTPT, pool, mntpt);
5245 		goto error;
5246 	}
5247 	zmntpt = s_strdup(mntpt);
5248 
5249 	filelist_free(&flist);
5250 
5251 	BAM_DPRINTF((D_Z_MOUNT_TOP_NONLEG_MNTPT, fcn, pool, zmntpt));
5252 
5253 	return (zmntpt);
5254 
5255 error:
5256 	filelist_free(&flist);
5257 	(void) umount_top_dataset(pool, *mnted, NULL);
5258 	BAM_DPRINTF((D_RETURN_FAILURE, fcn));
5259 	return (NULL);
5260 }
5261 
5262 static int
5263 umount_top_dataset(char *pool, zfs_mnted_t mnted, char *mntpt)
5264 {
5265 	char		cmd[PATH_MAX];
5266 	int		ret;
5267 	const char	*fcn = "umount_top_dataset()";
5268 
5269 	INJECT_ERROR1("Z_UMOUNT_TOP_INVALID_STATE", mnted = ZFS_MNT_ERROR);
5270 	switch (mnted) {
5271 	case LEGACY_ALREADY:
5272 	case ZFS_ALREADY:
5273 		/* nothing to do */
5274 		BAM_DPRINTF((D_Z_UMOUNT_TOP_ALREADY_NOP, fcn, pool,
5275 		    mntpt ? mntpt : "NULL"));
5276 		free(mntpt);
5277 		return (BAM_SUCCESS);
5278 	case LEGACY_MOUNTED:
5279 		(void) snprintf(cmd, sizeof (cmd),
5280 		    "/sbin/umount %s", pool);
5281 		ret = exec_cmd(cmd, NULL);
5282 		INJECT_ERROR1("Z_UMOUNT_TOP_LEGACY_UMOUNT_FAIL", ret = 1);
5283 		if (ret != 0) {
5284 			bam_error(UMOUNT_FAILED, pool);
5285 			free(mntpt);
5286 			return (BAM_ERROR);
5287 		}
5288 		if (mntpt)
5289 			(void) rmdir(mntpt);
5290 		free(mntpt);
5291 		BAM_DPRINTF((D_Z_UMOUNT_TOP_LEGACY, fcn, pool));
5292 		return (BAM_SUCCESS);
5293 	case ZFS_MOUNTED:
5294 		free(mntpt);
5295 		(void) snprintf(cmd, sizeof (cmd),
5296 		    "/sbin/zfs unmount %s", pool);
5297 		ret = exec_cmd(cmd, NULL);
5298 		INJECT_ERROR1("Z_UMOUNT_TOP_NONLEG_UMOUNT_FAIL", ret = 1);
5299 		if (ret != 0) {
5300 			bam_error(UMOUNT_FAILED, pool);
5301 			return (BAM_ERROR);
5302 		}
5303 		BAM_DPRINTF((D_Z_UMOUNT_TOP_NONLEG, fcn, pool));
5304 		return (BAM_SUCCESS);
5305 	default:
5306 		bam_error(INT_BAD_MNTSTATE, pool);
5307 		return (BAM_ERROR);
5308 	}
5309 	/*NOTREACHED*/
5310 }
5311 
5312 /*
5313  * For ZFS, osdev can be one of two forms
5314  * It can be a "special" file as seen in mnttab: rpool/ROOT/szboot_0402
5315  * It can be a /dev/[r]dsk special file. We handle both instances
5316  */
5317 static char *
5318 get_pool(char *osdev)
5319 {
5320 	char		cmd[PATH_MAX];
5321 	char		buf[PATH_MAX];
5322 	filelist_t	flist = {0};
5323 	char		*pool;
5324 	char		*cp;
5325 	char		*slash;
5326 	int		ret;
5327 	const char	*fcn = "get_pool()";
5328 
5329 	INJECT_ERROR1("GET_POOL_OSDEV", osdev = NULL);
5330 	if (osdev == NULL) {
5331 		bam_error(GET_POOL_OSDEV_NULL);
5332 		return (NULL);
5333 	}
5334 
5335 	BAM_DPRINTF((D_GET_POOL_OSDEV, fcn, osdev));
5336 
5337 	if (osdev[0] != '/') {
5338 		(void) strlcpy(buf, osdev, sizeof (buf));
5339 		slash = strchr(buf, '/');
5340 		if (slash)
5341 			*slash = '\0';
5342 		pool = s_strdup(buf);
5343 		BAM_DPRINTF((D_GET_POOL_RET, fcn, pool));
5344 		return (pool);
5345 	} else if (strncmp(osdev, "/dev/dsk/", strlen("/dev/dsk/")) != 0 &&
5346 	    strncmp(osdev, "/dev/rdsk/", strlen("/dev/rdsk/")) != 0) {
5347 		bam_error(GET_POOL_BAD_OSDEV, osdev);
5348 		return (NULL);
5349 	}
5350 
5351 	(void) snprintf(cmd, sizeof (cmd),
5352 	    "/usr/sbin/fstyp -a %s 2>/dev/null | /bin/grep '^name:'",
5353 	    osdev);
5354 
5355 	ret = exec_cmd(cmd, &flist);
5356 	INJECT_ERROR1("GET_POOL_FSTYP", ret = 1);
5357 	if (ret != 0) {
5358 		bam_error(FSTYP_A_FAILED, osdev);
5359 		return (NULL);
5360 	}
5361 
5362 	INJECT_ERROR1("GET_POOL_FSTYP_OUT", flist.head = NULL);
5363 	if ((flist.head == NULL) || (flist.head != flist.tail)) {
5364 		bam_error(NULL_FSTYP_A, osdev);
5365 		filelist_free(&flist);
5366 		return (NULL);
5367 	}
5368 
5369 	(void) strtok(flist.head->line, "'");
5370 	cp = strtok(NULL, "'");
5371 	INJECT_ERROR1("GET_POOL_FSTYP_STRTOK", cp = NULL);
5372 	if (cp == NULL) {
5373 		bam_error(BAD_FSTYP_A, osdev);
5374 		filelist_free(&flist);
5375 		return (NULL);
5376 	}
5377 
5378 	pool = s_strdup(cp);
5379 
5380 	filelist_free(&flist);
5381 
5382 	BAM_DPRINTF((D_GET_POOL_RET, fcn, pool));
5383 
5384 	return (pool);
5385 }
5386 
5387 static char *
5388 find_zfs_existing(char *osdev)
5389 {
5390 	char		*pool;
5391 	zfs_mnted_t	mnted;
5392 	char		*mntpt;
5393 	char		*sign;
5394 	const char	*fcn = "find_zfs_existing()";
5395 
5396 	pool = get_pool(osdev);
5397 	INJECT_ERROR1("ZFS_FIND_EXIST_POOL", pool = NULL);
5398 	if (pool == NULL) {
5399 		bam_error(ZFS_GET_POOL_FAILED, osdev);
5400 		return (NULL);
5401 	}
5402 
5403 	mntpt = mount_top_dataset(pool, &mnted);
5404 	INJECT_ERROR1("ZFS_FIND_EXIST_MOUNT_TOP", mntpt = NULL);
5405 	if (mntpt == NULL) {
5406 		bam_error(ZFS_MOUNT_TOP_DATASET_FAILED, pool);
5407 		free(pool);
5408 		return (NULL);
5409 	}
5410 
5411 	sign = find_primary_common(mntpt, "zfs");
5412 	if (sign == NULL) {
5413 		sign = find_backup_common(mntpt, "zfs");
5414 		BAM_DPRINTF((D_EXIST_BACKUP_SIGN, fcn, sign ? sign : "NULL"));
5415 	} else {
5416 		BAM_DPRINTF((D_EXIST_PRIMARY_SIGN, fcn, sign));
5417 	}
5418 
5419 	(void) umount_top_dataset(pool, mnted, mntpt);
5420 
5421 	free(pool);
5422 
5423 	return (sign);
5424 }
5425 
5426 static char *
5427 find_existing_sign(char *osroot, char *osdev, char *fstype)
5428 {
5429 	const char		*fcn = "find_existing_sign()";
5430 
5431 	INJECT_ERROR1("FIND_EXIST_NOTSUP_FS", fstype = "foofs");
5432 	if (strcmp(fstype, "ufs") == 0) {
5433 		BAM_DPRINTF((D_CHECK_UFS_EXIST_SIGN, fcn));
5434 		return (find_ufs_existing(osroot));
5435 	} else if (strcmp(fstype, "zfs") == 0) {
5436 		BAM_DPRINTF((D_CHECK_ZFS_EXIST_SIGN, fcn));
5437 		return (find_zfs_existing(osdev));
5438 	} else {
5439 		bam_error(GRUBSIGN_NOTSUP, fstype);
5440 		return (NULL);
5441 	}
5442 }
5443 
5444 #define	MH_HASH_SZ	16
5445 
5446 typedef enum {
5447 	MH_ERROR = -1,
5448 	MH_NOMATCH,
5449 	MH_MATCH
5450 } mh_search_t;
5451 
5452 typedef struct mcache {
5453 	char	*mc_special;
5454 	char	*mc_mntpt;
5455 	char	*mc_fstype;
5456 	struct mcache *mc_next;
5457 } mcache_t;
5458 
5459 typedef struct mhash {
5460 	mcache_t *mh_hash[MH_HASH_SZ];
5461 } mhash_t;
5462 
5463 static int
5464 mhash_fcn(char *key)
5465 {
5466 	int		i;
5467 	uint64_t	sum = 0;
5468 
5469 	for (i = 0; key[i] != '\0'; i++) {
5470 		sum += (uchar_t)key[i];
5471 	}
5472 
5473 	sum %= MH_HASH_SZ;
5474 
5475 	assert(sum < MH_HASH_SZ);
5476 
5477 	return (sum);
5478 }
5479 
5480 static mhash_t *
5481 cache_mnttab(void)
5482 {
5483 	FILE		*mfp;
5484 	struct extmnttab mnt;
5485 	mcache_t	*mcp;
5486 	mhash_t		*mhp;
5487 	char		*ctds;
5488 	int		idx;
5489 	int		error;
5490 	char		*special_dup;
5491 	const char	*fcn = "cache_mnttab()";
5492 
5493 	mfp = fopen(MNTTAB, "r");
5494 	error = errno;
5495 	INJECT_ERROR1("CACHE_MNTTAB_MNTTAB_ERR", mfp = NULL);
5496 	if (mfp == NULL) {
5497 		bam_error(OPEN_FAIL, MNTTAB, strerror(error));
5498 		return (NULL);
5499 	}
5500 
5501 	mhp = s_calloc(1, sizeof (mhash_t));
5502 
5503 	resetmnttab(mfp);
5504 
5505 	while (getextmntent(mfp, &mnt, sizeof (mnt)) == 0) {
5506 		/* only cache ufs */
5507 		if (strcmp(mnt.mnt_fstype, "ufs") != 0)
5508 			continue;
5509 
5510 		/* basename() modifies its arg, so dup it */
5511 		special_dup = s_strdup(mnt.mnt_special);
5512 		ctds = basename(special_dup);
5513 
5514 		mcp = s_calloc(1, sizeof (mcache_t));
5515 		mcp->mc_special = s_strdup(ctds);
5516 		mcp->mc_mntpt = s_strdup(mnt.mnt_mountp);
5517 		mcp->mc_fstype = s_strdup(mnt.mnt_fstype);
5518 		BAM_DPRINTF((D_CACHE_MNTS, fcn, ctds,
5519 		    mnt.mnt_mountp, mnt.mnt_fstype));
5520 		idx = mhash_fcn(ctds);
5521 		mcp->mc_next = mhp->mh_hash[idx];
5522 		mhp->mh_hash[idx] = mcp;
5523 		free(special_dup);
5524 	}
5525 
5526 	(void) fclose(mfp);
5527 
5528 	return (mhp);
5529 }
5530 
5531 static void
5532 free_mnttab(mhash_t *mhp)
5533 {
5534 	mcache_t	*mcp;
5535 	int		i;
5536 
5537 	for (i = 0; i < MH_HASH_SZ; i++) {
5538 		/*LINTED*/
5539 		while (mcp = mhp->mh_hash[i]) {
5540 			mhp->mh_hash[i] = mcp->mc_next;
5541 			free(mcp->mc_special);
5542 			free(mcp->mc_mntpt);
5543 			free(mcp->mc_fstype);
5544 			free(mcp);
5545 		}
5546 	}
5547 
5548 	for (i = 0; i < MH_HASH_SZ; i++) {
5549 		assert(mhp->mh_hash[i] == NULL);
5550 	}
5551 	free(mhp);
5552 }
5553 
5554 static mh_search_t
5555 search_hash(mhash_t *mhp, char *special, char **mntpt)
5556 {
5557 	int		idx;
5558 	mcache_t	*mcp;
5559 	const char 	*fcn = "search_hash()";
5560 
5561 	assert(mntpt);
5562 
5563 	*mntpt = NULL;
5564 
5565 	INJECT_ERROR1("SEARCH_HASH_FULL_PATH", special = "/foo");
5566 	if (strchr(special, '/')) {
5567 		bam_error(INVALID_MHASH_KEY, special);
5568 		return (MH_ERROR);
5569 	}
5570 
5571 	idx = mhash_fcn(special);
5572 
5573 	for (mcp = mhp->mh_hash[idx]; mcp; mcp = mcp->mc_next) {
5574 		if (strcmp(mcp->mc_special, special) == 0)
5575 			break;
5576 	}
5577 
5578 	if (mcp == NULL) {
5579 		BAM_DPRINTF((D_MNTTAB_HASH_NOMATCH, fcn, special));
5580 		return (MH_NOMATCH);
5581 	}
5582 
5583 	assert(strcmp(mcp->mc_fstype, "ufs") == 0);
5584 	*mntpt = mcp->mc_mntpt;
5585 	BAM_DPRINTF((D_MNTTAB_HASH_MATCH, fcn, special));
5586 	return (MH_MATCH);
5587 }
5588 
5589 static int
5590 check_add_ufs_sign_to_list(FILE *tfp, char *mntpt)
5591 {
5592 	char		*sign;
5593 	char		*signline;
5594 	char		signbuf[MAXNAMELEN];
5595 	int		len;
5596 	int		error;
5597 	const char	*fcn = "check_add_ufs_sign_to_list()";
5598 
5599 	/* safe to specify NULL as "osdev" arg for UFS */
5600 	sign = find_existing_sign(mntpt, NULL, "ufs");
5601 	if (sign == NULL) {
5602 		/* No existing signature, nothing to add to list */
5603 		BAM_DPRINTF((D_NO_SIGN_TO_LIST, fcn, mntpt));
5604 		return (0);
5605 	}
5606 
5607 	(void) snprintf(signbuf, sizeof (signbuf), "%s\n", sign);
5608 	signline = signbuf;
5609 
5610 	INJECT_ERROR1("UFS_MNTPT_SIGN_NOTUFS", signline = "pool_rpool10\n");
5611 	if (strncmp(signline, GRUBSIGN_UFS_PREFIX,
5612 	    strlen(GRUBSIGN_UFS_PREFIX))) {
5613 		bam_error(INVALID_UFS_SIGNATURE, sign);
5614 		free(sign);
5615 		/* ignore invalid signatures */
5616 		return (0);
5617 	}
5618 
5619 	len = fputs(signline, tfp);
5620 	error = errno;
5621 	INJECT_ERROR1("SIGN_LIST_PUTS_ERROR", len = 0);
5622 	if (len != strlen(signline)) {
5623 		bam_error(SIGN_LIST_FPUTS_ERR, sign, strerror(error));
5624 		free(sign);
5625 		return (-1);
5626 	}
5627 
5628 	free(sign);
5629 
5630 	BAM_DPRINTF((D_SIGN_LIST_PUTS_DONE, fcn, mntpt));
5631 	return (0);
5632 }
5633 
5634 /*
5635  * slice is a basename not a full pathname
5636  */
5637 static int
5638 process_slice_common(char *slice, FILE *tfp, mhash_t *mhp, char *tmpmnt)
5639 {
5640 	int		ret;
5641 	char		cmd[PATH_MAX];
5642 	char		path[PATH_MAX];
5643 	struct stat	sbuf;
5644 	char		*mntpt;
5645 	filelist_t	flist = {0};
5646 	char		*fstype;
5647 	char		blkslice[PATH_MAX];
5648 	const char	*fcn = "process_slice_common()";
5649 
5650 
5651 	ret = search_hash(mhp, slice, &mntpt);
5652 	switch (ret) {
5653 		case MH_MATCH:
5654 			if (check_add_ufs_sign_to_list(tfp, mntpt) == -1)
5655 				return (-1);
5656 			else
5657 				return (0);
5658 		case MH_NOMATCH:
5659 			break;
5660 		case MH_ERROR:
5661 		default:
5662 			return (-1);
5663 	}
5664 
5665 	(void) snprintf(path, sizeof (path), "/dev/rdsk/%s", slice);
5666 	if (stat(path, &sbuf) == -1) {
5667 		BAM_DPRINTF((D_SLICE_ENOENT, fcn, path));
5668 		return (0);
5669 	}
5670 
5671 	/* Check if ufs */
5672 	(void) snprintf(cmd, sizeof (cmd),
5673 	    "/usr/sbin/fstyp /dev/rdsk/%s 2>/dev/null",
5674 	    slice);
5675 
5676 	if (exec_cmd(cmd, &flist) != 0) {
5677 		if (bam_verbose)
5678 			bam_print(FSTYP_FAILED, slice);
5679 		return (0);
5680 	}
5681 
5682 	if ((flist.head == NULL) || (flist.head != flist.tail)) {
5683 		if (bam_verbose)
5684 			bam_print(FSTYP_BAD, slice);
5685 		filelist_free(&flist);
5686 		return (0);
5687 	}
5688 
5689 	fstype = strtok(flist.head->line, " \t\n");
5690 	if (fstype == NULL || strcmp(fstype, "ufs") != 0) {
5691 		if (bam_verbose)
5692 			bam_print(NOT_UFS_SLICE, slice, fstype);
5693 		filelist_free(&flist);
5694 		return (0);
5695 	}
5696 
5697 	filelist_free(&flist);
5698 
5699 	/*
5700 	 * Since we are mounting the filesystem read-only, the
5701 	 * the last mount field of the superblock is unchanged
5702 	 * and does not need to be fixed up post-mount;
5703 	 */
5704 
5705 	(void) snprintf(blkslice, sizeof (blkslice), "/dev/dsk/%s",
5706 	    slice);
5707 
5708 	(void) snprintf(cmd, sizeof (cmd),
5709 	    "/usr/sbin/mount -F ufs -o ro %s %s "
5710 	    "> /dev/null 2>&1", blkslice, tmpmnt);
5711 
5712 	if (exec_cmd(cmd, NULL) != 0) {
5713 		if (bam_verbose)
5714 			bam_print(MOUNT_FAILED, blkslice, "ufs");
5715 		return (0);
5716 	}
5717 
5718 	ret = check_add_ufs_sign_to_list(tfp, tmpmnt);
5719 
5720 	(void) snprintf(cmd, sizeof (cmd),
5721 	    "/usr/sbin/umount -f %s > /dev/null 2>&1",
5722 	    tmpmnt);
5723 
5724 	if (exec_cmd(cmd, NULL) != 0) {
5725 		bam_print(UMOUNT_FAILED, slice);
5726 		return (0);
5727 	}
5728 
5729 	return (ret);
5730 }
5731 
5732 static int
5733 process_vtoc_slices(
5734 	char *s0,
5735 	struct vtoc *vtoc,
5736 	FILE *tfp,
5737 	mhash_t *mhp,
5738 	char *tmpmnt)
5739 {
5740 	int		idx;
5741 	char		slice[PATH_MAX];
5742 	size_t		len;
5743 	char		*cp;
5744 	const char	*fcn = "process_vtoc_slices()";
5745 
5746 	len = strlen(s0);
5747 
5748 	assert(s0[len - 2] == 's' && s0[len - 1] == '0');
5749 
5750 	s0[len - 1] = '\0';
5751 
5752 	(void) strlcpy(slice, s0, sizeof (slice));
5753 
5754 	s0[len - 1] = '0';
5755 
5756 	cp = slice + len - 1;
5757 
5758 	for (idx = 0; idx < vtoc->v_nparts; idx++) {
5759 
5760 		(void) snprintf(cp, sizeof (slice) - (len - 1), "%u", idx);
5761 
5762 		if (vtoc->v_part[idx].p_size == 0) {
5763 			BAM_DPRINTF((D_VTOC_SIZE_ZERO, fcn, slice));
5764 			continue;
5765 		}
5766 
5767 		/* Skip "SWAP", "USR", "BACKUP", "VAR", "HOME", "ALTSCTR" */
5768 		switch (vtoc->v_part[idx].p_tag) {
5769 		case V_SWAP:
5770 		case V_USR:
5771 		case V_BACKUP:
5772 		case V_VAR:
5773 		case V_HOME:
5774 		case V_ALTSCTR:
5775 			BAM_DPRINTF((D_VTOC_NOT_ROOT_TAG, fcn, slice));
5776 			continue;
5777 		default:
5778 			BAM_DPRINTF((D_VTOC_ROOT_TAG, fcn, slice));
5779 			break;
5780 		}
5781 
5782 		/* skip unmountable and readonly slices */
5783 		switch (vtoc->v_part[idx].p_flag) {
5784 		case V_UNMNT:
5785 		case V_RONLY:
5786 			BAM_DPRINTF((D_VTOC_NOT_RDWR_FLAG, fcn, slice));
5787 			continue;
5788 		default:
5789 			BAM_DPRINTF((D_VTOC_RDWR_FLAG, fcn, slice));
5790 			break;
5791 		}
5792 
5793 		if (process_slice_common(slice, tfp, mhp, tmpmnt) == -1) {
5794 			return (-1);
5795 		}
5796 	}
5797 
5798 	return (0);
5799 }
5800 
5801 static int
5802 process_efi_slices(
5803 	char *s0,
5804 	struct dk_gpt *efi,
5805 	FILE *tfp,
5806 	mhash_t *mhp,
5807 	char *tmpmnt)
5808 {
5809 	int		idx;
5810 	char		slice[PATH_MAX];
5811 	size_t		len;
5812 	char		*cp;
5813 	const char	*fcn = "process_efi_slices()";
5814 
5815 	len = strlen(s0);
5816 
5817 	assert(s0[len - 2] == 's' && s0[len - 1] == '0');
5818 
5819 	s0[len - 1] = '\0';
5820 
5821 	(void) strlcpy(slice, s0, sizeof (slice));
5822 
5823 	s0[len - 1] = '0';
5824 
5825 	cp = slice + len - 1;
5826 
5827 	for (idx = 0; idx < efi->efi_nparts; idx++) {
5828 
5829 		(void) snprintf(cp, sizeof (slice) - (len - 1), "%u", idx);
5830 
5831 		if (efi->efi_parts[idx].p_size == 0) {
5832 			BAM_DPRINTF((D_EFI_SIZE_ZERO, fcn, slice));
5833 			continue;
5834 		}
5835 
5836 		/* Skip "SWAP", "USR", "BACKUP", "VAR", "HOME", "ALTSCTR" */
5837 		switch (efi->efi_parts[idx].p_tag) {
5838 		case V_SWAP:
5839 		case V_USR:
5840 		case V_BACKUP:
5841 		case V_VAR:
5842 		case V_HOME:
5843 		case V_ALTSCTR:
5844 			BAM_DPRINTF((D_EFI_NOT_ROOT_TAG, fcn, slice));
5845 			continue;
5846 		default:
5847 			BAM_DPRINTF((D_EFI_ROOT_TAG, fcn, slice));
5848 			break;
5849 		}
5850 
5851 		/* skip unmountable and readonly slices */
5852 		switch (efi->efi_parts[idx].p_flag) {
5853 		case V_UNMNT:
5854 		case V_RONLY:
5855 			BAM_DPRINTF((D_EFI_NOT_RDWR_FLAG, fcn, slice));
5856 			continue;
5857 		default:
5858 			BAM_DPRINTF((D_EFI_RDWR_FLAG, fcn, slice));
5859 			break;
5860 		}
5861 
5862 		if (process_slice_common(slice, tfp, mhp, tmpmnt) == -1) {
5863 			return (-1);
5864 		}
5865 	}
5866 
5867 	return (0);
5868 }
5869 
5870 /*
5871  * s0 is a basename not a full path
5872  */
5873 static int
5874 process_slice0(char *s0, FILE *tfp, mhash_t *mhp, char *tmpmnt)
5875 {
5876 	struct vtoc		vtoc;
5877 	struct dk_gpt		*efi;
5878 	char			s0path[PATH_MAX];
5879 	struct stat		sbuf;
5880 	int			e_flag;
5881 	int			v_flag;
5882 	int			retval;
5883 	int			err;
5884 	int			fd;
5885 	const char		*fcn = "process_slice0()";
5886 
5887 	(void) snprintf(s0path, sizeof (s0path), "/dev/rdsk/%s", s0);
5888 
5889 	if (stat(s0path, &sbuf) == -1) {
5890 		BAM_DPRINTF((D_SLICE0_ENOENT, fcn, s0path));
5891 		return (0);
5892 	}
5893 
5894 	fd = open(s0path, O_NONBLOCK|O_RDONLY);
5895 	if (fd == -1) {
5896 		bam_error(OPEN_FAIL, s0path, strerror(errno));
5897 		return (0);
5898 	}
5899 
5900 	e_flag = v_flag = 0;
5901 	retval = ((err = read_vtoc(fd, &vtoc)) >= 0) ? 0 : err;
5902 	switch (retval) {
5903 		case VT_EIO:
5904 			BAM_DPRINTF((D_VTOC_READ_FAIL, fcn, s0path));
5905 			break;
5906 		case VT_EINVAL:
5907 			BAM_DPRINTF((D_VTOC_INVALID, fcn, s0path));
5908 			break;
5909 		case VT_ERROR:
5910 			BAM_DPRINTF((D_VTOC_UNKNOWN_ERR, fcn, s0path));
5911 			break;
5912 		case VT_ENOTSUP:
5913 			e_flag = 1;
5914 			BAM_DPRINTF((D_VTOC_NOTSUP, fcn, s0path));
5915 			break;
5916 		case 0:
5917 			v_flag = 1;
5918 			BAM_DPRINTF((D_VTOC_READ_SUCCESS, fcn, s0path));
5919 			break;
5920 		default:
5921 			BAM_DPRINTF((D_VTOC_UNKNOWN_RETCODE, fcn, s0path));
5922 			break;
5923 	}
5924 
5925 
5926 	if (e_flag) {
5927 		e_flag = 0;
5928 		retval = ((err = efi_alloc_and_read(fd, &efi)) >= 0) ? 0 : err;
5929 		switch (retval) {
5930 		case VT_EIO:
5931 			BAM_DPRINTF((D_EFI_READ_FAIL, fcn, s0path));
5932 			break;
5933 		case VT_EINVAL:
5934 			BAM_DPRINTF((D_EFI_INVALID, fcn, s0path));
5935 			break;
5936 		case VT_ERROR:
5937 			BAM_DPRINTF((D_EFI_UNKNOWN_ERR, fcn, s0path));
5938 			break;
5939 		case VT_ENOTSUP:
5940 			BAM_DPRINTF((D_EFI_NOTSUP, fcn, s0path));
5941 			break;
5942 		case 0:
5943 			e_flag = 1;
5944 			BAM_DPRINTF((D_EFI_READ_SUCCESS, fcn, s0path));
5945 			break;
5946 		default:
5947 			BAM_DPRINTF((D_EFI_UNKNOWN_RETCODE, fcn, s0path));
5948 			break;
5949 		}
5950 	}
5951 
5952 	(void) close(fd);
5953 
5954 	if (v_flag) {
5955 		retval = process_vtoc_slices(s0,
5956 		    &vtoc, tfp, mhp, tmpmnt);
5957 	} else if (e_flag) {
5958 		retval = process_efi_slices(s0,
5959 		    efi, tfp, mhp, tmpmnt);
5960 	} else {
5961 		BAM_DPRINTF((D_NOT_VTOC_OR_EFI, fcn, s0path));
5962 		return (0);
5963 	}
5964 
5965 	return (retval);
5966 }
5967 
5968 /*
5969  * Find and create a list of all existing UFS boot signatures
5970  */
5971 static int
5972 FindAllUfsSignatures(void)
5973 {
5974 	mhash_t		*mnttab_hash;
5975 	DIR		*dirp = NULL;
5976 	struct dirent	*dp;
5977 	char		tmpmnt[PATH_MAX];
5978 	char		cmd[PATH_MAX];
5979 	struct stat	sb;
5980 	int		fd;
5981 	FILE		*tfp;
5982 	size_t		len;
5983 	int		ret;
5984 	int		error;
5985 	const char	*fcn = "FindAllUfsSignatures()";
5986 
5987 	if (stat(UFS_SIGNATURE_LIST, &sb) != -1)  {
5988 		bam_print(SIGNATURE_LIST_EXISTS, UFS_SIGNATURE_LIST);
5989 		return (0);
5990 	}
5991 
5992 	fd = open(UFS_SIGNATURE_LIST".tmp",
5993 	    O_RDWR|O_CREAT|O_TRUNC, 0644);
5994 	error = errno;
5995 	INJECT_ERROR1("SIGN_LIST_TMP_TRUNC", fd = -1);
5996 	if (fd == -1) {
5997 		bam_error(OPEN_FAIL, UFS_SIGNATURE_LIST".tmp", strerror(error));
5998 		return (-1);
5999 	}
6000 
6001 	ret = close(fd);
6002 	error = errno;
6003 	INJECT_ERROR1("SIGN_LIST_TMP_CLOSE", ret = -1);
6004 	if (ret == -1) {
6005 		bam_error(CLOSE_FAIL, UFS_SIGNATURE_LIST".tmp",
6006 		    strerror(error));
6007 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6008 		return (-1);
6009 	}
6010 
6011 	tfp = fopen(UFS_SIGNATURE_LIST".tmp", "a");
6012 	error = errno;
6013 	INJECT_ERROR1("SIGN_LIST_APPEND_FOPEN", tfp = NULL);
6014 	if (tfp == NULL) {
6015 		bam_error(OPEN_FAIL, UFS_SIGNATURE_LIST".tmp", strerror(error));
6016 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6017 		return (-1);
6018 	}
6019 
6020 	mnttab_hash = cache_mnttab();
6021 	INJECT_ERROR1("CACHE_MNTTAB_ERROR", mnttab_hash = NULL);
6022 	if (mnttab_hash == NULL) {
6023 		(void) fclose(tfp);
6024 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6025 		bam_error(CACHE_MNTTAB_FAIL, fcn);
6026 		return (-1);
6027 	}
6028 
6029 	(void) snprintf(tmpmnt, sizeof (tmpmnt),
6030 	    "/tmp/bootadm_ufs_sign_mnt.%d", getpid());
6031 	(void) unlink(tmpmnt);
6032 
6033 	ret = mkdirp(tmpmnt, DIR_PERMS);
6034 	error = errno;
6035 	INJECT_ERROR1("MKDIRP_SIGN_MNT", ret = -1);
6036 	if (ret == -1) {
6037 		bam_error(MKDIR_FAILED, tmpmnt, strerror(error));
6038 		free_mnttab(mnttab_hash);
6039 		(void) fclose(tfp);
6040 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6041 		return (-1);
6042 	}
6043 
6044 	dirp = opendir("/dev/rdsk");
6045 	error = errno;
6046 	INJECT_ERROR1("OPENDIR_DEV_RDSK", dirp = NULL);
6047 	if (dirp == NULL) {
6048 		bam_error(OPENDIR_FAILED, "/dev/rdsk", strerror(error));
6049 		goto fail;
6050 	}
6051 
6052 	while (dp = readdir(dirp)) {
6053 		if (strcmp(dp->d_name, ".") == 0 ||
6054 		    strcmp(dp->d_name, "..") == 0)
6055 			continue;
6056 
6057 		/*
6058 		 * we only look for the s0 slice. This is guranteed to
6059 		 * have 's' at len - 2.
6060 		 */
6061 		len = strlen(dp->d_name);
6062 		if (dp->d_name[len - 2 ] != 's' || dp->d_name[len - 1] != '0') {
6063 			BAM_DPRINTF((D_SKIP_SLICE_NOTZERO, fcn, dp->d_name));
6064 			continue;
6065 		}
6066 
6067 		ret = process_slice0(dp->d_name, tfp, mnttab_hash, tmpmnt);
6068 		INJECT_ERROR1("PROCESS_S0_FAIL", ret = -1);
6069 		if (ret == -1)
6070 			goto fail;
6071 	}
6072 
6073 	(void) closedir(dirp);
6074 	free_mnttab(mnttab_hash);
6075 	(void) rmdir(tmpmnt);
6076 
6077 	ret = fclose(tfp);
6078 	error = errno;
6079 	INJECT_ERROR1("FCLOSE_SIGNLIST_TMP", ret = EOF);
6080 	if (ret == EOF) {
6081 		bam_error(CLOSE_FAIL, UFS_SIGNATURE_LIST".tmp",
6082 		    strerror(error));
6083 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6084 		return (-1);
6085 	}
6086 
6087 	/* We have a list of existing GRUB signatures. Sort it first */
6088 	(void) snprintf(cmd, sizeof (cmd),
6089 	    "/usr/bin/sort -u %s.tmp > %s.sorted",
6090 	    UFS_SIGNATURE_LIST, UFS_SIGNATURE_LIST);
6091 
6092 	ret = exec_cmd(cmd, NULL);
6093 	INJECT_ERROR1("SORT_SIGN_LIST", ret = 1);
6094 	if (ret != 0) {
6095 		bam_error(GRUBSIGN_SORT_FAILED);
6096 		(void) unlink(UFS_SIGNATURE_LIST".sorted");
6097 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6098 		return (-1);
6099 	}
6100 
6101 	(void) unlink(UFS_SIGNATURE_LIST".tmp");
6102 
6103 	ret = rename(UFS_SIGNATURE_LIST".sorted", UFS_SIGNATURE_LIST);
6104 	error = errno;
6105 	INJECT_ERROR1("RENAME_TMP_SIGNLIST", ret = -1);
6106 	if (ret == -1) {
6107 		bam_error(RENAME_FAIL, UFS_SIGNATURE_LIST, strerror(error));
6108 		(void) unlink(UFS_SIGNATURE_LIST".sorted");
6109 		return (-1);
6110 	}
6111 
6112 	if (stat(UFS_SIGNATURE_LIST, &sb) == 0 && sb.st_size == 0) {
6113 		BAM_DPRINTF((D_ZERO_LEN_SIGNLIST, fcn, UFS_SIGNATURE_LIST));
6114 	}
6115 
6116 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6117 	return (0);
6118 
6119 fail:
6120 	if (dirp)
6121 		(void) closedir(dirp);
6122 	free_mnttab(mnttab_hash);
6123 	(void) rmdir(tmpmnt);
6124 	(void) fclose(tfp);
6125 	(void) unlink(UFS_SIGNATURE_LIST".tmp");
6126 	BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6127 	return (-1);
6128 }
6129 
6130 static char *
6131 create_ufs_sign(void)
6132 {
6133 	struct stat	sb;
6134 	int		signnum = -1;
6135 	char		tmpsign[MAXNAMELEN + 1];
6136 	char		*numstr;
6137 	int		i;
6138 	FILE		*tfp;
6139 	int		ret;
6140 	int		error;
6141 	const char	*fcn = "create_ufs_sign()";
6142 
6143 	bam_print(SEARCHING_UFS_SIGN);
6144 
6145 	ret = FindAllUfsSignatures();
6146 	INJECT_ERROR1("FIND_ALL_UFS", ret = -1);
6147 	if (ret == -1) {
6148 		bam_error(ERR_FIND_UFS_SIGN);
6149 		return (NULL);
6150 	}
6151 
6152 	/* Make sure the list exists and is owned by root */
6153 	INJECT_ERROR1("SIGNLIST_NOT_CREATED",
6154 	    (void) unlink(UFS_SIGNATURE_LIST));
6155 	if (stat(UFS_SIGNATURE_LIST, &sb) == -1 || sb.st_uid != 0) {
6156 		(void) unlink(UFS_SIGNATURE_LIST);
6157 		bam_error(UFS_SIGNATURE_LIST_MISS, UFS_SIGNATURE_LIST);
6158 		return (NULL);
6159 	}
6160 
6161 	if (sb.st_size == 0) {
6162 		bam_print(GRUBSIGN_UFS_NONE);
6163 		i = 0;
6164 		goto found;
6165 	}
6166 
6167 	/* The signature list was sorted when it was created */
6168 	tfp = fopen(UFS_SIGNATURE_LIST, "r");
6169 	error = errno;
6170 	INJECT_ERROR1("FOPEN_SIGN_LIST", tfp = NULL);
6171 	if (tfp == NULL) {
6172 		bam_error(UFS_SIGNATURE_LIST_OPENERR,
6173 		    UFS_SIGNATURE_LIST, strerror(error));
6174 		(void) unlink(UFS_SIGNATURE_LIST);
6175 		return (NULL);
6176 	}
6177 
6178 	for (i = 0; s_fgets(tmpsign, sizeof (tmpsign), tfp); i++) {
6179 
6180 		if (strncmp(tmpsign, GRUBSIGN_UFS_PREFIX,
6181 		    strlen(GRUBSIGN_UFS_PREFIX)) != 0) {
6182 			(void) fclose(tfp);
6183 			(void) unlink(UFS_SIGNATURE_LIST);
6184 			bam_error(UFS_BADSIGN, tmpsign);
6185 			return (NULL);
6186 		}
6187 		numstr = tmpsign + strlen(GRUBSIGN_UFS_PREFIX);
6188 
6189 		if (numstr[0] == '\0' || !isdigit(numstr[0])) {
6190 			(void) fclose(tfp);
6191 			(void) unlink(UFS_SIGNATURE_LIST);
6192 			bam_error(UFS_BADSIGN, tmpsign);
6193 			return (NULL);
6194 		}
6195 
6196 		signnum = atoi(numstr);
6197 		INJECT_ERROR1("NEGATIVE_SIGN", signnum = -1);
6198 		if (signnum < 0) {
6199 			(void) fclose(tfp);
6200 			(void) unlink(UFS_SIGNATURE_LIST);
6201 			bam_error(UFS_BADSIGN, tmpsign);
6202 			return (NULL);
6203 		}
6204 
6205 		if (i != signnum) {
6206 			BAM_DPRINTF((D_FOUND_HOLE_SIGNLIST, fcn, i));
6207 			break;
6208 		}
6209 	}
6210 
6211 	(void) fclose(tfp);
6212 
6213 found:
6214 	(void) snprintf(tmpsign, sizeof (tmpsign), "rootfs%d", i);
6215 
6216 	/* add the ufs signature to the /var/run list of signatures */
6217 	ret = ufs_add_to_sign_list(tmpsign);
6218 	INJECT_ERROR1("UFS_ADD_TO_SIGN_LIST", ret = -1);
6219 	if (ret == -1) {
6220 		(void) unlink(UFS_SIGNATURE_LIST);
6221 		bam_error(FAILED_ADD_SIGNLIST, tmpsign);
6222 		return (NULL);
6223 	}
6224 
6225 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6226 
6227 	return (s_strdup(tmpsign));
6228 }
6229 
6230 static char *
6231 get_fstype(char *osroot)
6232 {
6233 	FILE		*mntfp;
6234 	struct mnttab	mp = {0};
6235 	struct mnttab	mpref = {0};
6236 	int		error;
6237 	int		ret;
6238 	const char	*fcn = "get_fstype()";
6239 
6240 	INJECT_ERROR1("GET_FSTYPE_OSROOT", osroot = NULL);
6241 	if (osroot == NULL) {
6242 		bam_error(GET_FSTYPE_ARGS);
6243 		return (NULL);
6244 	}
6245 
6246 	mntfp = fopen(MNTTAB, "r");
6247 	error = errno;
6248 	INJECT_ERROR1("GET_FSTYPE_FOPEN", mntfp = NULL);
6249 	if (mntfp == NULL) {
6250 		bam_error(OPEN_FAIL, MNTTAB, strerror(error));
6251 		return (NULL);
6252 	}
6253 
6254 	if (*osroot == '\0')
6255 		mpref.mnt_mountp = "/";
6256 	else
6257 		mpref.mnt_mountp = osroot;
6258 
6259 	ret = getmntany(mntfp, &mp, &mpref);
6260 	INJECT_ERROR1("GET_FSTYPE_GETMNTANY", ret = 1);
6261 	if (ret != 0) {
6262 		bam_error(MNTTAB_MNTPT_NOT_FOUND, osroot, MNTTAB);
6263 		(void) fclose(mntfp);
6264 		return (NULL);
6265 	}
6266 	(void) fclose(mntfp);
6267 
6268 	INJECT_ERROR1("GET_FSTYPE_NULL", mp.mnt_fstype = NULL);
6269 	if (mp.mnt_fstype == NULL) {
6270 		bam_error(MNTTAB_FSTYPE_NULL, osroot);
6271 		return (NULL);
6272 	}
6273 
6274 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6275 
6276 	return (s_strdup(mp.mnt_fstype));
6277 }
6278 
6279 static char *
6280 create_zfs_sign(char *osdev)
6281 {
6282 	char		tmpsign[PATH_MAX];
6283 	char		*pool;
6284 	const char	*fcn = "create_zfs_sign()";
6285 
6286 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, osdev));
6287 
6288 	/*
6289 	 * First find the pool name
6290 	 */
6291 	pool = get_pool(osdev);
6292 	INJECT_ERROR1("CREATE_ZFS_SIGN_GET_POOL", pool = NULL);
6293 	if (pool == NULL) {
6294 		bam_error(GET_POOL_FAILED, osdev);
6295 		return (NULL);
6296 	}
6297 
6298 	(void) snprintf(tmpsign, sizeof (tmpsign), "pool_%s", pool);
6299 
6300 	BAM_DPRINTF((D_CREATED_ZFS_SIGN, fcn, tmpsign));
6301 
6302 	free(pool);
6303 
6304 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6305 
6306 	return (s_strdup(tmpsign));
6307 }
6308 
6309 static char *
6310 create_new_sign(char *osdev, char *fstype)
6311 {
6312 	char		*sign;
6313 	const char	*fcn = "create_new_sign()";
6314 
6315 	INJECT_ERROR1("NEW_SIGN_FSTYPE", fstype = "foofs");
6316 
6317 	if (strcmp(fstype, "zfs") == 0) {
6318 		BAM_DPRINTF((D_CREATE_NEW_ZFS, fcn));
6319 		sign = create_zfs_sign(osdev);
6320 	} else if (strcmp(fstype, "ufs") == 0) {
6321 		BAM_DPRINTF((D_CREATE_NEW_UFS, fcn));
6322 		sign = create_ufs_sign();
6323 	} else {
6324 		bam_error(GRUBSIGN_NOTSUP, fstype);
6325 		sign = NULL;
6326 	}
6327 
6328 	BAM_DPRINTF((D_CREATED_NEW_SIGN, fcn, sign ? sign : "<NULL>"));
6329 	return (sign);
6330 }
6331 
6332 static int
6333 set_backup_common(char *mntpt, char *sign)
6334 {
6335 	FILE		*bfp;
6336 	char		backup[PATH_MAX];
6337 	char		tmpsign[PATH_MAX];
6338 	int		error;
6339 	char		*bdir;
6340 	char		*backup_dup;
6341 	struct stat	sb;
6342 	int		ret;
6343 	const char	*fcn = "set_backup_common()";
6344 
6345 	(void) snprintf(backup, sizeof (backup), "%s%s",
6346 	    mntpt, GRUBSIGN_BACKUP);
6347 
6348 	/* First read the backup */
6349 	bfp = fopen(backup, "r");
6350 	if (bfp != NULL) {
6351 		while (s_fgets(tmpsign, sizeof (tmpsign), bfp)) {
6352 			if (strcmp(tmpsign, sign) == 0) {
6353 				BAM_DPRINTF((D_FOUND_IN_BACKUP, fcn, sign));
6354 				(void) fclose(bfp);
6355 				return (0);
6356 			}
6357 		}
6358 		(void) fclose(bfp);
6359 		BAM_DPRINTF((D_NOT_FOUND_IN_EXIST_BACKUP, fcn, sign));
6360 	} else {
6361 		BAM_DPRINTF((D_BACKUP_NOT_EXIST, fcn, backup));
6362 	}
6363 
6364 	/*
6365 	 * Didn't find the correct signature. First create
6366 	 * the directory if necessary.
6367 	 */
6368 
6369 	/* dirname() modifies its argument so dup it */
6370 	backup_dup = s_strdup(backup);
6371 	bdir = dirname(backup_dup);
6372 	assert(bdir);
6373 
6374 	ret = stat(bdir, &sb);
6375 	INJECT_ERROR1("SET_BACKUP_STAT", ret = -1);
6376 	if (ret == -1) {
6377 		BAM_DPRINTF((D_BACKUP_DIR_NOEXIST, fcn, bdir));
6378 		ret = mkdirp(bdir, DIR_PERMS);
6379 		error = errno;
6380 		INJECT_ERROR1("SET_BACKUP_MKDIRP", ret = -1);
6381 		if (ret == -1) {
6382 			bam_error(GRUBSIGN_BACKUP_MKDIRERR,
6383 			    GRUBSIGN_BACKUP, strerror(error));
6384 			free(backup_dup);
6385 			return (-1);
6386 		}
6387 	}
6388 	free(backup_dup);
6389 
6390 	/*
6391 	 * Open the backup in append mode to add the correct
6392 	 * signature;
6393 	 */
6394 	bfp = fopen(backup, "a");
6395 	error = errno;
6396 	INJECT_ERROR1("SET_BACKUP_FOPEN_A", bfp = NULL);
6397 	if (bfp == NULL) {
6398 		bam_error(GRUBSIGN_BACKUP_OPENERR,
6399 		    GRUBSIGN_BACKUP, strerror(error));
6400 		return (-1);
6401 	}
6402 
6403 	(void) snprintf(tmpsign, sizeof (tmpsign), "%s\n", sign);
6404 
6405 	ret = fputs(tmpsign, bfp);
6406 	error = errno;
6407 	INJECT_ERROR1("SET_BACKUP_FPUTS", ret = 0);
6408 	if (ret != strlen(tmpsign)) {
6409 		bam_error(GRUBSIGN_BACKUP_WRITEERR,
6410 		    GRUBSIGN_BACKUP, strerror(error));
6411 		(void) fclose(bfp);
6412 		return (-1);
6413 	}
6414 
6415 	(void) fclose(bfp);
6416 
6417 	if (bam_verbose)
6418 		bam_print(GRUBSIGN_BACKUP_UPDATED, GRUBSIGN_BACKUP);
6419 
6420 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6421 
6422 	return (0);
6423 }
6424 
6425 static int
6426 set_backup_ufs(char *osroot, char *sign)
6427 {
6428 	const char	*fcn = "set_backup_ufs()";
6429 
6430 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, sign));
6431 	return (set_backup_common(osroot, sign));
6432 }
6433 
6434 static int
6435 set_backup_zfs(char *osdev, char *sign)
6436 {
6437 	char		*pool;
6438 	char		*mntpt;
6439 	zfs_mnted_t	mnted;
6440 	int		ret;
6441 	const char	*fcn = "set_backup_zfs()";
6442 
6443 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osdev, sign));
6444 
6445 	pool = get_pool(osdev);
6446 	INJECT_ERROR1("SET_BACKUP_GET_POOL", pool = NULL);
6447 	if (pool == NULL) {
6448 		bam_error(GET_POOL_FAILED, osdev);
6449 		return (-1);
6450 	}
6451 
6452 	mntpt = mount_top_dataset(pool, &mnted);
6453 	INJECT_ERROR1("SET_BACKUP_MOUNT_DATASET", mntpt = NULL);
6454 	if (mntpt == NULL) {
6455 		bam_error(FAIL_MNT_TOP_DATASET, pool);
6456 		free(pool);
6457 		return (-1);
6458 	}
6459 
6460 	ret = set_backup_common(mntpt, sign);
6461 
6462 	(void) umount_top_dataset(pool, mnted, mntpt);
6463 
6464 	free(pool);
6465 
6466 	INJECT_ERROR1("SET_BACKUP_ZFS_FAIL", ret = 1);
6467 	if (ret == 0) {
6468 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6469 	} else {
6470 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6471 	}
6472 
6473 	return (ret);
6474 }
6475 
6476 static int
6477 set_backup(char *osroot, char *osdev, char *sign, char *fstype)
6478 {
6479 	const char	*fcn = "set_backup()";
6480 	int		ret;
6481 
6482 	INJECT_ERROR1("SET_BACKUP_FSTYPE", fstype = "foofs");
6483 
6484 	if (strcmp(fstype, "ufs") == 0) {
6485 		BAM_DPRINTF((D_SET_BACKUP_UFS, fcn));
6486 		ret = set_backup_ufs(osroot, sign);
6487 	} else if (strcmp(fstype, "zfs") == 0) {
6488 		BAM_DPRINTF((D_SET_BACKUP_ZFS, fcn));
6489 		ret = set_backup_zfs(osdev, sign);
6490 	} else {
6491 		bam_error(GRUBSIGN_NOTSUP, fstype);
6492 		ret = -1;
6493 	}
6494 
6495 	if (ret == 0) {
6496 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6497 	} else {
6498 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6499 	}
6500 
6501 	return (ret);
6502 }
6503 
6504 static int
6505 set_primary_common(char *mntpt, char *sign)
6506 {
6507 	char		signfile[PATH_MAX];
6508 	char		signdir[PATH_MAX];
6509 	struct stat	sb;
6510 	int		fd;
6511 	int		error;
6512 	int		ret;
6513 	const char	*fcn = "set_primary_common()";
6514 
6515 	(void) snprintf(signfile, sizeof (signfile), "%s/%s/%s",
6516 	    mntpt, GRUBSIGN_DIR, sign);
6517 
6518 	if (stat(signfile, &sb) != -1) {
6519 		if (bam_verbose)
6520 			bam_print(PRIMARY_SIGN_EXISTS, sign);
6521 		return (0);
6522 	} else {
6523 		BAM_DPRINTF((D_PRIMARY_NOT_EXIST, fcn, signfile));
6524 	}
6525 
6526 	(void) snprintf(signdir, sizeof (signdir), "%s/%s",
6527 	    mntpt, GRUBSIGN_DIR);
6528 
6529 	if (stat(signdir, &sb) == -1) {
6530 		BAM_DPRINTF((D_PRIMARY_DIR_NOEXIST, fcn, signdir));
6531 		ret = mkdirp(signdir, DIR_PERMS);
6532 		error = errno;
6533 		INJECT_ERROR1("SET_PRIMARY_MKDIRP", ret = -1);
6534 		if (ret == -1) {
6535 			bam_error(GRUBSIGN_MKDIR_ERR, signdir, strerror(errno));
6536 			return (-1);
6537 		}
6538 	}
6539 
6540 	fd = open(signfile, O_RDWR|O_CREAT|O_TRUNC, 0444);
6541 	error = errno;
6542 	INJECT_ERROR1("PRIMARY_SIGN_CREAT", fd = -1);
6543 	if (fd == -1) {
6544 		bam_error(GRUBSIGN_PRIMARY_CREATERR, signfile, strerror(error));
6545 		return (-1);
6546 	}
6547 
6548 	ret = fsync(fd);
6549 	error = errno;
6550 	INJECT_ERROR1("PRIMARY_FSYNC", ret = -1);
6551 	if (ret != 0) {
6552 		bam_error(GRUBSIGN_PRIMARY_SYNCERR, signfile, strerror(error));
6553 	}
6554 
6555 	(void) close(fd);
6556 
6557 	if (bam_verbose)
6558 		bam_print(GRUBSIGN_CREATED_PRIMARY, signfile);
6559 
6560 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6561 
6562 	return (0);
6563 }
6564 
6565 static int
6566 set_primary_ufs(char *osroot, char *sign)
6567 {
6568 	const char	*fcn = "set_primary_ufs()";
6569 
6570 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, sign));
6571 	return (set_primary_common(osroot, sign));
6572 }
6573 
6574 static int
6575 set_primary_zfs(char *osdev, char *sign)
6576 {
6577 	char		*pool;
6578 	char		*mntpt;
6579 	zfs_mnted_t	mnted;
6580 	int		ret;
6581 	const char	*fcn = "set_primary_zfs()";
6582 
6583 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osdev, sign));
6584 
6585 	pool = get_pool(osdev);
6586 	INJECT_ERROR1("SET_PRIMARY_ZFS_GET_POOL", pool = NULL);
6587 	if (pool == NULL) {
6588 		bam_error(GET_POOL_FAILED, osdev);
6589 		return (-1);
6590 	}
6591 
6592 	/* Pool name must exist in the sign */
6593 	ret = (strstr(sign, pool) != NULL);
6594 	INJECT_ERROR1("SET_PRIMARY_ZFS_POOL_SIGN_INCOMPAT", ret = 0);
6595 	if (ret == 0) {
6596 		bam_error(POOL_SIGN_INCOMPAT, pool, sign);
6597 		free(pool);
6598 		return (-1);
6599 	}
6600 
6601 	mntpt = mount_top_dataset(pool, &mnted);
6602 	INJECT_ERROR1("SET_PRIMARY_ZFS_MOUNT_DATASET", mntpt = NULL);
6603 	if (mntpt == NULL) {
6604 		bam_error(FAIL_MNT_TOP_DATASET, pool);
6605 		free(pool);
6606 		return (-1);
6607 	}
6608 
6609 	ret = set_primary_common(mntpt, sign);
6610 
6611 	(void) umount_top_dataset(pool, mnted, mntpt);
6612 
6613 	free(pool);
6614 
6615 	INJECT_ERROR1("SET_PRIMARY_ZFS_FAIL", ret = 1);
6616 	if (ret == 0) {
6617 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6618 	} else {
6619 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6620 	}
6621 
6622 	return (ret);
6623 }
6624 
6625 static int
6626 set_primary(char *osroot, char *osdev, char *sign, char *fstype)
6627 {
6628 	const char	*fcn = "set_primary()";
6629 	int		ret;
6630 
6631 	INJECT_ERROR1("SET_PRIMARY_FSTYPE", fstype = "foofs");
6632 	if (strcmp(fstype, "ufs") == 0) {
6633 		BAM_DPRINTF((D_SET_PRIMARY_UFS, fcn));
6634 		ret = set_primary_ufs(osroot, sign);
6635 	} else if (strcmp(fstype, "zfs") == 0) {
6636 		BAM_DPRINTF((D_SET_PRIMARY_ZFS, fcn));
6637 		ret = set_primary_zfs(osdev, sign);
6638 	} else {
6639 		bam_error(GRUBSIGN_NOTSUP, fstype);
6640 		ret = -1;
6641 	}
6642 
6643 	if (ret == 0) {
6644 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6645 	} else {
6646 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6647 	}
6648 
6649 	return (ret);
6650 }
6651 
6652 static int
6653 ufs_add_to_sign_list(char *sign)
6654 {
6655 	FILE		*tfp;
6656 	char		signline[MAXNAMELEN];
6657 	char		cmd[PATH_MAX];
6658 	int		ret;
6659 	int		error;
6660 	const char	*fcn = "ufs_add_to_sign_list()";
6661 
6662 	INJECT_ERROR1("ADD_TO_SIGN_LIST_NOT_UFS", sign = "pool_rpool5");
6663 	if (strncmp(sign, GRUBSIGN_UFS_PREFIX,
6664 	    strlen(GRUBSIGN_UFS_PREFIX)) != 0) {
6665 		bam_error(INVALID_UFS_SIGN, sign);
6666 		(void) unlink(UFS_SIGNATURE_LIST);
6667 		return (-1);
6668 	}
6669 
6670 	/*
6671 	 * most failures in this routine are not a fatal error
6672 	 * We simply unlink the /var/run file and continue
6673 	 */
6674 
6675 	ret = rename(UFS_SIGNATURE_LIST, UFS_SIGNATURE_LIST".tmp");
6676 	error = errno;
6677 	INJECT_ERROR1("ADD_TO_SIGN_LIST_RENAME", ret = -1);
6678 	if (ret == -1) {
6679 		bam_error(RENAME_FAIL, UFS_SIGNATURE_LIST".tmp",
6680 		    strerror(error));
6681 		(void) unlink(UFS_SIGNATURE_LIST);
6682 		return (0);
6683 	}
6684 
6685 	tfp = fopen(UFS_SIGNATURE_LIST".tmp", "a");
6686 	error = errno;
6687 	INJECT_ERROR1("ADD_TO_SIGN_LIST_FOPEN", tfp = NULL);
6688 	if (tfp == NULL) {
6689 		bam_error(OPEN_FAIL, UFS_SIGNATURE_LIST".tmp", strerror(error));
6690 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6691 		return (0);
6692 	}
6693 
6694 	(void) snprintf(signline, sizeof (signline), "%s\n", sign);
6695 
6696 	ret = fputs(signline, tfp);
6697 	error = errno;
6698 	INJECT_ERROR1("ADD_TO_SIGN_LIST_FPUTS", ret = 0);
6699 	if (ret != strlen(signline)) {
6700 		bam_error(SIGN_LIST_FPUTS_ERR, sign, strerror(error));
6701 		(void) fclose(tfp);
6702 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6703 		return (0);
6704 	}
6705 
6706 	ret = fclose(tfp);
6707 	error = errno;
6708 	INJECT_ERROR1("ADD_TO_SIGN_LIST_FCLOSE", ret = EOF);
6709 	if (ret == EOF) {
6710 		bam_error(CLOSE_FAIL, UFS_SIGNATURE_LIST".tmp",
6711 		    strerror(error));
6712 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6713 		return (0);
6714 	}
6715 
6716 	/* Sort the list again */
6717 	(void) snprintf(cmd, sizeof (cmd),
6718 	    "/usr/bin/sort -u %s.tmp > %s.sorted",
6719 	    UFS_SIGNATURE_LIST, UFS_SIGNATURE_LIST);
6720 
6721 	ret = exec_cmd(cmd, NULL);
6722 	INJECT_ERROR1("ADD_TO_SIGN_LIST_SORT", ret = 1);
6723 	if (ret != 0) {
6724 		bam_error(GRUBSIGN_SORT_FAILED);
6725 		(void) unlink(UFS_SIGNATURE_LIST".sorted");
6726 		(void) unlink(UFS_SIGNATURE_LIST".tmp");
6727 		return (0);
6728 	}
6729 
6730 	(void) unlink(UFS_SIGNATURE_LIST".tmp");
6731 
6732 	ret = rename(UFS_SIGNATURE_LIST".sorted", UFS_SIGNATURE_LIST);
6733 	error = errno;
6734 	INJECT_ERROR1("ADD_TO_SIGN_LIST_RENAME2", ret = -1);
6735 	if (ret == -1) {
6736 		bam_error(RENAME_FAIL, UFS_SIGNATURE_LIST, strerror(error));
6737 		(void) unlink(UFS_SIGNATURE_LIST".sorted");
6738 		return (0);
6739 	}
6740 
6741 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6742 
6743 	return (0);
6744 }
6745 
6746 static int
6747 set_signature(char *osroot, char *osdev, char *sign, char *fstype)
6748 {
6749 	int		ret;
6750 	const char	*fcn = "set_signature()";
6751 
6752 	BAM_DPRINTF((D_FUNC_ENTRY4, fcn, osroot, osdev, sign, fstype));
6753 
6754 	ret = set_backup(osroot, osdev, sign, fstype);
6755 	INJECT_ERROR1("SET_SIGNATURE_BACKUP", ret = -1);
6756 	if (ret == -1) {
6757 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6758 		bam_error(SET_BACKUP_FAILED, sign, osroot, osdev);
6759 		return (-1);
6760 	}
6761 
6762 	ret = set_primary(osroot, osdev, sign, fstype);
6763 	INJECT_ERROR1("SET_SIGNATURE_PRIMARY", ret = -1);
6764 
6765 	if (ret == 0) {
6766 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6767 	} else {
6768 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
6769 		bam_error(SET_PRIMARY_FAILED, sign, osroot, osdev);
6770 
6771 	}
6772 	return (ret);
6773 }
6774 
6775 char *
6776 get_grubsign(char *osroot, char *osdev)
6777 {
6778 	char		*grubsign;	/* (<sign>,#,#) */
6779 	char		*slice;
6780 	int		fdiskpart;
6781 	char		*sign;
6782 	char		*fstype;
6783 	int		ret;
6784 	const char	*fcn = "get_grubsign()";
6785 
6786 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, osdev));
6787 
6788 	fstype = get_fstype(osroot);
6789 	INJECT_ERROR1("GET_GRUBSIGN_FSTYPE", fstype = NULL);
6790 	if (fstype == NULL) {
6791 		bam_error(GET_FSTYPE_FAILED, osroot);
6792 		return (NULL);
6793 	}
6794 
6795 	sign = find_existing_sign(osroot, osdev, fstype);
6796 	INJECT_ERROR1("FIND_EXISTING_SIGN", sign = NULL);
6797 	if (sign == NULL) {
6798 		BAM_DPRINTF((D_GET_GRUBSIGN_NO_EXISTING, fcn, osroot, osdev));
6799 		sign = create_new_sign(osdev, fstype);
6800 		INJECT_ERROR1("CREATE_NEW_SIGN", sign = NULL);
6801 		if (sign == NULL) {
6802 			bam_error(GRUBSIGN_CREATE_FAIL, osdev);
6803 			free(fstype);
6804 			return (NULL);
6805 		}
6806 	}
6807 
6808 	ret = set_signature(osroot, osdev, sign, fstype);
6809 	INJECT_ERROR1("SET_SIGNATURE_FAIL", ret = -1);
6810 	if (ret == -1) {
6811 		bam_error(GRUBSIGN_WRITE_FAIL, osdev);
6812 		free(sign);
6813 		free(fstype);
6814 		(void) unlink(UFS_SIGNATURE_LIST);
6815 		return (NULL);
6816 	}
6817 
6818 	free(fstype);
6819 
6820 	if (bam_verbose)
6821 		bam_print(GRUBSIGN_FOUND_OR_CREATED, sign, osdev);
6822 
6823 	fdiskpart = get_partition(osdev);
6824 	INJECT_ERROR1("GET_GRUBSIGN_FDISK", fdiskpart = -1);
6825 	if (fdiskpart == -1) {
6826 		bam_error(FDISKPART_FAIL, osdev);
6827 		free(sign);
6828 		return (NULL);
6829 	}
6830 
6831 	slice = strrchr(osdev, 's');
6832 
6833 	grubsign = s_calloc(1, MAXNAMELEN + 10);
6834 	if (slice) {
6835 		(void) snprintf(grubsign, MAXNAMELEN + 10, "(%s,%d,%c)",
6836 		    sign, fdiskpart, slice[1] + 'a' - '0');
6837 	} else
6838 		(void) snprintf(grubsign, MAXNAMELEN + 10, "(%s,%d)",
6839 		    sign, fdiskpart);
6840 
6841 	free(sign);
6842 
6843 	BAM_DPRINTF((D_GET_GRUBSIGN_SUCCESS, fcn, grubsign));
6844 
6845 	return (grubsign);
6846 }
6847 
6848 static char *
6849 get_title(char *rootdir)
6850 {
6851 	static char	title[80];
6852 	char		*cp = NULL;
6853 	char		release[PATH_MAX];
6854 	FILE		*fp;
6855 	const char	*fcn = "get_title()";
6856 
6857 	/* open the /etc/release file */
6858 	(void) snprintf(release, sizeof (release), "%s/etc/release", rootdir);
6859 
6860 	fp = fopen(release, "r");
6861 	if (fp == NULL) {
6862 		bam_error(OPEN_FAIL, release, strerror(errno));
6863 		cp = NULL;
6864 		goto out;
6865 	}
6866 
6867 	while (s_fgets(title, sizeof (title), fp) != NULL) {
6868 		cp = strstr(title, "Solaris");
6869 		if (cp)
6870 			break;
6871 	}
6872 	(void) fclose(fp);
6873 
6874 out:
6875 	cp = cp ? cp : "Solaris";
6876 
6877 	BAM_DPRINTF((D_GET_TITLE, fcn, cp));
6878 
6879 	return (cp);
6880 }
6881 
6882 char *
6883 get_special(char *mountp)
6884 {
6885 	FILE		*mntfp;
6886 	struct mnttab	mp = {0};
6887 	struct mnttab	mpref = {0};
6888 	int		error;
6889 	int		ret;
6890 	const char 	*fcn = "get_special()";
6891 
6892 	INJECT_ERROR1("GET_SPECIAL_MNTPT", mountp = NULL);
6893 	if (mountp == NULL) {
6894 		bam_error(GET_SPECIAL_NULL_MNTPT);
6895 		return (NULL);
6896 	}
6897 
6898 	mntfp = fopen(MNTTAB, "r");
6899 	error = errno;
6900 	INJECT_ERROR1("GET_SPECIAL_MNTTAB_OPEN", mntfp = NULL);
6901 	if (mntfp == NULL) {
6902 		bam_error(OPEN_FAIL, MNTTAB, strerror(error));
6903 		return (NULL);
6904 	}
6905 
6906 	if (*mountp == '\0')
6907 		mpref.mnt_mountp = "/";
6908 	else
6909 		mpref.mnt_mountp = mountp;
6910 
6911 	ret = getmntany(mntfp, &mp, &mpref);
6912 	INJECT_ERROR1("GET_SPECIAL_MNTTAB_SEARCH", ret = 1);
6913 	if (ret != 0) {
6914 		(void) fclose(mntfp);
6915 		BAM_DPRINTF((D_GET_SPECIAL_NOT_IN_MNTTAB, fcn, mountp));
6916 		return (NULL);
6917 	}
6918 	(void) fclose(mntfp);
6919 
6920 	BAM_DPRINTF((D_GET_SPECIAL, fcn, mp.mnt_special));
6921 
6922 	return (s_strdup(mp.mnt_special));
6923 }
6924 
6925 static void
6926 free_physarray(char **physarray, int n)
6927 {
6928 	int			i;
6929 	const char		*fcn = "free_physarray()";
6930 
6931 	assert(physarray);
6932 	assert(n);
6933 
6934 	BAM_DPRINTF((D_FUNC_ENTRY_N1, fcn, n));
6935 
6936 	for (i = 0; i < n; i++) {
6937 		free(physarray[i]);
6938 	}
6939 	free(physarray);
6940 
6941 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
6942 }
6943 
6944 static int
6945 zfs_get_physical(char *special, char ***physarray, int *n)
6946 {
6947 	char			sdup[PATH_MAX];
6948 	char			cmd[PATH_MAX];
6949 	char			dsk[PATH_MAX];
6950 	char			*pool;
6951 	filelist_t		flist = {0};
6952 	line_t			*lp;
6953 	line_t			*startlp;
6954 	char			*comp1;
6955 	int			i;
6956 	int			ret;
6957 	const char		*fcn = "zfs_get_physical()";
6958 
6959 	assert(special);
6960 
6961 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, special));
6962 
6963 	INJECT_ERROR1("INVALID_ZFS_SPECIAL", special = "/foo");
6964 	if (special[0] == '/') {
6965 		bam_error(INVALID_ZFS_SPECIAL, special);
6966 		return (-1);
6967 	}
6968 
6969 	(void) strlcpy(sdup, special, sizeof (sdup));
6970 
6971 	pool = strtok(sdup, "/");
6972 	INJECT_ERROR1("ZFS_GET_PHYS_POOL", pool = NULL);
6973 	if (pool == NULL) {
6974 		bam_error(CANT_FIND_POOL_FROM_SPECIAL, special);
6975 		return (-1);
6976 	}
6977 
6978 	(void) snprintf(cmd, sizeof (cmd), "/sbin/zpool status %s", pool);
6979 
6980 	ret = exec_cmd(cmd, &flist);
6981 	INJECT_ERROR1("ZFS_GET_PHYS_STATUS", ret = 1);
6982 	if (ret != 0) {
6983 		bam_error(ZFS_GET_POOL_STATUS, pool);
6984 		return (-1);
6985 	}
6986 
6987 	INJECT_ERROR1("ZFS_GET_PHYS_STATUS_OUT", flist.head = NULL);
6988 	if (flist.head == NULL) {
6989 		bam_error(BAD_ZPOOL_STATUS, pool);
6990 		filelist_free(&flist);
6991 		return (-1);
6992 	}
6993 
6994 	for (lp = flist.head; lp; lp = lp->next) {
6995 		BAM_DPRINTF((D_STRTOK_ZPOOL_STATUS, fcn, lp->line));
6996 		comp1 = strtok(lp->line, " \t");
6997 		if (comp1 == NULL) {
6998 			free(lp->line);
6999 			lp->line = NULL;
7000 		} else {
7001 			comp1 = s_strdup(comp1);
7002 			free(lp->line);
7003 			lp->line = comp1;
7004 		}
7005 	}
7006 
7007 	for (lp = flist.head; lp; lp = lp->next) {
7008 		if (lp->line == NULL)
7009 			continue;
7010 		if (strcmp(lp->line, pool) == 0) {
7011 			BAM_DPRINTF((D_FOUND_POOL_IN_ZPOOL_STATUS, fcn, pool));
7012 			break;
7013 		}
7014 	}
7015 
7016 	if (lp == NULL) {
7017 		bam_error(NO_POOL_IN_ZPOOL_STATUS, pool);
7018 		filelist_free(&flist);
7019 		return (-1);
7020 	}
7021 
7022 	startlp = lp->next;
7023 	for (i = 0, lp = startlp; lp; lp = lp->next) {
7024 		if (lp->line == NULL)
7025 			continue;
7026 		if (strcmp(lp->line, "mirror") == 0)
7027 			continue;
7028 		if (lp->line[0] == '\0' || strcmp(lp->line, "errors:") == 0)
7029 			break;
7030 		i++;
7031 		BAM_DPRINTF((D_COUNTING_ZFS_PHYS, fcn, i));
7032 	}
7033 
7034 	if (i == 0) {
7035 		bam_error(NO_PHYS_IN_ZPOOL_STATUS, pool);
7036 		filelist_free(&flist);
7037 		return (-1);
7038 	}
7039 
7040 	*n = i;
7041 	*physarray = s_calloc(*n, sizeof (char *));
7042 	for (i = 0, lp = startlp; lp; lp = lp->next) {
7043 		if (lp->line == NULL)
7044 			continue;
7045 		if (strcmp(lp->line, "mirror") == 0)
7046 			continue;
7047 		if (strcmp(lp->line, "errors:") == 0)
7048 			break;
7049 		if (strncmp(lp->line, "/dev/dsk/", strlen("/dev/dsk/")) != 0 &&
7050 		    strncmp(lp->line, "/dev/rdsk/",
7051 		    strlen("/dev/rdsk/")) != 0)  {
7052 			(void) snprintf(dsk, sizeof (dsk), "/dev/dsk/%s",
7053 			    lp->line);
7054 		} else {
7055 			(void) strlcpy(dsk, lp->line, sizeof (dsk));
7056 		}
7057 		BAM_DPRINTF((D_ADDING_ZFS_PHYS, fcn, dsk, pool));
7058 		(*physarray)[i++] = s_strdup(dsk);
7059 	}
7060 
7061 	assert(i == *n);
7062 
7063 	filelist_free(&flist);
7064 
7065 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
7066 	return (0);
7067 }
7068 
7069 /*
7070  * Certain services needed to run metastat successfully may not
7071  * be enabled. Enable them now.
7072  */
7073 /*
7074  * Checks if the specified service is online
7075  * Returns: 	1 if the service is online
7076  *		0 if the service is not online
7077  *		-1 on error
7078  */
7079 static int
7080 is_svc_online(char *svc)
7081 {
7082 	char			*state;
7083 	const char		*fcn = "is_svc_online()";
7084 
7085 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, svc));
7086 
7087 	state = smf_get_state(svc);
7088 	INJECT_ERROR2("GET_SVC_STATE", free(state), state = NULL);
7089 	if (state == NULL) {
7090 		bam_error(GET_SVC_STATE_ERR, svc);
7091 		return (-1);
7092 	}
7093 	BAM_DPRINTF((D_GOT_SVC_STATUS, fcn, svc));
7094 
7095 	if (strcmp(state, SCF_STATE_STRING_ONLINE) == 0) {
7096 		BAM_DPRINTF((D_SVC_ONLINE, fcn, svc));
7097 		free(state);
7098 		return (1);
7099 	}
7100 
7101 	BAM_DPRINTF((D_SVC_NOT_ONLINE, fcn, state, svc));
7102 
7103 	free(state);
7104 
7105 	return (0);
7106 }
7107 
7108 static int
7109 enable_svc(char *svc)
7110 {
7111 	int			ret;
7112 	int			sleeptime;
7113 	const char		*fcn = "enable_svc()";
7114 
7115 	ret = is_svc_online(svc);
7116 	if (ret == -1) {
7117 		bam_error(SVC_IS_ONLINE_FAILED, svc);
7118 		return (-1);
7119 	} else if (ret == 1) {
7120 		BAM_DPRINTF((D_SVC_ALREADY_ONLINE, fcn, svc));
7121 		return (0);
7122 	}
7123 
7124 	/* Service is not enabled. Enable it now. */
7125 	ret = smf_enable_instance(svc, 0);
7126 	INJECT_ERROR1("ENABLE_SVC_FAILED", ret = -1);
7127 	if (ret != 0) {
7128 		bam_error(ENABLE_SVC_FAILED, svc);
7129 		return (-1);
7130 	}
7131 
7132 	BAM_DPRINTF((D_SVC_ONLINE_INITIATED, fcn, svc));
7133 
7134 	sleeptime = 0;
7135 	do {
7136 		ret = is_svc_online(svc);
7137 		INJECT_ERROR1("SVC_ONLINE_SUCCESS", ret = 1);
7138 		INJECT_ERROR1("SVC_ONLINE_FAILURE", ret = -1);
7139 		INJECT_ERROR1("SVC_ONLINE_NOTYET", ret = 0);
7140 		if (ret == -1) {
7141 			bam_error(ERR_SVC_GET_ONLINE, svc);
7142 			return (-1);
7143 		} else if (ret == 1) {
7144 			BAM_DPRINTF((D_SVC_NOW_ONLINE, fcn, svc));
7145 			return (1);
7146 		}
7147 		(void) sleep(1);
7148 	} while (++sleeptime < 60);
7149 
7150 	bam_error(TIMEOUT_ENABLE_SVC, svc);
7151 
7152 	return (-1);
7153 }
7154 
7155 static int
7156 ufs_get_physical(char *special, char ***physarray, int *n)
7157 {
7158 	char			cmd[PATH_MAX];
7159 	char			*shortname;
7160 	filelist_t		flist = {0};
7161 	char			*meta;
7162 	char			*type;
7163 	char			*comp1;
7164 	char			*comp2;
7165 	char			*comp3;
7166 	char			*comp4;
7167 	int			i;
7168 	line_t			*lp;
7169 	int			ret;
7170 	char			*svc;
7171 	const char		*fcn = "ufs_get_physical()";
7172 
7173 	assert(special);
7174 
7175 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, special));
7176 
7177 	if (strncmp(special, "/dev/md/", strlen("/dev/md/")) != 0) {
7178 		bam_error(UFS_GET_PHYS_NOT_SVM, special);
7179 		return (-1);
7180 	}
7181 
7182 	if (strncmp(special, "/dev/md/dsk/", strlen("/dev/md/dsk/")) == 0) {
7183 		shortname = special + strlen("/dev/md/dsk/");
7184 	} else if (strncmp(special, "/dev/md/rdsk/",
7185 	    strlen("/dev/md/rdsk/")) == 0) {
7186 		shortname = special + strlen("/dev/md/rdsk");
7187 	} else {
7188 		bam_error(UFS_GET_PHYS_INVALID_SVM, special);
7189 		return (-1);
7190 	}
7191 
7192 	BAM_DPRINTF((D_UFS_SVM_SHORT, fcn, special, shortname));
7193 
7194 	svc = "network/rpc/meta:default";
7195 	if (enable_svc(svc) == -1) {
7196 		bam_error(UFS_SVM_METASTAT_SVC_ERR, svc);
7197 	}
7198 
7199 	(void) snprintf(cmd, sizeof (cmd), "/sbin/metastat -p %s", shortname);
7200 
7201 	ret = exec_cmd(cmd, &flist);
7202 	INJECT_ERROR1("UFS_SVM_METASTAT", ret = 1);
7203 	if (ret != 0) {
7204 		bam_error(UFS_SVM_METASTAT_ERR, shortname);
7205 		return (-1);
7206 	}
7207 
7208 	INJECT_ERROR1("UFS_SVM_METASTAT_OUT", flist.head = NULL);
7209 	if (flist.head == NULL) {
7210 		bam_error(BAD_UFS_SVM_METASTAT, shortname);
7211 		filelist_free(&flist);
7212 		return (-1);
7213 	}
7214 
7215 	/*
7216 	 * Check if not a mirror. We only parse a single metadevice
7217 	 * if not a mirror
7218 	 */
7219 	meta = strtok(flist.head->line, " \t");
7220 	type = strtok(NULL, " \t");
7221 	if (meta == NULL || type == NULL) {
7222 		bam_error(ERROR_PARSE_UFS_SVM_METASTAT, shortname);
7223 		filelist_free(&flist);
7224 		return (-1);
7225 	}
7226 	if (strcmp(type, "-m") != 0) {
7227 		comp1 = strtok(NULL, " \t");
7228 		comp2 = strtok(NULL, " \t");
7229 		if (comp1 == NULL || comp2 != NULL) {
7230 			bam_error(INVALID_UFS_SVM_METASTAT, shortname);
7231 			filelist_free(&flist);
7232 			return (-1);
7233 		}
7234 		BAM_DPRINTF((D_UFS_SVM_ONE_COMP, fcn, comp1, shortname));
7235 		*physarray = s_calloc(1, sizeof (char *));
7236 		(*physarray)[0] = s_strdup(comp1);
7237 		*n = 1;
7238 		filelist_free(&flist);
7239 		return (0);
7240 	}
7241 
7242 	/*
7243 	 * Okay we have a mirror. Everything after the first line
7244 	 * is a submirror
7245 	 */
7246 	for (i = 0, lp = flist.head->next; lp; lp = lp->next) {
7247 		if (strstr(lp->line, "/dev/dsk/") == NULL &&
7248 		    strstr(lp->line, "/dev/rdsk/") == NULL) {
7249 			bam_error(CANNOT_PARSE_UFS_SVM_METASTAT, shortname);
7250 			filelist_free(&flist);
7251 			return (-1);
7252 		}
7253 		i++;
7254 	}
7255 
7256 	*physarray = s_calloc(i, sizeof (char *));
7257 	*n = i;
7258 
7259 	for (i = 0, lp = flist.head->next; lp; lp = lp->next) {
7260 		comp1 = strtok(lp->line, " \t");
7261 		comp2 = strtok(NULL, " \t");
7262 		comp3 = strtok(NULL, " \t");
7263 		comp4 = strtok(NULL, " \t");
7264 
7265 		if (comp3 == NULL || comp4 == NULL ||
7266 		    (strncmp(comp4, "/dev/dsk/", strlen("/dev/dsk/")) != 0 &&
7267 		    strncmp(comp4, "/dev/rdsk/", strlen("/dev/rdsk/")) != 0)) {
7268 			bam_error(CANNOT_PARSE_UFS_SVM_SUBMIRROR, shortname);
7269 			filelist_free(&flist);
7270 			free_physarray(*physarray, *n);
7271 			return (-1);
7272 		}
7273 
7274 		(*physarray)[i++] = s_strdup(comp4);
7275 	}
7276 
7277 	assert(i == *n);
7278 
7279 	filelist_free(&flist);
7280 
7281 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
7282 	return (0);
7283 }
7284 
7285 static int
7286 get_physical(char *menu_root, char ***physarray, int *n)
7287 {
7288 	char			*special;
7289 	int			ret;
7290 	const char		*fcn = "get_physical()";
7291 
7292 	assert(menu_root);
7293 	assert(physarray);
7294 	assert(n);
7295 
7296 	*physarray = NULL;
7297 	*n = 0;
7298 
7299 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, menu_root));
7300 
7301 	/* First get the device special file from /etc/mnttab */
7302 	special = get_special(menu_root);
7303 	INJECT_ERROR1("GET_PHYSICAL_SPECIAL", special = NULL);
7304 	if (special == NULL) {
7305 		bam_error(GET_SPECIAL_NULL, menu_root);
7306 		return (-1);
7307 	}
7308 
7309 	/* If already a physical device nothing to do */
7310 	if (strncmp(special, "/dev/dsk/", strlen("/dev/dsk/")) == 0 ||
7311 	    strncmp(special, "/dev/rdsk/", strlen("/dev/rdsk/")) == 0) {
7312 		BAM_DPRINTF((D_GET_PHYSICAL_ALREADY, fcn, menu_root, special));
7313 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
7314 		*physarray = s_calloc(1, sizeof (char *));
7315 		(*physarray)[0] = special;
7316 		*n = 1;
7317 		return (0);
7318 	}
7319 
7320 	if (is_zfs(menu_root)) {
7321 		ret = zfs_get_physical(special, physarray, n);
7322 	} else if (is_ufs(menu_root)) {
7323 		ret = ufs_get_physical(special, physarray, n);
7324 	} else {
7325 		bam_error(GET_PHYSICAL_NOTSUP_FSTYPE, menu_root, special);
7326 		ret = -1;
7327 	}
7328 
7329 	free(special);
7330 
7331 	INJECT_ERROR1("GET_PHYSICAL_RET", ret = -1);
7332 	if (ret == -1) {
7333 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
7334 	} else {
7335 		int	i;
7336 		assert (*n > 0);
7337 		for (i = 0; i < *n; i++) {
7338 			BAM_DPRINTF((D_GET_PHYSICAL_RET, fcn, (*physarray)[i]));
7339 		}
7340 	}
7341 
7342 	return (ret);
7343 }
7344 
7345 static int
7346 is_bootdisk(char *osroot, char *physical)
7347 {
7348 	int			ret;
7349 	char			*grubroot;
7350 	char			*bootp;
7351 	const char		*fcn = "is_bootdisk()";
7352 
7353 	assert(osroot);
7354 	assert(physical);
7355 
7356 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, physical));
7357 
7358 	bootp = strstr(physical, "p0:boot");
7359 	if (bootp)
7360 		*bootp = '\0';
7361 	/*
7362 	 * We just want the BIOS mapping for menu disk.
7363 	 * Don't pass menu_root to get_grubroot() as the
7364 	 * check that it is used for is not relevant here.
7365 	 * The osroot is immaterial as well - it is only used to
7366 	 * to find create_diskmap script. Everything hinges on
7367 	 * "physical"
7368 	 */
7369 	grubroot = get_grubroot(osroot, physical, NULL);
7370 
7371 	INJECT_ERROR1("IS_BOOTDISK_GRUBROOT", grubroot = NULL);
7372 	if (grubroot == NULL) {
7373 		if (bam_verbose)
7374 			bam_error(NO_GRUBROOT_FOR_DISK, physical);
7375 		return (0);
7376 	}
7377 	ret = grubroot[3] == '0';
7378 	free(grubroot);
7379 
7380 	BAM_DPRINTF((D_RETURN_RET, fcn, ret));
7381 
7382 	return (ret);
7383 }
7384 
7385 /*
7386  * Check if menu is on the boot device
7387  * Return 0 (false) on error
7388  */
7389 static int
7390 menu_on_bootdisk(char *osroot, char *menu_root)
7391 {
7392 	char		**physarray;
7393 	int		ret;
7394 	int		n;
7395 	int		i;
7396 	int		on_bootdisk;
7397 	const char	*fcn = "menu_on_bootdisk()";
7398 
7399 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, menu_root));
7400 
7401 	ret = get_physical(menu_root, &physarray, &n);
7402 	INJECT_ERROR1("MENU_ON_BOOTDISK_PHYSICAL", ret = -1);
7403 	if (ret != 0) {
7404 		bam_error(GET_PHYSICAL_MENU_NULL, menu_root);
7405 		return (0);
7406 	}
7407 
7408 	assert(physarray);
7409 	assert(n > 0);
7410 
7411 	on_bootdisk = 0;
7412 	for (i = 0; i < n; i++) {
7413 		assert(strncmp(physarray[i], "/dev/dsk/",
7414 		    strlen("/dev/dsk/")) == 0 ||
7415 		    strncmp(physarray[i], "/dev/rdsk/",
7416 		    strlen("/dev/rdsk/")) == 0);
7417 
7418 		BAM_DPRINTF((D_CHECK_ON_BOOTDISK, fcn, physarray[i]));
7419 		if (is_bootdisk(osroot, physarray[i])) {
7420 			on_bootdisk = 1;
7421 			BAM_DPRINTF((D_IS_ON_BOOTDISK, fcn, physarray[i]));
7422 		}
7423 	}
7424 
7425 	free_physarray(physarray, n);
7426 
7427 	INJECT_ERROR1("ON_BOOTDISK_YES", on_bootdisk = 1);
7428 	INJECT_ERROR1("ON_BOOTDISK_NO", on_bootdisk = 0);
7429 	if (on_bootdisk) {
7430 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
7431 	} else {
7432 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
7433 	}
7434 
7435 	return (on_bootdisk);
7436 }
7437 
7438 void
7439 bam_add_line(menu_t *mp, entry_t *entry, line_t *prev, line_t *lp)
7440 {
7441 	const char	*fcn = "bam_add_line()";
7442 
7443 	assert(mp);
7444 	assert(entry);
7445 	assert(prev);
7446 	assert(lp);
7447 
7448 	lp->next = prev->next;
7449 	if (prev->next) {
7450 		BAM_DPRINTF((D_ADD_LINE_PREV_NEXT, fcn));
7451 		prev->next->prev = lp;
7452 	} else {
7453 		BAM_DPRINTF((D_ADD_LINE_NOT_PREV_NEXT, fcn));
7454 	}
7455 	prev->next = lp;
7456 	lp->prev = prev;
7457 
7458 	if (entry->end == prev) {
7459 		BAM_DPRINTF((D_ADD_LINE_LAST_LINE_IN_ENTRY, fcn));
7460 		entry->end = lp;
7461 	}
7462 	if (mp->end == prev) {
7463 		assert(lp->next == NULL);
7464 		mp->end = lp;
7465 		BAM_DPRINTF((D_ADD_LINE_LAST_LINE_IN_MENU, fcn));
7466 	}
7467 }
7468 
7469 /*
7470  * look for matching bootadm entry with specified parameters
7471  * Here are the rules (based on existing usage):
7472  * - If title is specified, match on title only
7473  * - Else, match on root/findroot, kernel, and module.
7474  *   Note that, if root_opt is non-zero, the absence of
7475  *   root line is considered a match.
7476  */
7477 static entry_t *
7478 find_boot_entry(
7479 	menu_t *mp,
7480 	char *title,
7481 	char *kernel,
7482 	char *findroot,
7483 	char *root,
7484 	char *module,
7485 	int root_opt,
7486 	int *entry_num)
7487 {
7488 	int		i;
7489 	line_t		*lp;
7490 	entry_t		*ent;
7491 	const char	*fcn = "find_boot_entry()";
7492 
7493 	if (entry_num)
7494 		*entry_num = BAM_ERROR;
7495 
7496 	/* find matching entry */
7497 	for (i = 0, ent = mp->entries; ent; i++, ent = ent->next) {
7498 		lp = ent->start;
7499 
7500 		/* first line of entry must be bootadm comment */
7501 		lp = ent->start;
7502 		if (lp->flags != BAM_COMMENT ||
7503 		    strcmp(lp->arg, BAM_BOOTADM_HDR) != 0) {
7504 			continue;
7505 		}
7506 
7507 		/* advance to title line */
7508 		lp = lp->next;
7509 		if (title) {
7510 			if (lp->flags == BAM_TITLE && lp->arg &&
7511 			    strcmp(lp->arg, title) == 0) {
7512 				BAM_DPRINTF((D_MATCHED_TITLE, fcn, title));
7513 				break;
7514 			}
7515 			BAM_DPRINTF((D_NOMATCH_TITLE, fcn, title, lp->arg));
7516 			continue;	/* check title only */
7517 		}
7518 
7519 		lp = lp->next;	/* advance to root line */
7520 		if (lp == NULL) {
7521 			continue;
7522 		} else if (strcmp(lp->cmd, menu_cmds[FINDROOT_CMD]) == 0) {
7523 			INJECT_ERROR1("FIND_BOOT_ENTRY_NULL_FINDROOT",
7524 			    findroot = NULL);
7525 			if (findroot == NULL) {
7526 				BAM_DPRINTF((D_NOMATCH_FINDROOT_NULL,
7527 				    fcn, lp->arg));
7528 				continue;
7529 			}
7530 			/* findroot command found, try match  */
7531 			if (strcmp(lp->arg, findroot) != 0) {
7532 				BAM_DPRINTF((D_NOMATCH_FINDROOT,
7533 				    fcn, findroot, lp->arg));
7534 				continue;
7535 			}
7536 			BAM_DPRINTF((D_MATCHED_FINDROOT, fcn, findroot));
7537 			lp = lp->next;	/* advance to kernel line */
7538 		} else if (strcmp(lp->cmd, menu_cmds[ROOT_CMD]) == 0) {
7539 			INJECT_ERROR1("FIND_BOOT_ENTRY_NULL_ROOT", root = NULL);
7540 			if (root == NULL) {
7541 				BAM_DPRINTF((D_NOMATCH_ROOT_NULL,
7542 				    fcn, lp->arg));
7543 				continue;
7544 			}
7545 			/* root cmd found, try match */
7546 			if (strcmp(lp->arg, root) != 0) {
7547 				BAM_DPRINTF((D_NOMATCH_ROOT,
7548 				    fcn, root, lp->arg));
7549 				continue;
7550 			}
7551 			BAM_DPRINTF((D_MATCHED_ROOT, fcn, root));
7552 			lp = lp->next;	/* advance to kernel line */
7553 		} else {
7554 			INJECT_ERROR1("FIND_BOOT_ENTRY_ROOT_OPT_NO",
7555 			    root_opt = 0);
7556 			INJECT_ERROR1("FIND_BOOT_ENTRY_ROOT_OPT_YES",
7557 			    root_opt = 1);
7558 			/* no root command, see if root is optional */
7559 			if (root_opt == 0) {
7560 				BAM_DPRINTF((D_NO_ROOT_OPT, fcn));
7561 				continue;
7562 			}
7563 			BAM_DPRINTF((D_ROOT_OPT, fcn));
7564 		}
7565 
7566 		if (lp == NULL || lp->next == NULL) {
7567 			continue;
7568 		}
7569 
7570 		if (kernel &&
7571 		    (!check_cmd(lp->cmd, KERNEL_CMD, lp->arg, kernel))) {
7572 			if (!(ent->flags & BAM_ENTRY_FAILSAFE) ||
7573 			    !(ent->flags & BAM_ENTRY_DBOOT) ||
7574 			    strcmp(kernel, DIRECT_BOOT_FAILSAFE_LINE) != 0)
7575 				continue;
7576 
7577 			ent->flags |= BAM_ENTRY_UPGFSKERNEL;
7578 
7579 		}
7580 		BAM_DPRINTF((D_KERNEL_MATCH, fcn, kernel, lp->arg));
7581 
7582 		/*
7583 		 * Check for matching module entry (failsafe or normal).
7584 		 * If it fails to match, we go around the loop again.
7585 		 * For xpv entries, there are two module lines, so we
7586 		 * do the check twice.
7587 		 */
7588 		lp = lp->next;	/* advance to module line */
7589 		if (check_cmd(lp->cmd, MODULE_CMD, lp->arg, module) ||
7590 		    (((lp = lp->next) != NULL) &&
7591 		    check_cmd(lp->cmd, MODULE_CMD, lp->arg, module))) {
7592 			/* match found */
7593 			BAM_DPRINTF((D_MODULE_MATCH, fcn, module, lp->arg));
7594 			break;
7595 		}
7596 
7597 		if (strcmp(module, FAILSAFE_ARCHIVE) == 0 &&
7598 		    (strcmp(lp->prev->arg, FAILSAFE_ARCHIVE_32) == 0 ||
7599 		    strcmp(lp->prev->arg, FAILSAFE_ARCHIVE_64) == 0)) {
7600 			ent->flags |= BAM_ENTRY_UPGFSMODULE;
7601 			break;
7602 		}
7603 
7604 	}
7605 
7606 	if (ent && entry_num) {
7607 		*entry_num = i;
7608 	}
7609 
7610 	if (ent) {
7611 		BAM_DPRINTF((D_RETURN_RET, fcn, i));
7612 	} else {
7613 		BAM_DPRINTF((D_RETURN_RET, fcn, BAM_ERROR));
7614 	}
7615 	return (ent);
7616 }
7617 
7618 static int
7619 update_boot_entry(menu_t *mp, char *title, char *findroot, char *root,
7620     char *kernel, char *mod_kernel, char *module, int root_opt)
7621 {
7622 	int		i;
7623 	int		change_kernel = 0;
7624 	entry_t		*ent;
7625 	line_t		*lp;
7626 	line_t		*tlp;
7627 	char		linebuf[BAM_MAXLINE];
7628 	const char	*fcn = "update_boot_entry()";
7629 
7630 	/* note: don't match on title, it's updated on upgrade */
7631 	ent = find_boot_entry(mp, NULL, kernel, findroot, root, module,
7632 	    root_opt, &i);
7633 	if ((ent == NULL) && (bam_direct == BAM_DIRECT_DBOOT)) {
7634 		/*
7635 		 * We may be upgrading a kernel from multiboot to
7636 		 * directboot.  Look for a multiboot entry. A multiboot
7637 		 * entry will not have a findroot line.
7638 		 */
7639 		ent = find_boot_entry(mp, NULL, "multiboot", NULL, root,
7640 		    MULTIBOOT_ARCHIVE, root_opt, &i);
7641 		if (ent != NULL) {
7642 			BAM_DPRINTF((D_UPGRADE_FROM_MULTIBOOT, fcn, root));
7643 			change_kernel = 1;
7644 		}
7645 	} else if (ent) {
7646 		BAM_DPRINTF((D_FOUND_FINDROOT, fcn, findroot));
7647 	}
7648 
7649 	if (ent == NULL) {
7650 		BAM_DPRINTF((D_ENTRY_NOT_FOUND_CREATING, fcn, findroot));
7651 		return (add_boot_entry(mp, title, findroot,
7652 		    kernel, mod_kernel, module));
7653 	}
7654 
7655 	/* replace title of existing entry and update findroot line */
7656 	lp = ent->start;
7657 	lp = lp->next;	/* title line */
7658 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
7659 	    menu_cmds[TITLE_CMD], menu_cmds[SEP_CMD], title);
7660 	free(lp->arg);
7661 	free(lp->line);
7662 	lp->arg = s_strdup(title);
7663 	lp->line = s_strdup(linebuf);
7664 	BAM_DPRINTF((D_CHANGING_TITLE, fcn, title));
7665 
7666 	tlp = lp;	/* title line */
7667 	lp = lp->next;	/* root line */
7668 
7669 	/* if no root or findroot command, create a new line_t */
7670 	if (strcmp(lp->cmd, menu_cmds[ROOT_CMD]) != 0 &&
7671 	    strcmp(lp->cmd, menu_cmds[FINDROOT_CMD]) != 0) {
7672 		lp = s_calloc(1, sizeof (line_t));
7673 		bam_add_line(mp, ent, tlp, lp);
7674 	} else {
7675 		free(lp->cmd);
7676 		free(lp->sep);
7677 		free(lp->arg);
7678 		free(lp->line);
7679 	}
7680 
7681 	lp->cmd = s_strdup(menu_cmds[FINDROOT_CMD]);
7682 	lp->sep = s_strdup(menu_cmds[SEP_CMD]);
7683 	lp->arg = s_strdup(findroot);
7684 	(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
7685 	    menu_cmds[FINDROOT_CMD], menu_cmds[SEP_CMD], findroot);
7686 	lp->line = s_strdup(linebuf);
7687 	BAM_DPRINTF((D_ADDING_FINDROOT_LINE, fcn, findroot));
7688 
7689 	/* kernel line */
7690 	lp = lp->next;
7691 
7692 	if (ent->flags & BAM_ENTRY_UPGFSKERNEL) {
7693 		char		*params = NULL;
7694 
7695 		params = strstr(lp->line, "-s");
7696 		if (params != NULL)
7697 			(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s%s",
7698 			    menu_cmds[KERNEL_DOLLAR_CMD], menu_cmds[SEP_CMD],
7699 			    kernel, params+2);
7700 		else
7701 			(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
7702 			    menu_cmds[KERNEL_DOLLAR_CMD], menu_cmds[SEP_CMD],
7703 			    kernel);
7704 
7705 		free(lp->cmd);
7706 		free(lp->arg);
7707 		free(lp->line);
7708 		lp->cmd = s_strdup(menu_cmds[KERNEL_DOLLAR_CMD]);
7709 		lp->arg = s_strdup(strstr(linebuf, "/"));
7710 		lp->line = s_strdup(linebuf);
7711 		ent->flags &= ~BAM_ENTRY_UPGFSKERNEL;
7712 		BAM_DPRINTF((D_ADDING_KERNEL_DOLLAR, fcn, lp->prev->cmd));
7713 	}
7714 
7715 	if (change_kernel) {
7716 		/*
7717 		 * We're upgrading from multiboot to directboot.
7718 		 */
7719 		if (strcmp(lp->cmd, menu_cmds[KERNEL_CMD]) == 0) {
7720 			(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
7721 			    menu_cmds[KERNEL_DOLLAR_CMD], menu_cmds[SEP_CMD],
7722 			    kernel);
7723 			free(lp->cmd);
7724 			free(lp->arg);
7725 			free(lp->line);
7726 			lp->cmd = s_strdup(menu_cmds[KERNEL_DOLLAR_CMD]);
7727 			lp->arg = s_strdup(kernel);
7728 			lp->line = s_strdup(linebuf);
7729 			lp = lp->next;
7730 			BAM_DPRINTF((D_ADDING_KERNEL_DOLLAR, fcn, kernel));
7731 		}
7732 		if (strcmp(lp->cmd, menu_cmds[MODULE_CMD]) == 0) {
7733 			(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
7734 			    menu_cmds[MODULE_DOLLAR_CMD], menu_cmds[SEP_CMD],
7735 			    module);
7736 			free(lp->cmd);
7737 			free(lp->arg);
7738 			free(lp->line);
7739 			lp->cmd = s_strdup(menu_cmds[MODULE_DOLLAR_CMD]);
7740 			lp->arg = s_strdup(module);
7741 			lp->line = s_strdup(linebuf);
7742 			lp = lp->next;
7743 			BAM_DPRINTF((D_ADDING_MODULE_DOLLAR, fcn, module));
7744 		}
7745 	}
7746 
7747 	/* module line */
7748 	lp = lp->next;
7749 
7750 	if (ent->flags & BAM_ENTRY_UPGFSMODULE) {
7751 		if (strcmp(lp->cmd, menu_cmds[MODULE_CMD]) == 0) {
7752 			(void) snprintf(linebuf, sizeof (linebuf), "%s%s%s",
7753 			    menu_cmds[MODULE_DOLLAR_CMD], menu_cmds[SEP_CMD],
7754 			    module);
7755 			free(lp->cmd);
7756 			free(lp->arg);
7757 			free(lp->line);
7758 			lp->cmd = s_strdup(menu_cmds[MODULE_DOLLAR_CMD]);
7759 			lp->arg = s_strdup(module);
7760 			lp->line = s_strdup(linebuf);
7761 			lp = lp->next;
7762 			ent->flags &= ~BAM_ENTRY_UPGFSMODULE;
7763 			BAM_DPRINTF((D_ADDING_MODULE_DOLLAR, fcn, module));
7764 		}
7765 	}
7766 
7767 	BAM_DPRINTF((D_RETURN_RET, fcn, i));
7768 	return (i);
7769 }
7770 
7771 int
7772 root_optional(char *osroot, char *menu_root)
7773 {
7774 	char			*ospecial;
7775 	char			*mspecial;
7776 	char			*slash;
7777 	int			root_opt;
7778 	int			ret1;
7779 	int			ret2;
7780 	const char		*fcn = "root_optional()";
7781 
7782 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, menu_root));
7783 
7784 	/*
7785 	 * For all filesystems except ZFS, a straight compare of osroot
7786 	 * and menu_root will tell us if root is optional.
7787 	 * For ZFS, the situation is complicated by the fact that
7788 	 * menu_root and osroot are always different
7789 	 */
7790 	ret1 = is_zfs(osroot);
7791 	ret2 = is_zfs(menu_root);
7792 	INJECT_ERROR1("ROOT_OPT_NOT_ZFS", ret1 = 0);
7793 	if (!ret1 || !ret2) {
7794 		BAM_DPRINTF((D_ROOT_OPT_NOT_ZFS, fcn, osroot, menu_root));
7795 		root_opt = (strcmp(osroot, menu_root) == 0);
7796 		goto out;
7797 	}
7798 
7799 	ospecial = get_special(osroot);
7800 	INJECT_ERROR1("ROOT_OPTIONAL_OSPECIAL", ospecial = NULL);
7801 	if (ospecial == NULL) {
7802 		bam_error(GET_OSROOT_SPECIAL_ERR, osroot);
7803 		return (0);
7804 	}
7805 	BAM_DPRINTF((D_ROOT_OPTIONAL_OSPECIAL, fcn, ospecial, osroot));
7806 
7807 	mspecial = get_special(menu_root);
7808 	INJECT_ERROR1("ROOT_OPTIONAL_MSPECIAL", mspecial = NULL);
7809 	if (mspecial == NULL) {
7810 		bam_error(GET_MENU_ROOT_SPECIAL_ERR, menu_root);
7811 		free(ospecial);
7812 		return (0);
7813 	}
7814 	BAM_DPRINTF((D_ROOT_OPTIONAL_MSPECIAL, fcn, mspecial, menu_root));
7815 
7816 	slash = strchr(ospecial, '/');
7817 	if (slash)
7818 		*slash = '\0';
7819 	BAM_DPRINTF((D_ROOT_OPTIONAL_FIXED_OSPECIAL, fcn, ospecial, osroot));
7820 
7821 	root_opt = (strcmp(ospecial, mspecial) == 0);
7822 
7823 	free(ospecial);
7824 	free(mspecial);
7825 
7826 out:
7827 	INJECT_ERROR1("ROOT_OPTIONAL_NO", root_opt = 0);
7828 	INJECT_ERROR1("ROOT_OPTIONAL_YES", root_opt = 1);
7829 	if (root_opt) {
7830 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
7831 	} else {
7832 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
7833 	}
7834 
7835 	return (root_opt);
7836 }
7837 
7838 /*ARGSUSED*/
7839 static error_t
7840 update_entry(menu_t *mp, char *menu_root, char *osdev)
7841 {
7842 	int		entry;
7843 	char		*grubsign;
7844 	char		*grubroot;
7845 	char		*title;
7846 	char		osroot[PATH_MAX];
7847 	char		*failsafe_kernel = NULL;
7848 	struct stat	sbuf;
7849 	char		failsafe[256];
7850 	char		failsafe_64[256];
7851 	int		ret;
7852 	const char	*fcn = "update_entry()";
7853 
7854 	assert(mp);
7855 	assert(menu_root);
7856 	assert(osdev);
7857 	assert(bam_root);
7858 
7859 	BAM_DPRINTF((D_FUNC_ENTRY3, fcn, menu_root, osdev, bam_root));
7860 
7861 	(void) strlcpy(osroot, bam_root, sizeof (osroot));
7862 
7863 	title = get_title(osroot);
7864 	assert(title);
7865 
7866 	grubsign = get_grubsign(osroot, osdev);
7867 	INJECT_ERROR1("GET_GRUBSIGN_FAIL", grubsign = NULL);
7868 	if (grubsign == NULL) {
7869 		bam_error(GET_GRUBSIGN_ERROR, osroot, osdev);
7870 		return (BAM_ERROR);
7871 	}
7872 
7873 	/*
7874 	 * It is not a fatal error if get_grubroot() fails
7875 	 * We no longer rely on biosdev to populate the
7876 	 * menu
7877 	 */
7878 	grubroot = get_grubroot(osroot, osdev, menu_root);
7879 	INJECT_ERROR1("GET_GRUBROOT_FAIL", grubroot = NULL);
7880 	if (grubroot) {
7881 		BAM_DPRINTF((D_GET_GRUBROOT_SUCCESS,
7882 		    fcn, osroot, osdev, menu_root));
7883 	} else {
7884 		BAM_DPRINTF((D_GET_GRUBROOT_FAILURE,
7885 		    fcn, osroot, osdev, menu_root));
7886 	}
7887 
7888 	/* add the entry for normal Solaris */
7889 	INJECT_ERROR1("UPDATE_ENTRY_MULTIBOOT",
7890 	    bam_direct = BAM_DIRECT_MULTIBOOT);
7891 	if (bam_direct == BAM_DIRECT_DBOOT) {
7892 		entry = update_boot_entry(mp, title, grubsign, grubroot,
7893 		    (bam_zfs ? DIRECT_BOOT_KERNEL_ZFS : DIRECT_BOOT_KERNEL),
7894 		    NULL, DIRECT_BOOT_ARCHIVE,
7895 		    root_optional(osroot, menu_root));
7896 		BAM_DPRINTF((D_UPDATED_BOOT_ENTRY, fcn, bam_zfs, grubsign));
7897 		if ((entry != BAM_ERROR) && (bam_is_hv == BAM_HV_PRESENT)) {
7898 			(void) update_boot_entry(mp, NEW_HV_ENTRY, grubsign,
7899 			    grubroot, XEN_MENU, bam_zfs ?
7900 			    XEN_KERNEL_MODULE_LINE_ZFS : XEN_KERNEL_MODULE_LINE,
7901 			    DIRECT_BOOT_ARCHIVE,
7902 			    root_optional(osroot, menu_root));
7903 			BAM_DPRINTF((D_UPDATED_HV_ENTRY,
7904 			    fcn, bam_zfs, grubsign));
7905 		}
7906 	} else {
7907 		entry = update_boot_entry(mp, title, grubsign, grubroot,
7908 		    MULTI_BOOT, NULL, MULTIBOOT_ARCHIVE,
7909 		    root_optional(osroot, menu_root));
7910 
7911 		BAM_DPRINTF((D_UPDATED_MULTIBOOT_ENTRY, fcn, grubsign));
7912 	}
7913 
7914 	/*
7915 	 * Add the entry for failsafe archive.  On a bfu'd system, the
7916 	 * failsafe may be different than the installed kernel.
7917 	 */
7918 	(void) snprintf(failsafe, sizeof (failsafe), "%s%s",
7919 	    osroot, FAILSAFE_ARCHIVE_32);
7920 	(void) snprintf(failsafe_64, sizeof (failsafe_64), "%s%s",
7921 	    osroot, FAILSAFE_ARCHIVE_64);
7922 
7923 	/*
7924 	 * Check if at least one of the two archives exists
7925 	 * Using $ISADIR as the default line, we have an entry which works
7926 	 * for both the cases.
7927 	 */
7928 
7929 	if (stat(failsafe, &sbuf) == 0 || stat(failsafe_64, &sbuf) == 0) {
7930 
7931 		/* Figure out where the kernel line should point */
7932 		(void) snprintf(failsafe, sizeof (failsafe), "%s%s", osroot,
7933 		    DIRECT_BOOT_FAILSAFE_32);
7934 		(void) snprintf(failsafe_64, sizeof (failsafe_64), "%s%s",
7935 		    osroot, DIRECT_BOOT_FAILSAFE_64);
7936 		if (stat(failsafe, &sbuf) == 0 ||
7937 		    stat(failsafe_64, &sbuf) == 0) {
7938 			failsafe_kernel = DIRECT_BOOT_FAILSAFE_LINE;
7939 		} else {
7940 			(void) snprintf(failsafe, sizeof (failsafe), "%s%s",
7941 			    osroot, MULTI_BOOT_FAILSAFE);
7942 			if (stat(failsafe, &sbuf) == 0) {
7943 				failsafe_kernel = MULTI_BOOT_FAILSAFE_LINE;
7944 			}
7945 		}
7946 		if (failsafe_kernel != NULL) {
7947 			(void) update_boot_entry(mp, FAILSAFE_TITLE, grubsign,
7948 			    grubroot, failsafe_kernel, NULL, FAILSAFE_ARCHIVE,
7949 			    root_optional(osroot, menu_root));
7950 			BAM_DPRINTF((D_UPDATED_FAILSAFE_ENTRY, fcn,
7951 			    failsafe_kernel));
7952 		}
7953 	}
7954 	free(grubroot);
7955 
7956 	INJECT_ERROR1("UPDATE_ENTRY_ERROR", entry = BAM_ERROR);
7957 	if (entry == BAM_ERROR) {
7958 		bam_error(FAILED_TO_ADD_BOOT_ENTRY, title, grubsign);
7959 		free(grubsign);
7960 		return (BAM_ERROR);
7961 	}
7962 	free(grubsign);
7963 
7964 	update_numbering(mp);
7965 	ret = set_global(mp, menu_cmds[DEFAULT_CMD], entry);
7966 	INJECT_ERROR1("SET_DEFAULT_ERROR", ret = BAM_ERROR);
7967 	if (ret == BAM_ERROR) {
7968 		bam_error(SET_DEFAULT_FAILED, entry);
7969 	}
7970 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
7971 	return (BAM_WRITE);
7972 }
7973 
7974 static void
7975 save_default_entry(menu_t *mp, const char *which)
7976 {
7977 	int		lineNum;
7978 	int		entryNum;
7979 	int		entry = 0;	/* default is 0 */
7980 	char		linebuf[BAM_MAXLINE];
7981 	line_t		*lp = mp->curdefault;
7982 	const char	*fcn = "save_default_entry()";
7983 
7984 	if (mp->start) {
7985 		lineNum = mp->end->lineNum;
7986 		entryNum = mp->end->entryNum;
7987 	} else {
7988 		lineNum = LINE_INIT;
7989 		entryNum = ENTRY_INIT;
7990 	}
7991 
7992 	if (lp)
7993 		entry = s_strtol(lp->arg);
7994 
7995 	(void) snprintf(linebuf, sizeof (linebuf), "#%s%d", which, entry);
7996 	BAM_DPRINTF((D_SAVING_DEFAULT_TO, fcn, linebuf));
7997 	line_parser(mp, linebuf, &lineNum, &entryNum);
7998 	BAM_DPRINTF((D_SAVED_DEFAULT_TO, fcn, lineNum, entryNum));
7999 }
8000 
8001 static void
8002 restore_default_entry(menu_t *mp, const char *which, line_t *lp)
8003 {
8004 	int		entry;
8005 	char		*str;
8006 	const char	*fcn = "restore_default_entry()";
8007 
8008 	if (lp == NULL) {
8009 		BAM_DPRINTF((D_RESTORE_DEFAULT_NULL, fcn));
8010 		return;		/* nothing to restore */
8011 	}
8012 
8013 	BAM_DPRINTF((D_RESTORE_DEFAULT_STR, fcn, which));
8014 
8015 	str = lp->arg + strlen(which);
8016 	entry = s_strtol(str);
8017 	(void) set_global(mp, menu_cmds[DEFAULT_CMD], entry);
8018 
8019 	BAM_DPRINTF((D_RESTORED_DEFAULT_TO, fcn, entry));
8020 
8021 	/* delete saved old default line */
8022 	unlink_line(mp, lp);
8023 	line_free(lp);
8024 }
8025 
8026 /*
8027  * This function is for supporting reboot with args.
8028  * The opt value can be:
8029  * NULL		delete temp entry, if present
8030  * entry=<n>	switches default entry to <n>
8031  * else		treated as boot-args and setup a temperary menu entry
8032  *		and make it the default
8033  * Note that we are always rebooting the current OS instance
8034  * so osroot == / always.
8035  */
8036 #define	REBOOT_TITLE	"Solaris_reboot_transient"
8037 
8038 /*ARGSUSED*/
8039 static error_t
8040 update_temp(menu_t *mp, char *dummy, char *opt)
8041 {
8042 	int		entry;
8043 	char		*osdev;
8044 	char		*fstype;
8045 	char		*sign;
8046 	char		*opt_ptr;
8047 	char		*path;
8048 	char		kernbuf[BUFSIZ];
8049 	char		args_buf[BUFSIZ];
8050 	char		signbuf[PATH_MAX];
8051 	int		ret;
8052 	const char	*fcn = "update_temp()";
8053 
8054 	assert(mp);
8055 	assert(dummy == NULL);
8056 
8057 	/* opt can be NULL */
8058 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, opt ? opt : "<NULL>"));
8059 	BAM_DPRINTF((D_BAM_ROOT, fcn, bam_alt_root, bam_root));
8060 
8061 	if (bam_alt_root || bam_rootlen != 1 ||
8062 	    strcmp(bam_root, "/") != 0 ||
8063 	    strcmp(rootbuf, "/") != 0) {
8064 		bam_error(ALT_ROOT_INVALID, bam_root);
8065 		return (BAM_ERROR);
8066 	}
8067 
8068 	/* If no option, delete exiting reboot menu entry */
8069 	if (opt == NULL) {
8070 		entry_t		*ent;
8071 		BAM_DPRINTF((D_OPT_NULL, fcn));
8072 		ent = find_boot_entry(mp, REBOOT_TITLE, NULL, NULL,
8073 		    NULL, NULL, 0, &entry);
8074 		if (ent == NULL) {	/* not found is ok */
8075 			BAM_DPRINTF((D_TRANSIENT_NOTFOUND, fcn));
8076 			return (BAM_SUCCESS);
8077 		}
8078 		(void) do_delete(mp, entry);
8079 		restore_default_entry(mp, BAM_OLDDEF, mp->olddefault);
8080 		mp->olddefault = NULL;
8081 		BAM_DPRINTF((D_RESTORED_DEFAULT, fcn));
8082 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8083 		return (BAM_WRITE);
8084 	}
8085 
8086 	/* if entry= is specified, set the default entry */
8087 	if (strncmp(opt, "entry=", strlen("entry=")) == 0) {
8088 		int entryNum = s_strtol(opt + strlen("entry="));
8089 		BAM_DPRINTF((D_ENTRY_EQUALS, fcn, opt));
8090 		if (selector(mp, opt, &entry, NULL) == BAM_SUCCESS) {
8091 			/* this is entry=# option */
8092 			ret = set_global(mp, menu_cmds[DEFAULT_CMD], entry);
8093 			BAM_DPRINTF((D_ENTRY_SET_IS, fcn, entry, ret));
8094 			return (ret);
8095 		} else {
8096 			bam_error(SET_DEFAULT_FAILED, entryNum);
8097 			return (BAM_ERROR);
8098 		}
8099 	}
8100 
8101 	/*
8102 	 * add a new menu entry based on opt and make it the default
8103 	 */
8104 
8105 	fstype = get_fstype("/");
8106 	INJECT_ERROR1("REBOOT_FSTYPE_NULL", fstype = NULL);
8107 	if (fstype == NULL) {
8108 		bam_error(REBOOT_FSTYPE_FAILED);
8109 		return (BAM_ERROR);
8110 	}
8111 
8112 	osdev = get_special("/");
8113 	INJECT_ERROR1("REBOOT_SPECIAL_NULL", osdev = NULL);
8114 	if (osdev == NULL) {
8115 		free(fstype);
8116 		bam_error(REBOOT_SPECIAL_FAILED);
8117 		return (BAM_ERROR);
8118 	}
8119 
8120 	sign = find_existing_sign("/", osdev, fstype);
8121 	INJECT_ERROR1("REBOOT_SIGN_NULL", sign = NULL);
8122 	if (sign == NULL) {
8123 		free(fstype);
8124 		free(osdev);
8125 		bam_error(REBOOT_SIGN_FAILED);
8126 		return (BAM_ERROR);
8127 	}
8128 
8129 	free(osdev);
8130 	(void) strlcpy(signbuf, sign, sizeof (signbuf));
8131 	free(sign);
8132 
8133 	assert(strchr(signbuf, '(') == NULL && strchr(signbuf, ',') == NULL &&
8134 	    strchr(signbuf, ')') == NULL);
8135 
8136 	/*
8137 	 * There is no alternate root while doing reboot with args
8138 	 * This version of bootadm is only delivered with a DBOOT
8139 	 * version of Solaris.
8140 	 */
8141 	INJECT_ERROR1("REBOOT_NOT_DBOOT", bam_direct = BAM_DIRECT_MULTIBOOT);
8142 	if (bam_direct != BAM_DIRECT_DBOOT) {
8143 		free(fstype);
8144 		bam_error(REBOOT_DIRECT_FAILED);
8145 		return (BAM_ERROR);
8146 	}
8147 
8148 	/* add an entry for Solaris reboot */
8149 	if (opt[0] == '-') {
8150 		/* It's an option - first see if boot-file is set */
8151 		ret = get_kernel(mp, KERNEL_CMD, kernbuf, sizeof (kernbuf));
8152 		INJECT_ERROR1("REBOOT_GET_KERNEL", ret = BAM_ERROR);
8153 		if (ret != BAM_SUCCESS) {
8154 			free(fstype);
8155 			bam_error(REBOOT_GET_KERNEL_FAILED);
8156 			return (BAM_ERROR);
8157 		}
8158 		if (kernbuf[0] == '\0')
8159 			(void) strlcpy(kernbuf, DIRECT_BOOT_KERNEL,
8160 			    sizeof (kernbuf));
8161 		/*
8162 		 * If this is a zfs file system and kernbuf does not
8163 		 * have "-B $ZFS-BOOTFS" string yet, add it.
8164 		 */
8165 		if (strcmp(fstype, "zfs") == 0 && !strstr(kernbuf, ZFS_BOOT)) {
8166 			(void) strlcat(kernbuf, " ", sizeof (kernbuf));
8167 			(void) strlcat(kernbuf, ZFS_BOOT, sizeof (kernbuf));
8168 		}
8169 		(void) strlcat(kernbuf, " ", sizeof (kernbuf));
8170 		(void) strlcat(kernbuf, opt, sizeof (kernbuf));
8171 		BAM_DPRINTF((D_REBOOT_OPTION, fcn, kernbuf));
8172 	} else if (opt[0] == '/') {
8173 		/* It's a full path, so write it out. */
8174 		(void) strlcpy(kernbuf, opt, sizeof (kernbuf));
8175 
8176 		/*
8177 		 * If someone runs:
8178 		 *
8179 		 *	# eeprom boot-args='-kd'
8180 		 *	# reboot /platform/i86pc/kernel/unix
8181 		 *
8182 		 * we want to use the boot-args as part of the boot
8183 		 * line.  On the other hand, if someone runs:
8184 		 *
8185 		 *	# reboot "/platform/i86pc/kernel/unix -kd"
8186 		 *
8187 		 * we don't need to mess with boot-args.  If there's
8188 		 * no space in the options string, assume we're in the
8189 		 * first case.
8190 		 */
8191 		if (strchr(opt, ' ') == NULL) {
8192 			ret = get_kernel(mp, ARGS_CMD, args_buf,
8193 			    sizeof (args_buf));
8194 			INJECT_ERROR1("REBOOT_GET_ARGS", ret = BAM_ERROR);
8195 			if (ret != BAM_SUCCESS) {
8196 				free(fstype);
8197 				bam_error(REBOOT_GET_ARGS_FAILED);
8198 				return (BAM_ERROR);
8199 			}
8200 
8201 			if (args_buf[0] != '\0') {
8202 				(void) strlcat(kernbuf, " ", sizeof (kernbuf));
8203 				(void) strlcat(kernbuf, args_buf,
8204 				    sizeof (kernbuf));
8205 			}
8206 		}
8207 		BAM_DPRINTF((D_REBOOT_ABSPATH, fcn, kernbuf));
8208 	} else {
8209 		/*
8210 		 * It may be a partial path, or it may be a partial
8211 		 * path followed by options.  Assume that only options
8212 		 * follow a space.  If someone sends us a kernel path
8213 		 * that includes a space, they deserve to be broken.
8214 		 */
8215 		opt_ptr = strchr(opt, ' ');
8216 		if (opt_ptr != NULL) {
8217 			*opt_ptr = '\0';
8218 		}
8219 
8220 		path = expand_path(opt);
8221 		if (path != NULL) {
8222 			(void) strlcpy(kernbuf, path, sizeof (kernbuf));
8223 			free(path);
8224 
8225 			/*
8226 			 * If there were options given, use those.
8227 			 * Otherwise, copy over the default options.
8228 			 */
8229 			if (opt_ptr != NULL) {
8230 				/* Restore the space in opt string */
8231 				*opt_ptr = ' ';
8232 				(void) strlcat(kernbuf, opt_ptr,
8233 				    sizeof (kernbuf));
8234 			} else {
8235 				ret = get_kernel(mp, ARGS_CMD, args_buf,
8236 				    sizeof (args_buf));
8237 				INJECT_ERROR1("UPDATE_TEMP_PARTIAL_ARGS",
8238 				    ret = BAM_ERROR);
8239 				if (ret != BAM_SUCCESS) {
8240 					free(fstype);
8241 					bam_error(REBOOT_GET_ARGS_FAILED);
8242 					return (BAM_ERROR);
8243 				}
8244 
8245 				if (args_buf[0] != '\0') {
8246 					(void) strlcat(kernbuf, " ",
8247 					    sizeof (kernbuf));
8248 					(void) strlcat(kernbuf,
8249 					    args_buf, sizeof (kernbuf));
8250 				}
8251 			}
8252 			BAM_DPRINTF((D_REBOOT_RESOLVED_PARTIAL, fcn, kernbuf));
8253 		} else {
8254 			free(fstype);
8255 			bam_error(UNKNOWN_KERNEL, opt);
8256 			bam_print_stderr(UNKNOWN_KERNEL_REBOOT);
8257 			return (BAM_ERROR);
8258 		}
8259 	}
8260 	free(fstype);
8261 	entry = add_boot_entry(mp, REBOOT_TITLE, signbuf, kernbuf,
8262 	    NULL, NULL);
8263 	INJECT_ERROR1("REBOOT_ADD_BOOT_ENTRY", entry = BAM_ERROR);
8264 	if (entry == BAM_ERROR) {
8265 		bam_error(REBOOT_WITH_ARGS_ADD_ENTRY_FAILED);
8266 		return (BAM_ERROR);
8267 	}
8268 
8269 	save_default_entry(mp, BAM_OLDDEF);
8270 	ret = set_global(mp, menu_cmds[DEFAULT_CMD], entry);
8271 	INJECT_ERROR1("REBOOT_SET_GLOBAL", ret = BAM_ERROR);
8272 	if (ret == BAM_ERROR) {
8273 		bam_error(REBOOT_SET_DEFAULT_FAILED, entry);
8274 	}
8275 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8276 	return (BAM_WRITE);
8277 }
8278 
8279 static error_t
8280 set_global(menu_t *mp, char *globalcmd, int val)
8281 {
8282 	line_t		*lp;
8283 	line_t		*found;
8284 	line_t		*last;
8285 	char		*cp;
8286 	char		*str;
8287 	char		prefix[BAM_MAXLINE];
8288 	size_t		len;
8289 	const char	*fcn = "set_global()";
8290 
8291 	assert(mp);
8292 	assert(globalcmd);
8293 
8294 	if (strcmp(globalcmd, menu_cmds[DEFAULT_CMD]) == 0) {
8295 		INJECT_ERROR1("SET_GLOBAL_VAL_NEG", val = -1);
8296 		INJECT_ERROR1("SET_GLOBAL_MENU_EMPTY", mp->end = NULL);
8297 		INJECT_ERROR1("SET_GLOBAL_VAL_TOO_BIG", val = 100);
8298 		if (val < 0 || mp->end == NULL || val > mp->end->entryNum) {
8299 			(void) snprintf(prefix, sizeof (prefix), "%d", val);
8300 			bam_error(INVALID_ENTRY, prefix);
8301 			return (BAM_ERROR);
8302 		}
8303 	}
8304 
8305 	found = last = NULL;
8306 	for (lp = mp->start; lp; lp = lp->next) {
8307 		if (lp->flags != BAM_GLOBAL)
8308 			continue;
8309 
8310 		last = lp; /* track the last global found */
8311 
8312 		INJECT_ERROR1("SET_GLOBAL_NULL_CMD", lp->cmd = NULL);
8313 		if (lp->cmd == NULL) {
8314 			bam_error(NO_CMD, lp->lineNum);
8315 			continue;
8316 		}
8317 		if (strcmp(globalcmd, lp->cmd) != 0)
8318 			continue;
8319 
8320 		BAM_DPRINTF((D_FOUND_GLOBAL, fcn, globalcmd));
8321 
8322 		if (found) {
8323 			bam_error(DUP_CMD, globalcmd, lp->lineNum, bam_root);
8324 		}
8325 		found = lp;
8326 	}
8327 
8328 	if (found == NULL) {
8329 		lp = s_calloc(1, sizeof (line_t));
8330 		if (last == NULL) {
8331 			lp->next = mp->start;
8332 			mp->start = lp;
8333 			mp->end = (mp->end) ? mp->end : lp;
8334 		} else {
8335 			lp->next = last->next;
8336 			last->next = lp;
8337 			if (lp->next == NULL)
8338 				mp->end = lp;
8339 		}
8340 		lp->flags = BAM_GLOBAL; /* other fields not needed for writes */
8341 		len = strlen(globalcmd) + strlen(menu_cmds[SEP_CMD]);
8342 		len += 10;	/* val < 10 digits */
8343 		lp->line = s_calloc(1, len);
8344 		(void) snprintf(lp->line, len, "%s%s%d",
8345 		    globalcmd, menu_cmds[SEP_CMD], val);
8346 		BAM_DPRINTF((D_SET_GLOBAL_WROTE_NEW, fcn, lp->line));
8347 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8348 		return (BAM_WRITE);
8349 	}
8350 
8351 	/*
8352 	 * We are changing an existing entry. Retain any prefix whitespace,
8353 	 * but overwrite everything else. This preserves tabs added for
8354 	 * readability.
8355 	 */
8356 	str = found->line;
8357 	cp = prefix;
8358 	while (*str == ' ' || *str == '\t')
8359 		*(cp++) = *(str++);
8360 	*cp = '\0'; /* Terminate prefix */
8361 	len = strlen(prefix) + strlen(globalcmd);
8362 	len += strlen(menu_cmds[SEP_CMD]) + 10;
8363 
8364 	free(found->line);
8365 	found->line = s_calloc(1, len);
8366 	(void) snprintf(found->line, len,
8367 	    "%s%s%s%d", prefix, globalcmd, menu_cmds[SEP_CMD], val);
8368 
8369 	BAM_DPRINTF((D_SET_GLOBAL_REPLACED, fcn, found->line));
8370 	BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8371 	return (BAM_WRITE); /* need a write to menu */
8372 }
8373 
8374 /*
8375  * partial_path may be anything like "kernel/unix" or "kmdb".  Try to
8376  * expand it to a full unix path.  The calling function is expected to
8377  * output a message if an error occurs and NULL is returned.
8378  */
8379 static char *
8380 expand_path(const char *partial_path)
8381 {
8382 	int		new_path_len;
8383 	char		*new_path;
8384 	char		new_path2[PATH_MAX];
8385 	struct stat	sb;
8386 	const char	*fcn = "expand_path()";
8387 
8388 	new_path_len = strlen(partial_path) + 64;
8389 	new_path = s_calloc(1, new_path_len);
8390 
8391 	/* First, try the simplest case - something like "kernel/unix" */
8392 	(void) snprintf(new_path, new_path_len, "/platform/i86pc/%s",
8393 	    partial_path);
8394 	if (stat(new_path, &sb) == 0) {
8395 		BAM_DPRINTF((D_EXPAND_PATH, fcn, new_path));
8396 		return (new_path);
8397 	}
8398 
8399 	if (strcmp(partial_path, "kmdb") == 0) {
8400 		(void) snprintf(new_path, new_path_len, "%s -k",
8401 		    DIRECT_BOOT_KERNEL);
8402 		BAM_DPRINTF((D_EXPAND_PATH, fcn, new_path));
8403 		return (new_path);
8404 	}
8405 
8406 	/*
8407 	 * We've quickly reached unsupported usage.  Try once more to
8408 	 * see if we were just given a glom name.
8409 	 */
8410 	(void) snprintf(new_path, new_path_len, "/platform/i86pc/%s/unix",
8411 	    partial_path);
8412 	(void) snprintf(new_path2, PATH_MAX, "/platform/i86pc/%s/amd64/unix",
8413 	    partial_path);
8414 	if (stat(new_path, &sb) == 0) {
8415 		if (stat(new_path2, &sb) == 0) {
8416 			/*
8417 			 * We matched both, so we actually
8418 			 * want to write the $ISADIR version.
8419 			 */
8420 			(void) snprintf(new_path, new_path_len,
8421 			    "/platform/i86pc/kernel/%s/$ISADIR/unix",
8422 			    partial_path);
8423 		}
8424 		BAM_DPRINTF((D_EXPAND_PATH, fcn, new_path));
8425 		return (new_path);
8426 	}
8427 
8428 	free(new_path);
8429 	BAM_DPRINTF((D_RETURN_FAILURE, fcn));
8430 	return (NULL);
8431 }
8432 
8433 /*
8434  * The kernel cmd and arg have been changed, so
8435  * check whether the archive line needs to change.
8436  */
8437 static void
8438 set_archive_line(entry_t *entryp, line_t *kernelp)
8439 {
8440 	line_t		*lp = entryp->start;
8441 	char		*new_archive;
8442 	menu_cmd_t	m_cmd;
8443 	const char	*fcn = "set_archive_line()";
8444 
8445 	for (; lp != NULL; lp = lp->next) {
8446 		if (strncmp(lp->cmd, menu_cmds[MODULE_CMD],
8447 		    sizeof (menu_cmds[MODULE_CMD]) - 1) == 0) {
8448 			break;
8449 		}
8450 
8451 		INJECT_ERROR1("SET_ARCHIVE_LINE_END_ENTRY", lp = entryp->end);
8452 		if (lp == entryp->end) {
8453 			BAM_DPRINTF((D_ARCHIVE_LINE_NONE, fcn,
8454 			    entryp->entryNum));
8455 			return;
8456 		}
8457 	}
8458 	INJECT_ERROR1("SET_ARCHIVE_LINE_END_MENU", lp = NULL);
8459 	if (lp == NULL) {
8460 		BAM_DPRINTF((D_ARCHIVE_LINE_NONE, fcn, entryp->entryNum));
8461 		return;
8462 	}
8463 
8464 	if (strstr(kernelp->arg, "$ISADIR") != NULL) {
8465 		new_archive = DIRECT_BOOT_ARCHIVE;
8466 		m_cmd = MODULE_DOLLAR_CMD;
8467 	} else if (strstr(kernelp->arg, "amd64") != NULL) {
8468 		new_archive = DIRECT_BOOT_ARCHIVE_64;
8469 		m_cmd = MODULE_CMD;
8470 	} else {
8471 		new_archive = DIRECT_BOOT_ARCHIVE_32;
8472 		m_cmd = MODULE_CMD;
8473 	}
8474 
8475 	if (strcmp(lp->arg, new_archive) == 0) {
8476 		BAM_DPRINTF((D_ARCHIVE_LINE_NOCHANGE, fcn, lp->arg));
8477 		return;
8478 	}
8479 
8480 	if (strcmp(lp->cmd, menu_cmds[m_cmd]) != 0) {
8481 		free(lp->cmd);
8482 		lp->cmd = s_strdup(menu_cmds[m_cmd]);
8483 	}
8484 
8485 	free(lp->arg);
8486 	lp->arg = s_strdup(new_archive);
8487 	update_line(lp);
8488 	BAM_DPRINTF((D_ARCHIVE_LINE_REPLACED, fcn, lp->line));
8489 }
8490 
8491 /*
8492  * Title for an entry to set properties that once went in bootenv.rc.
8493  */
8494 #define	BOOTENV_RC_TITLE	"Solaris bootenv rc"
8495 
8496 /*
8497  * If path is NULL, return the kernel (optnum == KERNEL_CMD) or arguments
8498  * (optnum == ARGS_CMD) in the argument buf.  If path is a zero-length
8499  * string, reset the value to the default.  If path is a non-zero-length
8500  * string, set the kernel or arguments.
8501  */
8502 static error_t
8503 get_set_kernel(
8504 	menu_t *mp,
8505 	menu_cmd_t optnum,
8506 	char *path,
8507 	char *buf,
8508 	size_t bufsize)
8509 {
8510 	int		entryNum;
8511 	int		rv = BAM_SUCCESS;
8512 	int		free_new_path = 0;
8513 	entry_t		*entryp;
8514 	line_t		*ptr;
8515 	line_t		*kernelp;
8516 	char		*new_arg;
8517 	char		*old_args;
8518 	char		*space;
8519 	char		*new_path;
8520 	char		old_space;
8521 	size_t		old_kernel_len;
8522 	size_t		new_str_len;
8523 	char		*fstype;
8524 	char		*osdev;
8525 	char		*sign;
8526 	char		signbuf[PATH_MAX];
8527 	int		ret;
8528 	const char	*fcn = "get_set_kernel()";
8529 
8530 	assert(bufsize > 0);
8531 
8532 	ptr = kernelp = NULL;
8533 	new_arg = old_args = space = NULL;
8534 	new_path = NULL;
8535 	buf[0] = '\0';
8536 
8537 	INJECT_ERROR1("GET_SET_KERNEL_NOT_DBOOT",
8538 	    bam_direct = BAM_DIRECT_MULTIBOOT);
8539 	if (bam_direct != BAM_DIRECT_DBOOT) {
8540 		bam_error(NOT_DBOOT, optnum == KERNEL_CMD ? "kernel" : "args");
8541 		return (BAM_ERROR);
8542 	}
8543 
8544 	/*
8545 	 * If a user changed the default entry to a non-bootadm controlled
8546 	 * one, we don't want to mess with it.  Just print an error and
8547 	 * return.
8548 	 */
8549 	if (mp->curdefault) {
8550 		entryNum = s_strtol(mp->curdefault->arg);
8551 		for (entryp = mp->entries; entryp; entryp = entryp->next) {
8552 			if (entryp->entryNum == entryNum)
8553 				break;
8554 		}
8555 		if ((entryp != NULL) &&
8556 		    ((entryp->flags & (BAM_ENTRY_BOOTADM|BAM_ENTRY_LU)) == 0)) {
8557 			bam_error(DEFAULT_NOT_BAM);
8558 			return (BAM_ERROR);
8559 		}
8560 	}
8561 
8562 	entryp = find_boot_entry(mp, BOOTENV_RC_TITLE, NULL, NULL, NULL, NULL,
8563 	    0, &entryNum);
8564 
8565 	if (entryp != NULL) {
8566 		for (ptr = entryp->start; ptr && ptr != entryp->end;
8567 		    ptr = ptr->next) {
8568 			if (strncmp(ptr->cmd, menu_cmds[KERNEL_CMD],
8569 			    sizeof (menu_cmds[KERNEL_CMD]) - 1) == 0) {
8570 				kernelp = ptr;
8571 				break;
8572 			}
8573 		}
8574 		if (kernelp == NULL) {
8575 			bam_error(NO_KERNEL, entryNum);
8576 			return (BAM_ERROR);
8577 		}
8578 
8579 		old_kernel_len = strcspn(kernelp->arg, " \t");
8580 		space = old_args = kernelp->arg + old_kernel_len;
8581 		while ((*old_args == ' ') || (*old_args == '\t'))
8582 			old_args++;
8583 	}
8584 
8585 	if (path == NULL) {
8586 		if (entryp == NULL) {
8587 			BAM_DPRINTF((D_GET_SET_KERNEL_NO_RC, fcn));
8588 			BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8589 			return (BAM_SUCCESS);
8590 		}
8591 		assert(kernelp);
8592 		if (optnum == ARGS_CMD) {
8593 			if (old_args[0] != '\0') {
8594 				(void) strlcpy(buf, old_args, bufsize);
8595 				BAM_DPRINTF((D_GET_SET_KERNEL_ARGS, fcn, buf));
8596 			}
8597 		} else {
8598 			/*
8599 			 * We need to print the kernel, so we just turn the
8600 			 * first space into a '\0' and print the beginning.
8601 			 * We don't print anything if it's the default kernel.
8602 			 */
8603 			old_space = *space;
8604 			*space = '\0';
8605 			if (strcmp(kernelp->arg, DIRECT_BOOT_KERNEL) != 0) {
8606 				(void) strlcpy(buf, kernelp->arg, bufsize);
8607 				BAM_DPRINTF((D_GET_SET_KERNEL_KERN, fcn, buf));
8608 			}
8609 			*space = old_space;
8610 		}
8611 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8612 		return (BAM_SUCCESS);
8613 	}
8614 
8615 	/*
8616 	 * First, check if we're resetting an entry to the default.
8617 	 */
8618 	if ((path[0] == '\0') ||
8619 	    ((optnum == KERNEL_CMD) &&
8620 	    (strcmp(path, DIRECT_BOOT_KERNEL) == 0))) {
8621 		if ((entryp == NULL) || (kernelp == NULL)) {
8622 			/* No previous entry, it's already the default */
8623 			BAM_DPRINTF((D_GET_SET_KERNEL_ALREADY, fcn));
8624 			return (BAM_SUCCESS);
8625 		}
8626 
8627 		/*
8628 		 * Check if we can delete the entry.  If we're resetting the
8629 		 * kernel command, and the args is already empty, or if we're
8630 		 * resetting the args command, and the kernel is already the
8631 		 * default, we can restore the old default and delete the entry.
8632 		 */
8633 		if (((optnum == KERNEL_CMD) &&
8634 		    ((old_args == NULL) || (old_args[0] == '\0'))) ||
8635 		    ((optnum == ARGS_CMD) &&
8636 		    (strncmp(kernelp->arg, DIRECT_BOOT_KERNEL,
8637 		    sizeof (DIRECT_BOOT_KERNEL) - 1) == 0))) {
8638 			kernelp = NULL;
8639 			(void) do_delete(mp, entryNum);
8640 			restore_default_entry(mp, BAM_OLD_RC_DEF,
8641 			    mp->old_rc_default);
8642 			mp->old_rc_default = NULL;
8643 			rv = BAM_WRITE;
8644 			BAM_DPRINTF((D_GET_SET_KERNEL_RESTORE_DEFAULT, fcn));
8645 			goto done;
8646 		}
8647 
8648 		if (optnum == KERNEL_CMD) {
8649 			/*
8650 			 * At this point, we've already checked that old_args
8651 			 * and entryp are valid pointers.  The "+ 2" is for
8652 			 * a space a the string termination character.
8653 			 */
8654 			new_str_len = (sizeof (DIRECT_BOOT_KERNEL) - 1) +
8655 			    strlen(old_args) + 2;
8656 			new_arg = s_calloc(1, new_str_len);
8657 			(void) snprintf(new_arg, new_str_len, "%s %s",
8658 			    DIRECT_BOOT_KERNEL, old_args);
8659 			free(kernelp->arg);
8660 			kernelp->arg = new_arg;
8661 
8662 			/*
8663 			 * We have changed the kernel line, so we may need
8664 			 * to update the archive line as well.
8665 			 */
8666 			set_archive_line(entryp, kernelp);
8667 			BAM_DPRINTF((D_GET_SET_KERNEL_RESET_KERNEL_SET_ARG,
8668 			    fcn, kernelp->arg));
8669 		} else {
8670 			/*
8671 			 * We're resetting the boot args to nothing, so
8672 			 * we only need to copy the kernel.  We've already
8673 			 * checked that the kernel is not the default.
8674 			 */
8675 			new_arg = s_calloc(1, old_kernel_len + 1);
8676 			(void) snprintf(new_arg, old_kernel_len + 1, "%s",
8677 			    kernelp->arg);
8678 			free(kernelp->arg);
8679 			kernelp->arg = new_arg;
8680 			BAM_DPRINTF((D_GET_SET_KERNEL_RESET_ARG_SET_KERNEL,
8681 			    fcn, kernelp->arg));
8682 		}
8683 		rv = BAM_WRITE;
8684 		goto done;
8685 	}
8686 
8687 	/*
8688 	 * Expand the kernel file to a full path, if necessary
8689 	 */
8690 	if ((optnum == KERNEL_CMD) && (path[0] != '/')) {
8691 		new_path = expand_path(path);
8692 		if (new_path == NULL) {
8693 			bam_error(UNKNOWN_KERNEL, path);
8694 			BAM_DPRINTF((D_RETURN_FAILURE, fcn));
8695 			return (BAM_ERROR);
8696 		}
8697 		free_new_path = 1;
8698 	} else {
8699 		new_path = path;
8700 		free_new_path = 0;
8701 	}
8702 
8703 	/*
8704 	 * At this point, we know we're setting a new value.  First, take care
8705 	 * of the case where there was no previous entry.
8706 	 */
8707 	if (entryp == NULL) {
8708 
8709 		/* Similar to code in update_temp */
8710 		fstype = get_fstype("/");
8711 		INJECT_ERROR1("GET_SET_KERNEL_FSTYPE", fstype = NULL);
8712 		if (fstype == NULL) {
8713 			bam_error(BOOTENV_FSTYPE_FAILED);
8714 			rv = BAM_ERROR;
8715 			goto done;
8716 		}
8717 
8718 		osdev = get_special("/");
8719 		INJECT_ERROR1("GET_SET_KERNEL_SPECIAL", osdev = NULL);
8720 		if (osdev == NULL) {
8721 			free(fstype);
8722 			bam_error(BOOTENV_SPECIAL_FAILED);
8723 			rv = BAM_ERROR;
8724 			goto done;
8725 		}
8726 
8727 		sign = find_existing_sign("/", osdev, fstype);
8728 		INJECT_ERROR1("GET_SET_KERNEL_SIGN", sign = NULL);
8729 		if (sign == NULL) {
8730 			free(fstype);
8731 			free(osdev);
8732 			bam_error(BOOTENV_SIGN_FAILED);
8733 			rv = BAM_ERROR;
8734 			goto done;
8735 		}
8736 
8737 		free(fstype);
8738 		free(osdev);
8739 		(void) strlcpy(signbuf, sign, sizeof (signbuf));
8740 		free(sign);
8741 		assert(strchr(signbuf, '(') == NULL &&
8742 		    strchr(signbuf, ',') == NULL &&
8743 		    strchr(signbuf, ')') == NULL);
8744 
8745 		if (optnum == KERNEL_CMD) {
8746 			BAM_DPRINTF((D_GET_SET_KERNEL_NEW_KERN, fcn, new_path));
8747 			entryNum = add_boot_entry(mp, BOOTENV_RC_TITLE,
8748 			    signbuf, new_path, NULL, NULL);
8749 		} else {
8750 			new_str_len = strlen(DIRECT_BOOT_KERNEL) +
8751 			    strlen(path) + 8;
8752 			new_arg = s_calloc(1, new_str_len);
8753 
8754 			(void) snprintf(new_arg, new_str_len, "%s %s",
8755 			    DIRECT_BOOT_KERNEL, path);
8756 			BAM_DPRINTF((D_GET_SET_KERNEL_NEW_ARG, fcn, new_arg));
8757 			entryNum = add_boot_entry(mp, BOOTENV_RC_TITLE,
8758 			    signbuf, new_arg, NULL, DIRECT_BOOT_ARCHIVE);
8759 			free(new_arg);
8760 		}
8761 		INJECT_ERROR1("GET_SET_KERNEL_ADD_BOOT_ENTRY",
8762 		    entryNum = BAM_ERROR);
8763 		if (entryNum == BAM_ERROR) {
8764 			bam_error(GET_SET_KERNEL_ADD_BOOT_ENTRY,
8765 			    BOOTENV_RC_TITLE);
8766 			rv = BAM_ERROR;
8767 			goto done;
8768 		}
8769 		save_default_entry(mp, BAM_OLD_RC_DEF);
8770 		ret = set_global(mp, menu_cmds[DEFAULT_CMD], entryNum);
8771 		INJECT_ERROR1("GET_SET_KERNEL_SET_GLOBAL", ret = BAM_ERROR);
8772 		if (ret == BAM_ERROR) {
8773 			bam_error(GET_SET_KERNEL_SET_GLOBAL, entryNum);
8774 		}
8775 		rv = BAM_WRITE;
8776 		goto done;
8777 	}
8778 
8779 	/*
8780 	 * There was already an bootenv entry which we need to edit.
8781 	 */
8782 	if (optnum == KERNEL_CMD) {
8783 		new_str_len = strlen(new_path) + strlen(old_args) + 2;
8784 		new_arg = s_calloc(1, new_str_len);
8785 		(void) snprintf(new_arg, new_str_len, "%s %s", new_path,
8786 		    old_args);
8787 		free(kernelp->arg);
8788 		kernelp->arg = new_arg;
8789 
8790 		/*
8791 		 * If we have changed the kernel line, we may need to update
8792 		 * the archive line as well.
8793 		 */
8794 		set_archive_line(entryp, kernelp);
8795 		BAM_DPRINTF((D_GET_SET_KERNEL_REPLACED_KERNEL_SAME_ARG, fcn,
8796 		    kernelp->arg));
8797 	} else {
8798 		new_str_len = old_kernel_len + strlen(path) + 8;
8799 		new_arg = s_calloc(1, new_str_len);
8800 		(void) strncpy(new_arg, kernelp->arg, old_kernel_len);
8801 		(void) strlcat(new_arg, " ", new_str_len);
8802 		(void) strlcat(new_arg, path, new_str_len);
8803 		free(kernelp->arg);
8804 		kernelp->arg = new_arg;
8805 		BAM_DPRINTF((D_GET_SET_KERNEL_SAME_KERNEL_REPLACED_ARG, fcn,
8806 		    kernelp->arg));
8807 	}
8808 	rv = BAM_WRITE;
8809 
8810 done:
8811 	if ((rv == BAM_WRITE) && kernelp)
8812 		update_line(kernelp);
8813 	if (free_new_path)
8814 		free(new_path);
8815 	if (rv == BAM_WRITE) {
8816 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8817 	} else {
8818 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
8819 	}
8820 	return (rv);
8821 }
8822 
8823 static error_t
8824 get_kernel(menu_t *mp, menu_cmd_t optnum, char *buf, size_t bufsize)
8825 {
8826 	const char	*fcn = "get_kernel()";
8827 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, menu_cmds[optnum]));
8828 	return (get_set_kernel(mp, optnum, NULL, buf, bufsize));
8829 }
8830 
8831 static error_t
8832 set_kernel(menu_t *mp, menu_cmd_t optnum, char *path, char *buf, size_t bufsize)
8833 {
8834 	const char	*fcn = "set_kernel()";
8835 	assert(path != NULL);
8836 	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, menu_cmds[optnum], path));
8837 	return (get_set_kernel(mp, optnum, path, buf, bufsize));
8838 }
8839 
8840 /*ARGSUSED*/
8841 static error_t
8842 set_option(menu_t *mp, char *dummy, char *opt)
8843 {
8844 	int		optnum;
8845 	int		optval;
8846 	char		*val;
8847 	char		buf[BUFSIZ] = "";
8848 	error_t		rv;
8849 	const char	*fcn = "set_option()";
8850 
8851 	assert(mp);
8852 	assert(opt);
8853 	assert(dummy == NULL);
8854 
8855 	/* opt is set from bam_argv[0] and is always non-NULL */
8856 	BAM_DPRINTF((D_FUNC_ENTRY1, fcn, opt));
8857 
8858 	val = strchr(opt, '=');
8859 	if (val != NULL) {
8860 		*val = '\0';
8861 	}
8862 
8863 	if (strcmp(opt, "default") == 0) {
8864 		optnum = DEFAULT_CMD;
8865 	} else if (strcmp(opt, "timeout") == 0) {
8866 		optnum = TIMEOUT_CMD;
8867 	} else if (strcmp(opt, menu_cmds[KERNEL_CMD]) == 0) {
8868 		optnum = KERNEL_CMD;
8869 	} else if (strcmp(opt, menu_cmds[ARGS_CMD]) == 0) {
8870 		optnum = ARGS_CMD;
8871 	} else {
8872 		bam_error(INVALID_OPTION, opt);
8873 		return (BAM_ERROR);
8874 	}
8875 
8876 	/*
8877 	 * kernel and args are allowed without "=new_value" strings.  All
8878 	 * others cause errors
8879 	 */
8880 	if ((val == NULL) && (optnum != KERNEL_CMD) && (optnum != ARGS_CMD)) {
8881 		bam_error(NO_OPTION_ARG, opt);
8882 		return (BAM_ERROR);
8883 	} else if (val != NULL) {
8884 		*val = '=';
8885 	}
8886 
8887 	if ((optnum == KERNEL_CMD) || (optnum == ARGS_CMD)) {
8888 		BAM_DPRINTF((D_SET_OPTION, fcn, menu_cmds[optnum],
8889 		    val ? val + 1 : "NULL"));
8890 
8891 		if (val)
8892 			rv = set_kernel(mp, optnum, val + 1, buf, sizeof (buf));
8893 		else
8894 			rv = get_kernel(mp, optnum, buf, sizeof (buf));
8895 		if ((rv == BAM_SUCCESS) && (buf[0] != '\0'))
8896 			(void) printf("%s\n", buf);
8897 	} else {
8898 		optval = s_strtol(val + 1);
8899 		BAM_DPRINTF((D_SET_OPTION, fcn, menu_cmds[optnum], val + 1));
8900 		rv = set_global(mp, menu_cmds[optnum], optval);
8901 	}
8902 
8903 	if (rv == BAM_WRITE || rv == BAM_SUCCESS) {
8904 		BAM_DPRINTF((D_RETURN_SUCCESS, fcn));
8905 	} else {
8906 		BAM_DPRINTF((D_RETURN_FAILURE, fcn));
8907 	}
8908 
8909 	return (rv);
8910 }
8911 
8912 /*
8913  * The quiet argument suppresses messages. This is used
8914  * when invoked in the context of other commands (e.g. list_entry)
8915  */
8916 static error_t
8917 read_globals(menu_t *mp, char *menu_path, char *globalcmd, int quiet)
8918 {
8919 	line_t *lp;
8920 	char *arg;
8921 	int done, ret = BAM_SUCCESS;
8922 
8923 	assert(mp);
8924 	assert(menu_path);
8925 	assert(globalcmd);
8926 
8927 	if (mp->start == NULL) {
8928 		if (!quiet)
8929 			bam_error(NO_MENU, menu_path);
8930 		return (BAM_ERROR);
8931 	}
8932 
8933 	done = 0;
8934 	for (lp = mp->start; lp; lp = lp->next) {
8935 		if (lp->flags != BAM_GLOBAL)
8936 			continue;
8937 
8938 		if (lp->cmd == NULL) {
8939 			if (!quiet)
8940 				bam_error(NO_CMD, lp->lineNum);
8941 			continue;
8942 		}
8943 
8944 		if (strcmp(globalcmd, lp->cmd) != 0)
8945 			continue;
8946 
8947 		/* Found global. Check for duplicates */
8948 		if (done && !quiet) {
8949 			bam_error(DUP_CMD, globalcmd, lp->lineNum, bam_root);
8950 			ret = BAM_ERROR;
8951 		}
8952 
8953 		arg = lp->arg ? lp->arg : "";
8954 		bam_print(GLOBAL_CMD, globalcmd, arg);
8955 		done = 1;
8956 	}
8957 
8958 	if (!done && bam_verbose)
8959 		bam_print(NO_ENTRY, globalcmd);
8960 
8961 	return (ret);
8962 }
8963 
8964 static error_t
8965 menu_write(char *root, menu_t *mp)
8966 {
8967 	const char *fcn = "menu_write()";
8968 
8969 	BAM_DPRINTF((D_MENU_WRITE_ENTER, fcn, root));
8970 	return (list2file(root, MENU_TMP, GRUB_MENU, mp->start));
8971 }
8972 
8973 void
8974 line_free(line_t *lp)
8975 {
8976 	if (lp == NULL)
8977 		return;
8978 
8979 	if (lp->cmd)
8980 		free(lp->cmd);
8981 	if (lp->sep)
8982 		free(lp->sep);
8983 	if (lp->arg)
8984 		free(lp->arg);
8985 	if (lp->line)
8986 		free(lp->line);
8987 	free(lp);
8988 }
8989 
8990 static void
8991 linelist_free(line_t *start)
8992 {
8993 	line_t *lp;
8994 
8995 	while (start) {
8996 		lp = start;
8997 		start = start->next;
8998 		line_free(lp);
8999 	}
9000 }
9001 
9002 static void
9003 filelist_free(filelist_t *flistp)
9004 {
9005 	linelist_free(flistp->head);
9006 	flistp->head = NULL;
9007 	flistp->tail = NULL;
9008 }
9009 
9010 static void
9011 menu_free(menu_t *mp)
9012 {
9013 	entry_t *ent, *tmp;
9014 	assert(mp);
9015 
9016 	if (mp->start)
9017 		linelist_free(mp->start);
9018 	ent = mp->entries;
9019 	while (ent) {
9020 		tmp = ent;
9021 		ent = tmp->next;
9022 		free(tmp);
9023 	}
9024 
9025 	free(mp);
9026 }
9027 
9028 /*
9029  * Utility routines
9030  */
9031 
9032 
9033 /*
9034  * Returns 0 on success
9035  * Any other value indicates an error
9036  */
9037 static int
9038 exec_cmd(char *cmdline, filelist_t *flistp)
9039 {
9040 	char buf[BUFSIZ];
9041 	int ret;
9042 	FILE *ptr;
9043 	sigset_t set;
9044 	void (*disp)(int);
9045 
9046 	/*
9047 	 * For security
9048 	 * - only absolute paths are allowed
9049 	 * - set IFS to space and tab
9050 	 */
9051 	if (*cmdline != '/') {
9052 		bam_error(ABS_PATH_REQ, cmdline);
9053 		return (-1);
9054 	}
9055 	(void) putenv("IFS= \t");
9056 
9057 	/*
9058 	 * We may have been exec'ed with SIGCHLD blocked
9059 	 * unblock it here
9060 	 */
9061 	(void) sigemptyset(&set);
9062 	(void) sigaddset(&set, SIGCHLD);
9063 	if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) {
9064 		bam_error(CANT_UNBLOCK_SIGCHLD, strerror(errno));
9065 		return (-1);
9066 	}
9067 
9068 	/*
9069 	 * Set SIGCHLD disposition to SIG_DFL for popen/pclose
9070 	 */
9071 	disp = sigset(SIGCHLD, SIG_DFL);
9072 	if (disp == SIG_ERR) {
9073 		bam_error(FAILED_SIG, strerror(errno));
9074 		return (-1);
9075 	}
9076 	if (disp == SIG_HOLD) {
9077 		bam_error(BLOCKED_SIG, cmdline);
9078 		return (-1);
9079 	}
9080 
9081 	ptr = popen(cmdline, "r");
9082 	if (ptr == NULL) {
9083 		bam_error(POPEN_FAIL, cmdline, strerror(errno));
9084 		return (-1);
9085 	}
9086 
9087 	/*
9088 	 * If we simply do a pclose() following a popen(), pclose()
9089 	 * will close the reader end of the pipe immediately even
9090 	 * if the child process has not started/exited. pclose()
9091 	 * does wait for cmd to terminate before returning though.
9092 	 * When the executed command writes its output to the pipe
9093 	 * there is no reader process and the command dies with
9094 	 * SIGPIPE. To avoid this we read repeatedly until read
9095 	 * terminates with EOF. This indicates that the command
9096 	 * (writer) has closed the pipe and we can safely do a
9097 	 * pclose().
9098 	 *
9099 	 * Since pclose() does wait for the command to exit,
9100 	 * we can safely reap the exit status of the command
9101 	 * from the value returned by pclose()
9102 	 */
9103 	while (s_fgets(buf, sizeof (buf), ptr) != NULL) {
9104 		if (flistp == NULL) {
9105 			/* s_fgets strips newlines, so insert them at the end */
9106 			bam_print(PRINT, buf);
9107 		} else {
9108 			append_to_flist(flistp, buf);
9109 		}
9110 	}
9111 
9112 	ret = pclose(ptr);
9113 	if (ret == -1) {
9114 		bam_error(PCLOSE_FAIL, cmdline, strerror(errno));
9115 		return (-1);
9116 	}
9117 
9118 	if (WIFEXITED(ret)) {
9119 		return (WEXITSTATUS(ret));
9120 	} else {
9121 		bam_error(EXEC_FAIL, cmdline, ret);
9122 		return (-1);
9123 	}
9124 }
9125 
9126 /*
9127  * Since this function returns -1 on error
9128  * it cannot be used to convert -1. However,
9129  * that is sufficient for what we need.
9130  */
9131 static long
9132 s_strtol(char *str)
9133 {
9134 	long l;
9135 	char *res = NULL;
9136 
9137 	if (str == NULL) {
9138 		return (-1);
9139 	}
9140 
9141 	errno = 0;
9142 	l = strtol(str, &res, 10);
9143 	if (errno || *res != '\0') {
9144 		return (-1);
9145 	}
9146 
9147 	return (l);
9148 }
9149 
9150 /*
9151  * Wrapper around fputs, that adds a newline (since fputs doesn't)
9152  */
9153 static int
9154 s_fputs(char *str, FILE *fp)
9155 {
9156 	char linebuf[BAM_MAXLINE];
9157 
9158 	(void) snprintf(linebuf, sizeof (linebuf), "%s\n", str);
9159 	return (fputs(linebuf, fp));
9160 }
9161 
9162 /*
9163  * Wrapper around fgets, that strips newlines returned by fgets
9164  */
9165 char *
9166 s_fgets(char *buf, int buflen, FILE *fp)
9167 {
9168 	int n;
9169 
9170 	buf = fgets(buf, buflen, fp);
9171 	if (buf) {
9172 		n = strlen(buf);
9173 		if (n == buflen - 1 && buf[n-1] != '\n')
9174 			bam_error(TOO_LONG, buflen - 1, buf);
9175 		buf[n-1] = (buf[n-1] == '\n') ? '\0' : buf[n-1];
9176 	}
9177 
9178 	return (buf);
9179 }
9180 
9181 void *
9182 s_calloc(size_t nelem, size_t sz)
9183 {
9184 	void *ptr;
9185 
9186 	ptr = calloc(nelem, sz);
9187 	if (ptr == NULL) {
9188 		bam_error(NO_MEM, nelem*sz);
9189 		bam_exit(1);
9190 	}
9191 	return (ptr);
9192 }
9193 
9194 void *
9195 s_realloc(void *ptr, size_t sz)
9196 {
9197 	ptr = realloc(ptr, sz);
9198 	if (ptr == NULL) {
9199 		bam_error(NO_MEM, sz);
9200 		bam_exit(1);
9201 	}
9202 	return (ptr);
9203 }
9204 
9205 char *
9206 s_strdup(char *str)
9207 {
9208 	char *ptr;
9209 
9210 	if (str == NULL)
9211 		return (NULL);
9212 
9213 	ptr = strdup(str);
9214 	if (ptr == NULL) {
9215 		bam_error(NO_MEM, strlen(str) + 1);
9216 		bam_exit(1);
9217 	}
9218 	return (ptr);
9219 }
9220 
9221 /*
9222  * Returns 1 if amd64 (or sparc, for syncing x86 diskless clients)
9223  * Returns 0 otherwise
9224  */
9225 static int
9226 is_amd64(void)
9227 {
9228 	static int amd64 = -1;
9229 	char isabuf[257];	/* from sysinfo(2) manpage */
9230 
9231 	if (amd64 != -1)
9232 		return (amd64);
9233 
9234 	if (bam_alt_platform) {
9235 		if (strcmp(bam_platform, "i86pc") == 0) {
9236 			amd64 = 1;		/* diskless server */
9237 		}
9238 	} else {
9239 		if (sysinfo(SI_ISALIST, isabuf, sizeof (isabuf)) > 0 &&
9240 		    strncmp(isabuf, "amd64 ", strlen("amd64 ")) == 0) {
9241 			amd64 = 1;
9242 		} else if (strstr(isabuf, "i386") == NULL) {
9243 			amd64 = 1;		/* diskless server */
9244 		}
9245 	}
9246 	if (amd64 == -1)
9247 		amd64 = 0;
9248 
9249 	return (amd64);
9250 }
9251 
9252 static char *
9253 get_machine(void)
9254 {
9255 	static int cached = -1;
9256 	static char mbuf[257];	/* from sysinfo(2) manpage */
9257 
9258 	if (cached == 0)
9259 		return (mbuf);
9260 
9261 	if (bam_alt_platform) {
9262 		return (bam_platform);
9263 	} else {
9264 		if (sysinfo(SI_MACHINE, mbuf, sizeof (mbuf)) > 0) {
9265 			cached = 1;
9266 		}
9267 	}
9268 	if (cached == -1) {
9269 		mbuf[0] = '\0';
9270 		cached = 0;
9271 	}
9272 
9273 	return (mbuf);
9274 }
9275 
9276 int
9277 is_sparc(void)
9278 {
9279 	static int issparc = -1;
9280 	char mbuf[257];	/* from sysinfo(2) manpage */
9281 
9282 	if (issparc != -1)
9283 		return (issparc);
9284 
9285 	if (bam_alt_platform) {
9286 		if (strncmp(bam_platform, "sun4", 4) == 0) {
9287 			issparc = 1;
9288 		}
9289 	} else {
9290 		if (sysinfo(SI_ARCHITECTURE, mbuf, sizeof (mbuf)) > 0 &&
9291 		    strcmp(mbuf, "sparc") == 0) {
9292 			issparc = 1;
9293 		}
9294 	}
9295 	if (issparc == -1)
9296 		issparc = 0;
9297 
9298 	return (issparc);
9299 }
9300 
9301 static void
9302 append_to_flist(filelist_t *flistp, char *s)
9303 {
9304 	line_t *lp;
9305 
9306 	lp = s_calloc(1, sizeof (line_t));
9307 	lp->line = s_strdup(s);
9308 	if (flistp->head == NULL)
9309 		flistp->head = lp;
9310 	else
9311 		flistp->tail->next = lp;
9312 	flistp->tail = lp;
9313 }
9314 
9315 #if !defined(_OPB)
9316 
9317 UCODE_VENDORS;
9318 
9319 /*ARGSUSED*/
9320 static void
9321 ucode_install(char *root)
9322 {
9323 	int i;
9324 
9325 	for (i = 0; ucode_vendors[i].filestr != NULL; i++) {
9326 		int cmd_len = PATH_MAX + 256;
9327 		char cmd[PATH_MAX + 256];
9328 		char file[PATH_MAX];
9329 		char timestamp[PATH_MAX];
9330 		struct stat fstatus, tstatus;
9331 		struct utimbuf u_times;
9332 
9333 		(void) snprintf(file, PATH_MAX, "%s/%s/%s-ucode.%s",
9334 		    bam_root, UCODE_INSTALL_PATH, ucode_vendors[i].filestr,
9335 		    ucode_vendors[i].extstr);
9336 
9337 		if (stat(file, &fstatus) != 0 || !(S_ISREG(fstatus.st_mode)))
9338 			continue;
9339 
9340 		(void) snprintf(timestamp, PATH_MAX, "%s.ts", file);
9341 
9342 		if (stat(timestamp, &tstatus) == 0 &&
9343 		    fstatus.st_mtime <= tstatus.st_mtime)
9344 			continue;
9345 
9346 		(void) snprintf(cmd, cmd_len, "/usr/sbin/ucodeadm -i -R "
9347 		    "%s/%s/%s %s > /dev/null 2>&1", bam_root,
9348 		    UCODE_INSTALL_PATH, ucode_vendors[i].vendorstr, file);
9349 		if (system(cmd) != 0)
9350 			return;
9351 
9352 		if (creat(timestamp, S_IRUSR | S_IWUSR) == -1)
9353 			return;
9354 
9355 		u_times.actime = fstatus.st_atime;
9356 		u_times.modtime = fstatus.st_mtime;
9357 		(void) utime(timestamp, &u_times);
9358 	}
9359 }
9360 #endif
9361