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