xref: /illumos-gate/usr/src/cmd/halt/halt.c (revision 8d0c3d29bb99f6521f2dc5058a7e4debebad7899)
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 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved	*/
28 
29 /*
30  * University Copyright- Copyright (c) 1982, 1986, 1988
31  * The Regents of the University of California
32  * All Rights Reserved
33  *
34  * University Acknowledgment- Portions of this document are derived from
35  * software developed by the University of California, Berkeley, and its
36  * contributors.
37  * Portions contributed by Juergen Keil, <jk@tools.de>.
38  */
39 
40 
41 /*
42  * Common code for halt(1M), poweroff(1M), and reboot(1M).  We use
43  * argv[0] to determine which behavior to exhibit.
44  */
45 
46 #include <stdio.h>
47 #include <procfs.h>
48 #include <sys/types.h>
49 #include <sys/elf.h>
50 #include <sys/systeminfo.h>
51 #include <sys/stat.h>
52 #include <sys/uadmin.h>
53 #include <sys/mntent.h>
54 #include <sys/mnttab.h>
55 #include <sys/mount.h>
56 #include <sys/fs/ufs_mount.h>
57 #include <alloca.h>
58 #include <assert.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <libgen.h>
62 #include <libscf.h>
63 #include <libscf_priv.h>
64 #include <limits.h>
65 #include <locale.h>
66 #include <libintl.h>
67 #include <syslog.h>
68 #include <signal.h>
69 #include <strings.h>
70 #include <unistd.h>
71 #include <stdlib.h>
72 #include <stdio.h>
73 #include <strings.h>
74 #include <time.h>
75 #include <wait.h>
76 #include <ctype.h>
77 #include <utmpx.h>
78 #include <pwd.h>
79 #include <zone.h>
80 #include <spawn.h>
81 
82 #include <libzfs.h>
83 #if defined(__i386)
84 #include <libgrubmgmt.h>
85 #endif
86 
87 #if !defined(TEXT_DOMAIN)
88 #define	TEXT_DOMAIN	"SYS_TEST"
89 #endif
90 
91 #if defined(__sparc)
92 #define	CUR_ELFDATA	ELFDATA2MSB
93 #elif defined(__i386)
94 #define	CUR_ELFDATA	ELFDATA2LSB
95 #endif
96 
97 static libzfs_handle_t *g_zfs;
98 
99 extern int audit_halt_setup(int, char **);
100 extern int audit_halt_success(void);
101 extern int audit_halt_fail(void);
102 
103 extern int audit_reboot_setup(void);
104 extern int audit_reboot_success(void);
105 extern int audit_reboot_fail(void);
106 
107 static char *cmdname;	/* basename(argv[0]), the name of the command */
108 
109 typedef struct ctidlist_struct {
110 	ctid_t ctid;
111 	struct ctidlist_struct *next;
112 } ctidlist_t;
113 
114 static ctidlist_t *ctidlist = NULL;
115 static ctid_t startdct = -1;
116 
117 #define	FMRI_STARTD_CONTRACT \
118 	"svc:/system/svc/restarter:default/:properties/restarter/contract"
119 
120 #define	BEADM_PROG	"/usr/sbin/beadm"
121 #define	BOOTADM_PROG	"/sbin/bootadm"
122 #define	ZONEADM_PROG	"/usr/sbin/zoneadm"
123 
124 /*
125  * The length of FASTBOOT_MOUNTPOINT must be less than MAXPATHLEN.
126  */
127 #define	FASTBOOT_MOUNTPOINT	"/tmp/.fastboot.root"
128 
129 /*
130  * Fast Reboot related variables
131  */
132 static char	fastboot_mounted[MAXPATHLEN];
133 
134 #if defined(__i386)
135 static grub_boot_args_t	fbarg;
136 static grub_boot_args_t	*fbarg_used;
137 static int fbarg_entnum = GRUB_ENTRY_DEFAULT;
138 #endif	/* __i386 */
139 
140 static int validate_ufs_disk(char *, char *);
141 static int validate_zfs_pool(char *, char *);
142 
143 static pid_t
144 get_initpid()
145 {
146 	static int init_pid = -1;
147 
148 	if (init_pid == -1) {
149 		if (zone_getattr(getzoneid(), ZONE_ATTR_INITPID, &init_pid,
150 		    sizeof (init_pid)) != sizeof (init_pid)) {
151 			assert(errno == ESRCH);
152 			init_pid = -1;
153 		}
154 	}
155 	return (init_pid);
156 }
157 
158 /*
159  * Quiesce or resume init using /proc.  When stopping init, we can't send
160  * SIGTSTP (since init ignores it) or SIGSTOP (since the kernel won't permit
161  * it).
162  */
163 static int
164 direct_init(long command)
165 {
166 	char ctlfile[MAXPATHLEN];
167 	pid_t pid;
168 	int ctlfd;
169 
170 	assert(command == PCDSTOP || command == PCRUN);
171 	if ((pid = get_initpid()) == -1) {
172 		return (-1);
173 	}
174 
175 	(void) snprintf(ctlfile, sizeof (ctlfile), "/proc/%d/ctl", pid);
176 	if ((ctlfd = open(ctlfile, O_WRONLY)) == -1)
177 		return (-1);
178 
179 	if (command == PCDSTOP) {
180 		if (write(ctlfd, &command, sizeof (long)) == -1) {
181 			(void) close(ctlfd);
182 			return (-1);
183 		}
184 	} else {	/* command == PCRUN */
185 		long cmds[2];
186 		cmds[0] = command;
187 		cmds[1] = 0;
188 		if (write(ctlfd, cmds, sizeof (cmds)) == -1) {
189 			(void) close(ctlfd);
190 			return (-1);
191 		}
192 	}
193 	(void) close(ctlfd);
194 	return (0);
195 }
196 
197 static void
198 stop_startd()
199 {
200 	scf_handle_t *h;
201 	scf_property_t *prop = NULL;
202 	scf_value_t *val = NULL;
203 	uint64_t uint64;
204 
205 	if ((h = scf_handle_create(SCF_VERSION)) == NULL)
206 		return;
207 
208 	if ((scf_handle_bind(h) != 0) ||
209 	    ((prop = scf_property_create(h)) == NULL) ||
210 	    ((val = scf_value_create(h)) == NULL))
211 		goto out;
212 
213 	if (scf_handle_decode_fmri(h, FMRI_STARTD_CONTRACT,
214 	    NULL, NULL, NULL, NULL, prop, SCF_DECODE_FMRI_EXACT) != 0)
215 		goto out;
216 
217 	if (scf_property_is_type(prop, SCF_TYPE_COUNT) != 0 ||
218 	    scf_property_get_value(prop, val) != 0 ||
219 	    scf_value_get_count(val, &uint64) != 0)
220 		goto out;
221 
222 	startdct = (ctid_t)uint64;
223 	(void) sigsend(P_CTID, startdct, SIGSTOP);
224 
225 out:
226 	scf_property_destroy(prop);
227 	scf_value_destroy(val);
228 	scf_handle_destroy(h);
229 }
230 
231 static void
232 continue_startd()
233 {
234 	if (startdct != -1)
235 		(void) sigsend(P_CTID, startdct, SIGCONT);
236 }
237 
238 #define	FMRI_RESTARTER_PROP "/:properties/general/restarter"
239 #define	FMRI_CONTRACT_PROP "/:properties/restarter/contract"
240 
241 static int
242 save_ctid(ctid_t ctid)
243 {
244 	ctidlist_t *next;
245 
246 	for (next = ctidlist; next != NULL; next = next->next)
247 		if (next->ctid == ctid)
248 			return (-1);
249 
250 	next = (ctidlist_t *)malloc(sizeof (ctidlist_t));
251 	if (next == NULL)
252 		return (-1);
253 
254 	next->ctid = ctid;
255 	next->next = ctidlist;
256 	ctidlist = next;
257 	return (0);
258 }
259 
260 static void
261 stop_delegates()
262 {
263 	ctid_t ctid;
264 	scf_handle_t *h;
265 	scf_scope_t *sc = NULL;
266 	scf_service_t *svc = NULL;
267 	scf_instance_t *inst = NULL;
268 	scf_snapshot_t *snap = NULL;
269 	scf_snapshot_t *isnap = NULL;
270 	scf_propertygroup_t *pg = NULL;
271 	scf_property_t *prop = NULL;
272 	scf_value_t *val = NULL;
273 	scf_iter_t *siter = NULL;
274 	scf_iter_t *iiter = NULL;
275 	char *fmri;
276 	ssize_t length;
277 
278 	uint64_t uint64;
279 	ssize_t bytes;
280 
281 	length = scf_limit(SCF_LIMIT_MAX_FMRI_LENGTH);
282 	if (length <= 0)
283 		return;
284 
285 	length++;
286 	fmri = alloca(length * sizeof (char));
287 
288 	if ((h = scf_handle_create(SCF_VERSION)) == NULL)
289 		return;
290 
291 	if (scf_handle_bind(h) != 0) {
292 		scf_handle_destroy(h);
293 		return;
294 	}
295 
296 	if ((sc = scf_scope_create(h)) == NULL ||
297 	    (svc = scf_service_create(h)) == NULL ||
298 	    (inst = scf_instance_create(h)) == NULL ||
299 	    (snap = scf_snapshot_create(h)) == NULL ||
300 	    (pg = scf_pg_create(h)) == NULL ||
301 	    (prop = scf_property_create(h)) == NULL ||
302 	    (val = scf_value_create(h)) == NULL ||
303 	    (siter = scf_iter_create(h)) == NULL ||
304 	    (iiter = scf_iter_create(h)) == NULL)
305 		goto out;
306 
307 	if (scf_handle_get_scope(h, SCF_SCOPE_LOCAL, sc) != 0)
308 		goto out;
309 
310 	if (scf_iter_scope_services(siter, sc) != 0)
311 		goto out;
312 
313 	while (scf_iter_next_service(siter, svc) == 1) {
314 
315 		if (scf_iter_service_instances(iiter, svc) != 0)
316 			continue;
317 
318 		while (scf_iter_next_instance(iiter, inst) == 1) {
319 
320 			if ((scf_instance_get_snapshot(inst, "running",
321 			    snap)) != 0)
322 				isnap = NULL;
323 			else
324 				isnap = snap;
325 
326 			if (scf_instance_get_pg_composed(inst, isnap,
327 			    SCF_PG_GENERAL, pg) != 0)
328 				continue;
329 
330 			if (scf_pg_get_property(pg, SCF_PROPERTY_RESTARTER,
331 			    prop) != 0 ||
332 			    scf_property_get_value(prop, val) != 0)
333 				continue;
334 
335 			bytes = scf_value_get_astring(val, fmri, length);
336 			if (bytes <= 0 || bytes >= length)
337 				continue;
338 
339 			if (strlcat(fmri, FMRI_CONTRACT_PROP, length) >=
340 			    length)
341 				continue;
342 
343 			if (scf_handle_decode_fmri(h, fmri, NULL, NULL,
344 			    NULL, NULL, prop, SCF_DECODE_FMRI_EXACT) != 0)
345 				continue;
346 
347 			if (scf_property_is_type(prop, SCF_TYPE_COUNT) != 0 ||
348 			    scf_property_get_value(prop, val) != 0 ||
349 			    scf_value_get_count(val, &uint64) != 0)
350 				continue;
351 
352 			ctid = (ctid_t)uint64;
353 			if (save_ctid(ctid) == 0) {
354 				(void) sigsend(P_CTID, ctid, SIGSTOP);
355 			}
356 		}
357 	}
358 out:
359 	scf_scope_destroy(sc);
360 	scf_service_destroy(svc);
361 	scf_instance_destroy(inst);
362 	scf_snapshot_destroy(snap);
363 	scf_pg_destroy(pg);
364 	scf_property_destroy(prop);
365 	scf_value_destroy(val);
366 	scf_iter_destroy(siter);
367 	scf_iter_destroy(iiter);
368 
369 	(void) scf_handle_unbind(h);
370 	scf_handle_destroy(h);
371 }
372 
373 static void
374 continue_delegates()
375 {
376 	ctidlist_t *next;
377 	for (next = ctidlist; next != NULL; next = next->next)
378 		(void) sigsend(P_CTID, next->ctid, SIGCONT);
379 }
380 
381 #define	FMRI_GDM "svc:/application/graphical-login/gdm:default"
382 #define	GDM_STOP_TIMEOUT	10	/* Give gdm 10 seconds to shut down */
383 
384 /*
385  * If gdm is running, try to stop gdm.
386  * Returns  0 on success, -1 on failure.
387  */
388 static int
389 stop_gdm()
390 {
391 	char *gdm_state = NULL;
392 	int retry = 0;
393 
394 	/*
395 	 * If gdm is running, try to stop gdm.
396 	 */
397 	while ((gdm_state = smf_get_state(FMRI_GDM)) != NULL &&
398 	    strcmp(gdm_state, SCF_STATE_STRING_ONLINE) == 0 &&
399 	    retry++ < GDM_STOP_TIMEOUT) {
400 
401 		free(gdm_state);
402 
403 		/*
404 		 * Only need to disable once.
405 		 */
406 		if (retry == 1 &&
407 		    smf_disable_instance(FMRI_GDM, SMF_TEMPORARY) != 0) {
408 			(void) fprintf(stderr,
409 			    gettext("%s: Failed to stop %s: %s.\n"),
410 			    cmdname, FMRI_GDM, scf_strerror(scf_error()));
411 			return (-1);
412 		}
413 		(void) sleep(1);
414 	}
415 
416 	if (retry >= GDM_STOP_TIMEOUT) {
417 		(void) fprintf(stderr, gettext("%s: Failed to stop %s.\n"),
418 		    cmdname, FMRI_GDM);
419 		return (-1);
420 	}
421 
422 	return (0);
423 }
424 
425 
426 static void
427 stop_restarters()
428 {
429 	stop_startd();
430 	stop_delegates();
431 }
432 
433 static void
434 continue_restarters()
435 {
436 	continue_startd();
437 	continue_delegates();
438 }
439 
440 /*
441  * Copy an array of strings into buf, separated by spaces.  Returns 0 on
442  * success.
443  */
444 static int
445 gather_args(char **args, char *buf, size_t buf_sz)
446 {
447 	if (strlcpy(buf, *args, buf_sz) >= buf_sz)
448 		return (-1);
449 
450 	for (++args; *args != NULL; ++args) {
451 		if (strlcat(buf, " ", buf_sz) >= buf_sz)
452 			return (-1);
453 		if (strlcat(buf, *args, buf_sz) >= buf_sz)
454 			return (-1);
455 	}
456 
457 	return (0);
458 }
459 
460 /*
461  * Halt every zone on the system.  We are committed to doing a shutdown
462  * even if something goes wrong here. If something goes wrong, we just
463  * continue with the shutdown.  Return non-zero if we need to wait for zones to
464  * halt later on.
465  */
466 static int
467 halt_zones()
468 {
469 	pid_t pid;
470 	zoneid_t *zones;
471 	size_t nz = 0, old_nz;
472 	int i;
473 	char zname[ZONENAME_MAX];
474 
475 	/*
476 	 * Get a list of zones. If the number of zones changes in between the
477 	 * two zone_list calls, try again.
478 	 */
479 
480 	for (;;) {
481 		(void) zone_list(NULL, &nz);
482 		if (nz == 1)
483 			return (0);
484 		old_nz = nz;
485 		zones = calloc(sizeof (zoneid_t), nz);
486 		if (zones == NULL) {
487 			(void) fprintf(stderr,
488 			    gettext("%s: Could not halt zones"
489 			    " (out of memory).\n"), cmdname);
490 			return (0);
491 		}
492 
493 		(void) zone_list(zones, &nz);
494 		if (old_nz == nz)
495 			break;
496 		free(zones);
497 	}
498 
499 	if (nz == 2) {
500 		(void) fprintf(stderr, gettext("%s: Halting 1 zone.\n"),
501 		    cmdname);
502 	} else {
503 		(void) fprintf(stderr, gettext("%s: Halting %i zones.\n"),
504 		    cmdname, nz - 1);
505 	}
506 
507 	for (i = 0; i < nz; i++) {
508 		if (zones[i] == GLOBAL_ZONEID)
509 			continue;
510 		if (getzonenamebyid(zones[i], zname, sizeof (zname)) < 0) {
511 			/*
512 			 * getzonenamebyid should only fail if we raced with
513 			 * another process trying to shut down the zone.
514 			 * We assume this happened and ignore the error.
515 			 */
516 			if (errno != EINVAL) {
517 				(void) fprintf(stderr,
518 				    gettext("%s: Unexpected error while "
519 				    "looking up zone %ul: %s.\n"),
520 				    cmdname, zones[i], strerror(errno));
521 			}
522 
523 			continue;
524 		}
525 		pid = fork();
526 		if (pid < 0) {
527 			(void) fprintf(stderr,
528 			    gettext("%s: Zone \"%s\" could not be"
529 			    " halted (could not fork(): %s).\n"),
530 			    cmdname, zname, strerror(errno));
531 			continue;
532 		}
533 		if (pid == 0) {
534 			(void) execl(ZONEADM_PROG, ZONEADM_PROG,
535 			    "-z", zname, "halt", NULL);
536 			(void) fprintf(stderr,
537 			    gettext("%s: Zone \"%s\" could not be halted"
538 			    " (cannot exec(" ZONEADM_PROG "): %s).\n"),
539 			    cmdname, zname, strerror(errno));
540 			exit(0);
541 		}
542 	}
543 
544 	return (1);
545 }
546 
547 /*
548  * This function tries to wait for all non-global zones to go away.
549  * It will timeout if no progress is made for 5 seconds, or a total of
550  * 30 seconds elapses.
551  */
552 
553 static void
554 check_zones_haltedness()
555 {
556 	int t = 0, t_prog = 0;
557 	size_t nz = 0, last_nz;
558 
559 	do {
560 		last_nz = nz;
561 		(void) zone_list(NULL, &nz);
562 		if (nz == 1)
563 			return;
564 
565 		(void) sleep(1);
566 
567 		if (last_nz > nz)
568 			t_prog = 0;
569 
570 		t++;
571 		t_prog++;
572 
573 		if (t == 10) {
574 			if (nz == 2) {
575 				(void) fprintf(stderr,
576 				    gettext("%s: Still waiting for 1 zone to "
577 				    "halt. Will wait up to 20 seconds.\n"),
578 				    cmdname);
579 			} else {
580 				(void) fprintf(stderr,
581 				    gettext("%s: Still waiting for %i zones "
582 				    "to halt. Will wait up to 20 seconds.\n"),
583 				    cmdname, nz - 1);
584 			}
585 		}
586 
587 	} while ((t < 30) && (t_prog < 5));
588 }
589 
590 
591 /*
592  * Validate that this is a root disk or dataset
593  * Returns 0 if it is a root disk or dataset;
594  * returns 1 if it is a disk argument or dataset, but not valid or not root;
595  * returns -1 if it is not a valid argument or a disk argument.
596  */
597 static int
598 validate_disk(char *arg, char *mountpoint)
599 {
600 	static char root_dev_path[] = "/dev/dsk";
601 	char kernpath[MAXPATHLEN];
602 	struct stat64 statbuf;
603 	int rc = 0;
604 
605 	if (strlen(arg) > MAXPATHLEN) {
606 		(void) fprintf(stderr,
607 		    gettext("%s: Argument is too long\n"), cmdname);
608 		return (-1);
609 	}
610 
611 	bcopy(FASTBOOT_MOUNTPOINT, mountpoint, sizeof (FASTBOOT_MOUNTPOINT));
612 
613 	if (strstr(arg, mountpoint) == NULL) {
614 		/*
615 		 * Do a force umount just in case some other filesystem has
616 		 * been mounted there.
617 		 */
618 		(void) umount2(mountpoint, MS_FORCE);
619 	}
620 
621 	/* Create the directory if it doesn't already exist */
622 	if (lstat64(mountpoint, &statbuf) != 0) {
623 		if (mkdirp(mountpoint, 0755) != 0) {
624 			(void) fprintf(stderr,
625 			    gettext("Failed to create mountpoint %s\n"),
626 			    mountpoint);
627 			return (-1);
628 		}
629 	}
630 
631 	if (strncmp(arg, root_dev_path, strlen(root_dev_path)) == 0) {
632 		/* ufs root disk argument */
633 		rc = validate_ufs_disk(arg, mountpoint);
634 	} else {
635 		/* zfs root pool argument */
636 		rc = validate_zfs_pool(arg, mountpoint);
637 	}
638 
639 	if (rc != 0)
640 		return (rc);
641 
642 	(void) snprintf(kernpath, MAXPATHLEN, "%s/platform/i86pc/kernel/unix",
643 	    mountpoint);
644 
645 	if (stat64(kernpath, &statbuf) != 0) {
646 		(void) fprintf(stderr,
647 		    gettext("%s: %s is not a root disk or dataset\n"),
648 		    cmdname, arg);
649 		return (1);
650 	}
651 
652 	return (0);
653 }
654 
655 
656 static int
657 validate_ufs_disk(char *arg, char *mountpoint)
658 {
659 	struct ufs_args	ufs_args = { 0 };
660 	char mntopts[MNT_LINE_MAX] = MNTOPT_LARGEFILES;
661 
662 	/* perform the mount */
663 	ufs_args.flags = UFSMNT_LARGEFILES;
664 	if (mount(arg, mountpoint, MS_DATA|MS_OPTIONSTR,
665 	    MNTTYPE_UFS, &ufs_args, sizeof (ufs_args),
666 	    mntopts, sizeof (mntopts)) != 0) {
667 		perror(cmdname);
668 		(void) fprintf(stderr,
669 		    gettext("%s: Failed to mount %s\n"), cmdname, arg);
670 		return (-1);
671 	}
672 
673 	return (0);
674 }
675 
676 static int
677 validate_zfs_pool(char *arg, char *mountpoint)
678 {
679 	zfs_handle_t *zhp = NULL;
680 	char mntopts[MNT_LINE_MAX] = { '\0' };
681 	int rc = 0;
682 
683 	if ((g_zfs = libzfs_init()) == NULL) {
684 		(void) fprintf(stderr, gettext("Internal error: failed to "
685 		    "initialize ZFS library\n"));
686 		return (-1);
687 	}
688 
689 	/* Try to open the dataset */
690 	if ((zhp = zfs_open(g_zfs, arg,
691 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_DATASET)) == NULL)
692 		return (-1);
693 
694 	/* perform the mount */
695 	if (mount(zfs_get_name(zhp), mountpoint, MS_DATA|MS_OPTIONSTR|MS_RDONLY,
696 	    MNTTYPE_ZFS, NULL, 0, mntopts, sizeof (mntopts)) != 0) {
697 		perror(cmdname);
698 		(void) fprintf(stderr,
699 		    gettext("%s: Failed to mount %s\n"), cmdname, arg);
700 		rc = -1;
701 	}
702 
703 validate_zfs_err_out:
704 	if (zhp != NULL)
705 		zfs_close(zhp);
706 
707 	libzfs_fini(g_zfs);
708 	return (rc);
709 }
710 
711 /*
712  * Return 0 if not zfs, or is zfs and have successfully constructed the
713  * boot argument; returns non-zero otherwise.
714  * At successful completion fpth contains pointer where mount point ends.
715  * NOTE: arg is supposed to be the resolved path
716  */
717 static int
718 get_zfs_bootfs_arg(const char *arg, const char ** fpth, int *is_zfs,
719 		char *bootfs_arg)
720 {
721 	zfs_handle_t *zhp = NULL;
722 	zpool_handle_t *zpoolp = NULL;
723 	FILE *mtabp = NULL;
724 	struct mnttab mnt;
725 	char *poolname = NULL;
726 	char physpath[MAXPATHLEN];
727 	char mntsp[ZPOOL_MAXNAMELEN];
728 	char bootfs[ZPOOL_MAXNAMELEN];
729 	int rc = 0;
730 	size_t mntlen = 0;
731 	size_t msz;
732 	static char fmt[] = "-B zfs-bootfs=%s,bootpath=\"%s\"";
733 
734 	*fpth = arg;
735 	*is_zfs = 0;
736 
737 	bzero(physpath, sizeof (physpath));
738 	bzero(bootfs, sizeof (bootfs));
739 
740 	if ((mtabp = fopen(MNTTAB, "r")) == NULL) {
741 		return (-1);
742 	}
743 
744 	while (getmntent(mtabp, &mnt) == 0) {
745 		if (strstr(arg, mnt.mnt_mountp) == arg &&
746 		    (msz = strlen(mnt.mnt_mountp)) > mntlen) {
747 			mntlen = msz;
748 			*is_zfs = strcmp(MNTTYPE_ZFS, mnt.mnt_fstype) == 0;
749 			(void) strlcpy(mntsp, mnt.mnt_special, sizeof (mntsp));
750 		}
751 	}
752 
753 	(void) fclose(mtabp);
754 
755 	if (mntlen > 1)
756 		*fpth += mntlen;
757 
758 	if (!*is_zfs)
759 		return (0);
760 
761 	if ((g_zfs = libzfs_init()) == NULL)
762 		return (-1);
763 
764 	/* Try to open the dataset */
765 	if ((zhp = zfs_open(g_zfs, mntsp,
766 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_DATASET)) == NULL) {
767 		(void) fprintf(stderr, gettext("Cannot open %s\n"), mntsp);
768 		rc = -1;
769 		goto validate_zfs_err_out;
770 	}
771 
772 	(void) strlcpy(bootfs, mntsp, sizeof (bootfs));
773 
774 	if ((poolname = strtok(mntsp, "/")) == NULL) {
775 		rc = -1;
776 		goto validate_zfs_err_out;
777 	}
778 
779 	if ((zpoolp = zpool_open(g_zfs, poolname)) == NULL) {
780 		(void) fprintf(stderr, gettext("Cannot open %s\n"), poolname);
781 		rc = -1;
782 		goto validate_zfs_err_out;
783 	}
784 
785 	if (zpool_get_physpath(zpoolp, physpath, sizeof (physpath)) != 0) {
786 		(void) fprintf(stderr, gettext("Cannot find phys_path\n"));
787 		rc = -1;
788 		goto validate_zfs_err_out;
789 	}
790 
791 	/*
792 	 * For the mirror physpath would contain the list of all
793 	 * bootable devices, pick up the first one.
794 	 */
795 	(void) strtok(physpath, " ");
796 	if (snprintf(bootfs_arg, BOOTARGS_MAX, fmt, bootfs, physpath) >=
797 	    BOOTARGS_MAX) {
798 		rc = E2BIG;
799 		(void) fprintf(stderr,
800 		    gettext("Boot arguments are too long\n"));
801 	}
802 
803 validate_zfs_err_out:
804 	if (zhp != NULL)
805 		zfs_close(zhp);
806 
807 	if (zpoolp != NULL)
808 		zpool_close(zpoolp);
809 
810 	libzfs_fini(g_zfs);
811 	return (rc);
812 }
813 
814 /*
815  * Validate that the file exists, and is an ELF file.
816  * Returns 0 on success, -1 on failure.
817  */
818 static int
819 validate_unix(char *arg, int *mplen, int *is_zfs, char *bootfs_arg)
820 {
821 	const char *location;
822 	int class, format;
823 	unsigned char ident[EI_NIDENT];
824 	char physpath[MAXPATHLEN];
825 	int elffd = -1;
826 	size_t	sz;
827 
828 	if ((sz = resolvepath(arg, physpath, sizeof (physpath) - 1)) ==
829 	    (size_t)-1) {
830 		(void) fprintf(stderr,
831 		    gettext("Cannot resolve path for %s: %s\n"),
832 		    arg, strerror(errno));
833 		return (-1);
834 	}
835 	(void) strlcpy(arg, physpath, sz + 1);
836 
837 	if (strlen(arg) > MAXPATHLEN) {
838 		(void) fprintf(stderr,
839 		    gettext("%s: New kernel name is too long\n"), cmdname);
840 		return (-1);
841 	}
842 
843 	if (strncmp(basename(arg), "unix", 4) != 0) {
844 		(void) fprintf(stderr,
845 		    gettext("%s: %s: Kernel name must be unix\n"),
846 		    cmdname, arg);
847 		return (-1);
848 	}
849 
850 	if (get_zfs_bootfs_arg(arg, &location, is_zfs, bootfs_arg) != 0)
851 		goto err_out;
852 
853 	*mplen = location - arg;
854 
855 	if (strstr(location, "/boot/platform") == location) {
856 		/*
857 		 * Rebooting to failsafe.
858 		 * Clear bootfs_arg and is_zfs flag.
859 		 */
860 		bootfs_arg[0] = 0;
861 		*is_zfs = 0;
862 	} else if (strstr(location, "/platform") != location) {
863 		(void) fprintf(stderr,
864 		    gettext("%s: %s: No /platform in file name\n"),
865 		    cmdname, arg);
866 		goto err_out;
867 	}
868 
869 	if ((elffd = open64(arg, O_RDONLY)) < 0 ||
870 	    (pread64(elffd, ident, EI_NIDENT, 0) != EI_NIDENT)) {
871 		(void) fprintf(stderr, "%s: %s: %s\n",
872 		    cmdname, arg, strerror(errno));
873 		goto err_out;
874 	}
875 
876 	class = ident[EI_CLASS];
877 
878 	if ((class != ELFCLASS32 && class != ELFCLASS64) ||
879 	    memcmp(&ident[EI_MAG0], ELFMAG, 4) != 0) {
880 		(void) fprintf(stderr,
881 		    gettext("%s: %s: Not a valid ELF file\n"), cmdname, arg);
882 		goto err_out;
883 	}
884 
885 	format = ident[EI_DATA];
886 
887 	if (format != CUR_ELFDATA) {
888 		(void) fprintf(stderr, gettext("%s: %s: Invalid data format\n"),
889 		    cmdname, arg);
890 		goto err_out;
891 	}
892 
893 	return (0);
894 
895 err_out:
896 	if (elffd >= 0) {
897 		(void) close(elffd);
898 		elffd = -1;
899 	}
900 	return (-1);
901 }
902 
903 static int
904 halt_exec(const char *path, ...)
905 {
906 	pid_t		pid;
907 	int		i;
908 	int		st;
909 	const char	*arg;
910 	va_list	vp;
911 	const char	*argv[256];
912 
913 	if ((pid = fork()) == -1) {
914 		return (errno);
915 	} else if (pid == 0) {
916 		(void) fclose(stdout);
917 		(void) fclose(stderr);
918 
919 		argv[0] = path;
920 		i = 1;
921 
922 		va_start(vp, path);
923 
924 		do {
925 			arg = va_arg(vp, const char *);
926 			argv[i] = arg;
927 		} while (arg != NULL &&
928 		    ++i != sizeof (argv) / sizeof (argv[0]));
929 
930 		va_end(vp);
931 
932 		(void) execve(path, (char * const *)argv, NULL);
933 		(void) fprintf(stderr, gettext("Cannot execute %s: %s\n"),
934 		    path, strerror(errno));
935 		exit(-1);
936 	} else {
937 		if (waitpid(pid, &st, 0) == pid &&
938 		    !WIFSIGNALED(st) && WIFEXITED(st))
939 			st = WEXITSTATUS(st);
940 		else
941 			st = -1;
942 	}
943 	return (st);
944 }
945 
946 /*
947  * Mount the specified BE.
948  *
949  * Upon success returns zero and copies bename string to mountpoint[]
950  */
951 static int
952 fastboot_bename(const char *bename, char *mountpoint, size_t mpsz)
953 {
954 	int rc;
955 
956 	/*
957 	 * Attempt to unmount the BE first in case it's already mounted
958 	 * elsewhere.
959 	 */
960 	(void) halt_exec(BEADM_PROG, "umount", bename, NULL);
961 
962 	if ((rc = halt_exec(BEADM_PROG, "mount", bename, FASTBOOT_MOUNTPOINT,
963 	    NULL)) != 0)
964 		(void) fprintf(stderr,
965 		    gettext("%s: Unable to mount BE \"%s\" at %s\n"),
966 		    cmdname, bename, FASTBOOT_MOUNTPOINT);
967 	else
968 		(void) strlcpy(mountpoint, FASTBOOT_MOUNTPOINT, mpsz);
969 
970 	return (rc);
971 }
972 
973 /*
974  * Returns 0 on successful parsing of the arguments;
975  * returns EINVAL on parsing failures that should abort the reboot attempt;
976  * returns other error code to fall back to regular reboot.
977  */
978 static int
979 parse_fastboot_args(char *bootargs_buf, size_t buf_size,
980     int *is_dryrun, const char *bename)
981 {
982 	char mountpoint[MAXPATHLEN];
983 	char bootargs_saved[BOOTARGS_MAX];
984 	char bootargs_scratch[BOOTARGS_MAX];
985 	char bootfs_arg[BOOTARGS_MAX];
986 	char unixfile[BOOTARGS_MAX];
987 	char *head, *newarg;
988 	int buflen;		/* length of the bootargs_buf */
989 	int mplen;		/* length of the mount point */
990 	int rootlen = 0;	/* length of the root argument */
991 	int unixlen = 0;	/* length of the unix argument */
992 	int off = 0;		/* offset into the new boot argument */
993 	int is_zfs = 0;
994 	int rc = 0;
995 
996 	bzero(mountpoint, sizeof (mountpoint));
997 
998 	/*
999 	 * If argc is not 0, buflen is length of the argument being passed in;
1000 	 * else it is 0 as bootargs_buf has been initialized to all 0's.
1001 	 */
1002 	buflen = strlen(bootargs_buf);
1003 
1004 	/* Save a copy of the original argument */
1005 	bcopy(bootargs_buf, bootargs_saved, buflen);
1006 	bzero(&bootargs_saved[buflen], sizeof (bootargs_saved) - buflen);
1007 
1008 	/* Save another copy to be used by strtok */
1009 	bcopy(bootargs_buf, bootargs_scratch, buflen);
1010 	bzero(&bootargs_scratch[buflen], sizeof (bootargs_scratch) - buflen);
1011 	head = &bootargs_scratch[0];
1012 
1013 	/* Get the first argument */
1014 	newarg = strtok(bootargs_scratch, " ");
1015 
1016 	/*
1017 	 * If this is a dry run request, verify that the drivers can handle
1018 	 * fast reboot.
1019 	 */
1020 	if (newarg && strncasecmp(newarg, "dryrun", strlen("dryrun")) == 0) {
1021 		*is_dryrun = 1;
1022 		(void) system("/usr/sbin/devfsadm");
1023 	}
1024 
1025 	/*
1026 	 * Always perform a dry run to identify all the drivers that
1027 	 * need to implement devo_reset().
1028 	 */
1029 	if (uadmin(A_SHUTDOWN, AD_FASTREBOOT_DRYRUN,
1030 	    (uintptr_t)bootargs_saved) != 0) {
1031 		(void) fprintf(stderr, gettext("%s: Not all drivers "
1032 		    "have implemented quiesce(9E)\n"
1033 		    "\tPlease see /var/adm/messages for drivers that haven't\n"
1034 		    "\timplemented quiesce(9E).\n"), cmdname);
1035 	} else if (*is_dryrun) {
1036 		(void) fprintf(stderr, gettext("%s: All drivers have "
1037 		    "implemented quiesce(9E)\n"), cmdname);
1038 	}
1039 
1040 	/* Return if it is a true dry run. */
1041 	if (*is_dryrun)
1042 		return (rc);
1043 
1044 #if defined(__i386)
1045 	/* Read boot args from GRUB menu */
1046 	if ((bootargs_buf[0] == 0 || isdigit(bootargs_buf[0])) &&
1047 	    bename == NULL) {
1048 		/*
1049 		 * If no boot arguments are given, or a GRUB menu entry
1050 		 * number is provided, process the GRUB menu.
1051 		 */
1052 		int entnum;
1053 		if (bootargs_buf[0] == 0)
1054 			entnum = GRUB_ENTRY_DEFAULT;
1055 		else {
1056 			errno = 0;
1057 			entnum = strtoul(bootargs_buf, NULL, 10);
1058 			rc = errno;
1059 		}
1060 
1061 		if (rc == 0 && (rc = grub_get_boot_args(&fbarg, NULL,
1062 		    entnum)) == 0) {
1063 			if (strlcpy(bootargs_buf, fbarg.gba_bootargs,
1064 			    buf_size) >= buf_size) {
1065 				grub_cleanup_boot_args(&fbarg);
1066 				bcopy(bootargs_saved, bootargs_buf, buf_size);
1067 				rc = E2BIG;
1068 			}
1069 		}
1070 		/* Failed to read GRUB menu, fall back to normal reboot */
1071 		if (rc != 0) {
1072 			(void) fprintf(stderr,
1073 			    gettext("%s: Failed to process GRUB menu "
1074 			    "entry for fast reboot.\n\t%s\n"),
1075 			    cmdname, grub_strerror(rc));
1076 			(void) fprintf(stderr,
1077 			    gettext("%s: Falling back to regular reboot.\n"),
1078 			    cmdname);
1079 			return (-1);
1080 		}
1081 		/* No need to process further */
1082 		fbarg_used = &fbarg;
1083 		fbarg_entnum = entnum;
1084 		return (0);
1085 	}
1086 #endif	/* __i386 */
1087 
1088 	/* Zero out the boot argument buffer as we will reconstruct it */
1089 	bzero(bootargs_buf, buf_size);
1090 	bzero(bootfs_arg, sizeof (bootfs_arg));
1091 	bzero(unixfile, sizeof (unixfile));
1092 
1093 	if (bename && (rc = fastboot_bename(bename, mountpoint,
1094 	    sizeof (mountpoint))) != 0)
1095 		return (EINVAL);
1096 
1097 
1098 	/*
1099 	 * If BE is not specified, look for disk argument to construct
1100 	 * mountpoint; if BE has been specified, mountpoint has already been
1101 	 * constructed.
1102 	 */
1103 	if (newarg && newarg[0] != '-' && !bename) {
1104 		int tmprc;
1105 
1106 		if ((tmprc = validate_disk(newarg, mountpoint)) == 0) {
1107 			/*
1108 			 * The first argument is a valid root argument.
1109 			 * Get the next argument.
1110 			 */
1111 			newarg = strtok(NULL, " ");
1112 			rootlen = (newarg) ? (newarg - head) : buflen;
1113 			(void) strlcpy(fastboot_mounted, mountpoint,
1114 			    sizeof (fastboot_mounted));
1115 
1116 		} else if (tmprc == -1) {
1117 			/*
1118 			 * Not a disk argument.  Use / as default root.
1119 			 */
1120 			bcopy("/", mountpoint, 1);
1121 			bzero(&mountpoint[1], sizeof (mountpoint) - 1);
1122 		} else {
1123 			/*
1124 			 * Disk argument, but not valid or not root.
1125 			 * Return failure.
1126 			 */
1127 			return (EINVAL);
1128 		}
1129 	}
1130 
1131 	/*
1132 	 * Make mountpoint the first part of unixfile.
1133 	 * If there is not disk argument, and BE has not been specified,
1134 	 * mountpoint could be empty.
1135 	 */
1136 	mplen = strlen(mountpoint);
1137 	bcopy(mountpoint, unixfile, mplen);
1138 
1139 	/*
1140 	 * Look for unix argument
1141 	 */
1142 	if (newarg && newarg[0] != '-') {
1143 		bcopy(newarg, &unixfile[mplen], strlen(newarg));
1144 		newarg = strtok(NULL, " ");
1145 		rootlen = (newarg) ? (newarg - head) : buflen;
1146 	} else if (mplen != 0) {
1147 		/*
1148 		 * No unix argument, but mountpoint is not empty, use
1149 		 * /platform/i86pc/$ISADIR/kernel/unix as default.
1150 		 */
1151 		char isa[20];
1152 
1153 		if (sysinfo(SI_ARCHITECTURE_64, isa, sizeof (isa)) != -1)
1154 			(void) snprintf(&unixfile[mplen],
1155 			    sizeof (unixfile) - mplen,
1156 			    "/platform/i86pc/kernel/%s/unix", isa);
1157 		else if (sysinfo(SI_ARCHITECTURE_32, isa, sizeof (isa)) != -1) {
1158 			(void) snprintf(&unixfile[mplen],
1159 			    sizeof (unixfile) - mplen,
1160 			    "/platform/i86pc/kernel/unix");
1161 		} else {
1162 			(void) fprintf(stderr,
1163 			    gettext("%s: Unknown architecture"), cmdname);
1164 			return (EINVAL);
1165 		}
1166 	}
1167 
1168 	/*
1169 	 * We now have the complete unix argument.  Verify that it exists and
1170 	 * is an ELF file.  Split the argument up into mountpoint and unix
1171 	 * portions again.  This is necessary to handle cases where mountpoint
1172 	 * is specified on the command line as part of the unix argument,
1173 	 * such as this:
1174 	 *	# reboot -f /.alt/platform/i86pc/kernel/amd64/unix
1175 	 */
1176 	unixlen = strlen(unixfile);
1177 	if (unixlen > 0) {
1178 		if (validate_unix(unixfile, &mplen, &is_zfs,
1179 		    bootfs_arg) != 0) {
1180 			/* Not a valid unix file */
1181 			return (EINVAL);
1182 		} else {
1183 			int space = 0;
1184 			/*
1185 			 * Construct boot argument.
1186 			 */
1187 			unixlen = strlen(unixfile);
1188 
1189 			/*
1190 			 * mdep cannot start with space because bootadm
1191 			 * creates bogus menu entries if it does.
1192 			 */
1193 			if (mplen > 0) {
1194 				bcopy(unixfile, bootargs_buf, mplen);
1195 				(void) strcat(bootargs_buf, " ");
1196 				space = 1;
1197 			}
1198 			bcopy(&unixfile[mplen], &bootargs_buf[mplen + space],
1199 			    unixlen - mplen);
1200 			(void) strcat(bootargs_buf, " ");
1201 			off += unixlen + space + 1;
1202 		}
1203 	} else {
1204 		/* Check to see if root is zfs */
1205 		const char	*dp;
1206 		(void) get_zfs_bootfs_arg("/", &dp, &is_zfs, bootfs_arg);
1207 	}
1208 
1209 	if (is_zfs && (buflen != 0 || bename != NULL))	{
1210 		/* LINTED E_SEC_SPRINTF_UNBOUNDED_COPY */
1211 		off += sprintf(bootargs_buf + off, "%s ", bootfs_arg);
1212 	}
1213 
1214 	/*
1215 	 * Copy the rest of the arguments
1216 	 */
1217 	bcopy(&bootargs_saved[rootlen], &bootargs_buf[off], buflen - rootlen);
1218 
1219 	return (rc);
1220 }
1221 
1222 #define	MAXARGS		5
1223 
1224 static void
1225 do_archives_update(int do_fast_reboot)
1226 {
1227 	int	r, i = 0;
1228 	pid_t	pid;
1229 	char	*cmd_argv[MAXARGS];
1230 
1231 
1232 	cmd_argv[i++] = "/sbin/bootadm";
1233 	cmd_argv[i++] = "-ea";
1234 	cmd_argv[i++] = "update_all";
1235 	if (do_fast_reboot)
1236 		cmd_argv[i++] = "fastboot";
1237 	cmd_argv[i] = NULL;
1238 
1239 	r = posix_spawn(&pid, cmd_argv[0], NULL, NULL, cmd_argv, NULL);
1240 
1241 	/* if posix_spawn fails we emit a warning and continue */
1242 
1243 	if (r != 0)
1244 		(void) fprintf(stderr, gettext("%s: WARNING, unable to start "
1245 		    "boot archive update\n"), cmdname);
1246 	else
1247 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
1248 			;
1249 }
1250 
1251 int
1252 main(int argc, char *argv[])
1253 {
1254 	char *ttyn = ttyname(STDERR_FILENO);
1255 
1256 	int qflag = 0, needlog = 1, nosync = 0;
1257 	int fast_reboot = 0;
1258 	int prom_reboot = 0;
1259 	uintptr_t mdep = NULL;
1260 	int cmd, fcn, c, aval, r;
1261 	const char *usage;
1262 	const char *optstring;
1263 	zoneid_t zoneid = getzoneid();
1264 	int need_check_zones = 0;
1265 	char bootargs_buf[BOOTARGS_MAX];
1266 	char *bootargs_orig = NULL;
1267 	char *bename = NULL;
1268 
1269 	const char * const resetting = "/etc/svc/volatile/resetting";
1270 
1271 	(void) setlocale(LC_ALL, "");
1272 	(void) textdomain(TEXT_DOMAIN);
1273 
1274 	cmdname = basename(argv[0]);
1275 
1276 	if (strcmp(cmdname, "halt") == 0) {
1277 		(void) audit_halt_setup(argc, argv);
1278 		optstring = "dlnqy";
1279 		usage = gettext("usage: %s [ -dlnqy ]\n");
1280 		cmd = A_SHUTDOWN;
1281 		fcn = AD_HALT;
1282 	} else if (strcmp(cmdname, "poweroff") == 0) {
1283 		(void) audit_halt_setup(argc, argv);
1284 		optstring = "dlnqy";
1285 		usage = gettext("usage: %s [ -dlnqy ]\n");
1286 		cmd = A_SHUTDOWN;
1287 		fcn = AD_POWEROFF;
1288 	} else if (strcmp(cmdname, "reboot") == 0) {
1289 		(void) audit_reboot_setup();
1290 #if defined(__i386)
1291 		optstring = "dlnqpfe:";
1292 		usage = gettext("usage: %s [ -dlnq(p|fe:) ] [ boot args ]\n");
1293 #else
1294 		optstring = "dlnqfp";
1295 		usage = gettext("usage: %s [ -dlnq(p|f) ] [ boot args ]\n");
1296 #endif
1297 		cmd = A_SHUTDOWN;
1298 		fcn = AD_BOOT;
1299 	} else {
1300 		(void) fprintf(stderr,
1301 		    gettext("%s: not installed properly\n"), cmdname);
1302 		return (1);
1303 	}
1304 
1305 	while ((c = getopt(argc, argv, optstring)) != EOF) {
1306 		switch (c) {
1307 		case 'd':
1308 			if (zoneid == GLOBAL_ZONEID)
1309 				cmd = A_DUMP;
1310 			else {
1311 				(void) fprintf(stderr,
1312 				    gettext("%s: -d only valid from global"
1313 				    " zone\n"), cmdname);
1314 				return (1);
1315 			}
1316 			break;
1317 		case 'l':
1318 			needlog = 0;
1319 			break;
1320 		case 'n':
1321 			nosync = 1;
1322 			break;
1323 		case 'q':
1324 			qflag = 1;
1325 			break;
1326 		case 'y':
1327 			ttyn = NULL;
1328 			break;
1329 		case 'f':
1330 			fast_reboot = 1;
1331 			break;
1332 		case 'p':
1333 			prom_reboot = 1;
1334 			break;
1335 #if defined(__i386)
1336 		case 'e':
1337 			bename = optarg;
1338 			break;
1339 #endif
1340 		default:
1341 			/*
1342 			 * TRANSLATION_NOTE
1343 			 * Don't translate the words "halt" or "reboot"
1344 			 */
1345 			(void) fprintf(stderr, usage, cmdname);
1346 			return (1);
1347 		}
1348 	}
1349 
1350 	argc -= optind;
1351 	argv += optind;
1352 
1353 	if (argc != 0) {
1354 		if (fcn != AD_BOOT) {
1355 			(void) fprintf(stderr, usage, cmdname);
1356 			return (1);
1357 		}
1358 
1359 		/* Gather the arguments into bootargs_buf. */
1360 		if (gather_args(argv, bootargs_buf, sizeof (bootargs_buf)) !=
1361 		    0) {
1362 			(void) fprintf(stderr,
1363 			    gettext("%s: Boot arguments too long.\n"), cmdname);
1364 			return (1);
1365 		}
1366 
1367 		bootargs_orig = strdup(bootargs_buf);
1368 		mdep = (uintptr_t)bootargs_buf;
1369 	} else {
1370 		/*
1371 		 * Initialize it to 0 in case of fastboot, the buffer
1372 		 * will be used.
1373 		 */
1374 		bzero(bootargs_buf, sizeof (bootargs_buf));
1375 	}
1376 
1377 	if (geteuid() != 0) {
1378 		(void) fprintf(stderr,
1379 		    gettext("%s: permission denied\n"), cmdname);
1380 		goto fail;
1381 	}
1382 
1383 	if (fast_reboot && prom_reboot) {
1384 		(void) fprintf(stderr,
1385 		    gettext("%s: -p and -f are mutually exclusive\n"),
1386 		    cmdname);
1387 		return (EINVAL);
1388 	}
1389 	/*
1390 	 * Check whether fast reboot is the default operating mode
1391 	 */
1392 	if (fcn == AD_BOOT && !fast_reboot && !prom_reboot &&
1393 	    zoneid == GLOBAL_ZONEID) {
1394 		fast_reboot = scf_is_fastboot_default();
1395 
1396 	}
1397 
1398 	if (bename && !fast_reboot)	{
1399 		(void) fprintf(stderr, gettext("%s: -e only valid with -f\n"),
1400 		    cmdname);
1401 		return (EINVAL);
1402 	}
1403 
1404 #if defined(__sparc)
1405 	if (fast_reboot) {
1406 		fast_reboot = 2;	/* need to distinguish each case */
1407 	}
1408 #endif
1409 
1410 	/*
1411 	 * If fast reboot, do some sanity check on the argument
1412 	 */
1413 	if (fast_reboot == 1) {
1414 		int rc;
1415 		int is_dryrun = 0;
1416 
1417 		if (zoneid != GLOBAL_ZONEID)	{
1418 			(void) fprintf(stderr,
1419 			    gettext("%s: Fast reboot only valid from global"
1420 			    " zone\n"), cmdname);
1421 			return (EINVAL);
1422 		}
1423 
1424 		rc = parse_fastboot_args(bootargs_buf, sizeof (bootargs_buf),
1425 		    &is_dryrun, bename);
1426 
1427 		/*
1428 		 * If dry run, or if arguments are invalid, return.
1429 		 */
1430 		if (is_dryrun)
1431 			return (rc);
1432 		else if (rc == EINVAL)
1433 			goto fail;
1434 		else if (rc != 0)
1435 			fast_reboot = 0;
1436 
1437 		/*
1438 		 * For all the other errors, we continue on in case user
1439 		 * user want to force fast reboot, or fall back to regular
1440 		 * reboot.
1441 		 */
1442 		if (strlen(bootargs_buf) != 0)
1443 			mdep = (uintptr_t)bootargs_buf;
1444 	}
1445 
1446 #if 0	/* For debugging */
1447 	if (mdep != NULL)
1448 		(void) fprintf(stderr, "mdep = %s\n", (char *)mdep);
1449 #endif
1450 
1451 	if (fcn != AD_BOOT && ttyn != NULL &&
1452 	    strncmp(ttyn, "/dev/term/", strlen("/dev/term/")) == 0) {
1453 		/*
1454 		 * TRANSLATION_NOTE
1455 		 * Don't translate ``halt -y''
1456 		 */
1457 		(void) fprintf(stderr,
1458 		    gettext("%s: dangerous on a dialup;"), cmdname);
1459 		(void) fprintf(stderr,
1460 		    gettext("use ``%s -y'' if you are really sure\n"), cmdname);
1461 		goto fail;
1462 	}
1463 
1464 	if (needlog) {
1465 		char *user = getlogin();
1466 		struct passwd *pw;
1467 		char *tty;
1468 
1469 		openlog(cmdname, 0, LOG_AUTH);
1470 		if (user == NULL && (pw = getpwuid(getuid())) != NULL)
1471 			user = pw->pw_name;
1472 		if (user == NULL)
1473 			user = "root";
1474 
1475 		tty = ttyname(1);
1476 
1477 		if (tty == NULL)
1478 			syslog(LOG_CRIT, "initiated by %s", user);
1479 		else
1480 			syslog(LOG_CRIT, "initiated by %s on %s", user, tty);
1481 	}
1482 
1483 	/*
1484 	 * We must assume success and log it before auditd is terminated.
1485 	 */
1486 	if (fcn == AD_BOOT)
1487 		aval = audit_reboot_success();
1488 	else
1489 		aval = audit_halt_success();
1490 
1491 	if (aval == -1) {
1492 		(void) fprintf(stderr,
1493 		    gettext("%s: can't turn off auditd\n"), cmdname);
1494 		if (needlog)
1495 			(void) sleep(5); /* Give syslogd time to record this */
1496 	}
1497 
1498 	(void) signal(SIGHUP, SIG_IGN);	/* for remote connections */
1499 
1500 	/*
1501 	 * We start to fork a bunch of zoneadms to halt any active zones.
1502 	 * This will proceed with halt in parallel until we call
1503 	 * check_zone_haltedness later on.
1504 	 */
1505 	if (zoneid == GLOBAL_ZONEID && cmd != A_DUMP) {
1506 		need_check_zones = halt_zones();
1507 	}
1508 
1509 #if defined(__i386)
1510 	/* set new default entry in the GRUB entry */
1511 	if (fbarg_entnum != GRUB_ENTRY_DEFAULT) {
1512 		char buf[32];
1513 		(void) snprintf(buf, sizeof (buf), "default=%u", fbarg_entnum);
1514 		(void) halt_exec(BOOTADM_PROG, "set-menu", buf, NULL);
1515 	}
1516 #endif	/* __i386 */
1517 
1518 	/* if we're dumping, do the archive update here and don't defer it */
1519 	if (cmd == A_DUMP && zoneid == GLOBAL_ZONEID && !nosync)
1520 		do_archives_update(fast_reboot);
1521 
1522 	/*
1523 	 * If we're not forcing a crash dump, mark the system as quiescing for
1524 	 * smf(5)'s benefit, and idle the init process.
1525 	 */
1526 	if (cmd != A_DUMP) {
1527 		if (direct_init(PCDSTOP) == -1) {
1528 			/*
1529 			 * TRANSLATION_NOTE
1530 			 * Don't translate the word "init"
1531 			 */
1532 			(void) fprintf(stderr,
1533 			    gettext("%s: can't idle init\n"), cmdname);
1534 			goto fail;
1535 		}
1536 
1537 		if (creat(resetting, 0755) == -1)
1538 			(void) fprintf(stderr,
1539 			    gettext("%s: could not create %s.\n"),
1540 			    cmdname, resetting);
1541 	}
1542 
1543 	/*
1544 	 * Make sure we don't get stopped by a jobcontrol shell
1545 	 * once we start killing everybody.
1546 	 */
1547 	(void) signal(SIGTSTP, SIG_IGN);
1548 	(void) signal(SIGTTIN, SIG_IGN);
1549 	(void) signal(SIGTTOU, SIG_IGN);
1550 	(void) signal(SIGPIPE, SIG_IGN);
1551 	(void) signal(SIGTERM, SIG_IGN);
1552 
1553 	/*
1554 	 * Try to stop gdm so X has a chance to return the screen and
1555 	 * keyboard to a sane state.
1556 	 */
1557 	if (fast_reboot == 1 && stop_gdm() != 0) {
1558 		(void) fprintf(stderr,
1559 		    gettext("%s: Falling back to regular reboot.\n"), cmdname);
1560 		fast_reboot = 0;
1561 		mdep = (uintptr_t)bootargs_orig;
1562 	} else if (bootargs_orig) {
1563 		free(bootargs_orig);
1564 	}
1565 
1566 	if (cmd != A_DUMP) {
1567 		/*
1568 		 * Stop all restarters so they do not try to restart services
1569 		 * that are terminated.
1570 		 */
1571 		stop_restarters();
1572 
1573 		/*
1574 		 * Wait a little while for zones to shutdown.
1575 		 */
1576 		if (need_check_zones) {
1577 			check_zones_haltedness();
1578 
1579 			(void) fprintf(stderr,
1580 			    gettext("%s: Completing system halt.\n"),
1581 			    cmdname);
1582 		}
1583 	}
1584 
1585 	/*
1586 	 * If we're not forcing a crash dump, give everyone 5 seconds to
1587 	 * handle a SIGTERM and clean up properly.
1588 	 */
1589 	if (cmd != A_DUMP) {
1590 		int	start, end, delta;
1591 
1592 		(void) kill(-1, SIGTERM);
1593 		start = time(NULL);
1594 
1595 		if (zoneid == GLOBAL_ZONEID && !nosync)
1596 			do_archives_update(fast_reboot);
1597 
1598 		end = time(NULL);
1599 		delta = end - start;
1600 		if (delta < 5)
1601 			(void) sleep(5 - delta);
1602 	}
1603 
1604 	(void) signal(SIGINT, SIG_IGN);
1605 
1606 	if (!qflag && !nosync) {
1607 		struct utmpx wtmpx;
1608 
1609 		bzero(&wtmpx, sizeof (struct utmpx));
1610 		(void) strcpy(wtmpx.ut_line, "~");
1611 		(void) time(&wtmpx.ut_tv.tv_sec);
1612 
1613 		if (cmd == A_DUMP)
1614 			(void) strcpy(wtmpx.ut_name, "crash dump");
1615 		else
1616 			(void) strcpy(wtmpx.ut_name, "shutdown");
1617 
1618 		(void) updwtmpx(WTMPX_FILE, &wtmpx);
1619 		sync();
1620 	}
1621 
1622 	if (cmd == A_DUMP && nosync != 0)
1623 		(void) uadmin(A_DUMP, AD_NOSYNC, NULL);
1624 
1625 	if (fast_reboot)
1626 		fcn = AD_FASTREBOOT;
1627 
1628 	if (uadmin(cmd, fcn, mdep) == -1)
1629 		(void) fprintf(stderr, "%s: uadmin failed: %s\n",
1630 		    cmdname, strerror(errno));
1631 	else
1632 		(void) fprintf(stderr, "%s: uadmin unexpectedly returned 0\n",
1633 		    cmdname);
1634 
1635 	do {
1636 		r = remove(resetting);
1637 	} while (r != 0 && errno == EINTR);
1638 
1639 	if (r != 0 && errno != ENOENT)
1640 		(void) fprintf(stderr, gettext("%s: could not remove %s.\n"),
1641 		    cmdname, resetting);
1642 
1643 	if (direct_init(PCRUN) == -1) {
1644 		/*
1645 		 * TRANSLATION_NOTE
1646 		 * Don't translate the word "init"
1647 		 */
1648 		(void) fprintf(stderr,
1649 		    gettext("%s: can't resume init\n"), cmdname);
1650 	}
1651 
1652 	continue_restarters();
1653 
1654 	if (get_initpid() != -1)
1655 		/* tell init to restate current level */
1656 		(void) kill(get_initpid(), SIGHUP);
1657 
1658 fail:
1659 	if (fcn == AD_BOOT)
1660 		(void) audit_reboot_fail();
1661 	else
1662 		(void) audit_halt_fail();
1663 
1664 	if (fast_reboot == 1) {
1665 		if (bename) {
1666 			(void) halt_exec(BEADM_PROG, "umount", bename, NULL);
1667 
1668 		} else if (strlen(fastboot_mounted) != 0) {
1669 			(void) umount(fastboot_mounted);
1670 #if defined(__i386)
1671 		} else if (fbarg_used != NULL) {
1672 			grub_cleanup_boot_args(fbarg_used);
1673 #endif	/* __i386 */
1674 		}
1675 	}
1676 
1677 	return (1);
1678 }
1679