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