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