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