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