xref: /titanic_50/usr/src/cmd/halt/halt.c (revision 24bb1048b1197ebc9afe761e4098573aeedfe8c9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /*
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2015 by Delphix. All rights reserved.
28  */
29 
30 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
31 /*	  All Rights Reserved	*/
32 
33 /*
34  * University Copyright- Copyright (c) 1982, 1986, 1988
35  * The Regents of the University of California
36  * All Rights Reserved
37  *
38  * University Acknowledgment- Portions of this document are derived from
39  * software developed by the University of California, Berkeley, and its
40  * contributors.
41  * Portions contributed by Juergen Keil, <jk@tools.de>.
42  */
43 
44 
45 /*
46  * Common code for halt(1M), poweroff(1M), and reboot(1M).  We use
47  * argv[0] to determine which behavior to exhibit.
48  */
49 
50 #include <stdio.h>
51 #include <procfs.h>
52 #include <sys/types.h>
53 #include <sys/elf.h>
54 #include <sys/systeminfo.h>
55 #include <sys/stat.h>
56 #include <sys/uadmin.h>
57 #include <sys/mntent.h>
58 #include <sys/mnttab.h>
59 #include <sys/mount.h>
60 #include <sys/fs/ufs_mount.h>
61 #include <alloca.h>
62 #include <assert.h>
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <libgen.h>
66 #include <libscf.h>
67 #include <libscf_priv.h>
68 #include <limits.h>
69 #include <locale.h>
70 #include <libintl.h>
71 #include <syslog.h>
72 #include <signal.h>
73 #include <strings.h>
74 #include <unistd.h>
75 #include <stdlib.h>
76 #include <stdio.h>
77 #include <strings.h>
78 #include <time.h>
79 #include <wait.h>
80 #include <ctype.h>
81 #include <utmpx.h>
82 #include <pwd.h>
83 #include <zone.h>
84 #include <spawn.h>
85 
86 #include <libzfs.h>
87 #if defined(__i386)
88 #include <libgrubmgmt.h>
89 #endif
90 
91 #if !defined(TEXT_DOMAIN)
92 #define	TEXT_DOMAIN	"SYS_TEST"
93 #endif
94 
95 #if defined(__sparc)
96 #define	CUR_ELFDATA	ELFDATA2MSB
97 #elif defined(__i386)
98 #define	CUR_ELFDATA	ELFDATA2LSB
99 #endif
100 
101 static libzfs_handle_t *g_zfs;
102 
103 extern int audit_halt_setup(int, char **);
104 extern int audit_halt_success(void);
105 extern int audit_halt_fail(void);
106 
107 extern int audit_reboot_setup(void);
108 extern int audit_reboot_success(void);
109 extern int audit_reboot_fail(void);
110 
111 static char *cmdname;	/* basename(argv[0]), the name of the command */
112 
113 typedef struct ctidlist_struct {
114 	ctid_t ctid;
115 	struct ctidlist_struct *next;
116 } ctidlist_t;
117 
118 static ctidlist_t *ctidlist = NULL;
119 static ctid_t startdct = -1;
120 
121 #define	FMRI_STARTD_CONTRACT \
122 	"svc:/system/svc/restarter:default/:properties/restarter/contract"
123 
124 #define	BEADM_PROG	"/usr/sbin/beadm"
125 #define	BOOTADM_PROG	"/sbin/bootadm"
126 #define	ZONEADM_PROG	"/usr/sbin/zoneadm"
127 
128 /*
129  * The length of FASTBOOT_MOUNTPOINT must be less than MAXPATHLEN.
130  */
131 #define	FASTBOOT_MOUNTPOINT	"/tmp/.fastboot.root"
132 
133 /*
134  * Fast Reboot related variables
135  */
136 static char	fastboot_mounted[MAXPATHLEN];
137 
138 #if defined(__i386)
139 static grub_boot_args_t	fbarg;
140 static grub_boot_args_t	*fbarg_used;
141 static int fbarg_entnum = GRUB_ENTRY_DEFAULT;
142 #endif	/* __i386 */
143 
144 static int validate_ufs_disk(char *, char *);
145 static int validate_zfs_pool(char *, char *);
146 
147 static pid_t
148 get_initpid()
149 {
150 	static int init_pid = -1;
151 
152 	if (init_pid == -1) {
153 		if (zone_getattr(getzoneid(), ZONE_ATTR_INITPID, &init_pid,
154 		    sizeof (init_pid)) != sizeof (init_pid)) {
155 			assert(errno == ESRCH);
156 			init_pid = -1;
157 		}
158 	}
159 	return (init_pid);
160 }
161 
162 /*
163  * Quiesce or resume init using /proc.  When stopping init, we can't send
164  * SIGTSTP (since init ignores it) or SIGSTOP (since the kernel won't permit
165  * it).
166  */
167 static int
168 direct_init(long command)
169 {
170 	char ctlfile[MAXPATHLEN];
171 	pid_t pid;
172 	int ctlfd;
173 
174 	assert(command == PCDSTOP || command == PCRUN);
175 	if ((pid = get_initpid()) == -1) {
176 		return (-1);
177 	}
178 
179 	(void) snprintf(ctlfile, sizeof (ctlfile), "/proc/%d/ctl", pid);
180 	if ((ctlfd = open(ctlfile, O_WRONLY)) == -1)
181 		return (-1);
182 
183 	if (command == PCDSTOP) {
184 		if (write(ctlfd, &command, sizeof (long)) == -1) {
185 			(void) close(ctlfd);
186 			return (-1);
187 		}
188 	} else {	/* command == PCRUN */
189 		long cmds[2];
190 		cmds[0] = command;
191 		cmds[1] = 0;
192 		if (write(ctlfd, cmds, sizeof (cmds)) == -1) {
193 			(void) close(ctlfd);
194 			return (-1);
195 		}
196 	}
197 	(void) close(ctlfd);
198 	return (0);
199 }
200 
201 static void
202 stop_startd()
203 {
204 	scf_handle_t *h;
205 	scf_property_t *prop = NULL;
206 	scf_value_t *val = NULL;
207 	uint64_t uint64;
208 
209 	if ((h = scf_handle_create(SCF_VERSION)) == NULL)
210 		return;
211 
212 	if ((scf_handle_bind(h) != 0) ||
213 	    ((prop = scf_property_create(h)) == NULL) ||
214 	    ((val = scf_value_create(h)) == NULL))
215 		goto out;
216 
217 	if (scf_handle_decode_fmri(h, FMRI_STARTD_CONTRACT,
218 	    NULL, NULL, NULL, NULL, prop, SCF_DECODE_FMRI_EXACT) != 0)
219 		goto out;
220 
221 	if (scf_property_is_type(prop, SCF_TYPE_COUNT) != 0 ||
222 	    scf_property_get_value(prop, val) != 0 ||
223 	    scf_value_get_count(val, &uint64) != 0)
224 		goto out;
225 
226 	startdct = (ctid_t)uint64;
227 	(void) sigsend(P_CTID, startdct, SIGSTOP);
228 
229 out:
230 	scf_property_destroy(prop);
231 	scf_value_destroy(val);
232 	scf_handle_destroy(h);
233 }
234 
235 static void
236 continue_startd()
237 {
238 	if (startdct != -1)
239 		(void) sigsend(P_CTID, startdct, SIGCONT);
240 }
241 
242 #define	FMRI_RESTARTER_PROP "/:properties/general/restarter"
243 #define	FMRI_CONTRACT_PROP "/:properties/restarter/contract"
244 
245 static int
246 save_ctid(ctid_t ctid)
247 {
248 	ctidlist_t *next;
249 
250 	for (next = ctidlist; next != NULL; next = next->next)
251 		if (next->ctid == ctid)
252 			return (-1);
253 
254 	next = (ctidlist_t *)malloc(sizeof (ctidlist_t));
255 	if (next == NULL)
256 		return (-1);
257 
258 	next->ctid = ctid;
259 	next->next = ctidlist;
260 	ctidlist = next;
261 	return (0);
262 }
263 
264 static void
265 stop_delegates()
266 {
267 	ctid_t ctid;
268 	scf_handle_t *h;
269 	scf_scope_t *sc = NULL;
270 	scf_service_t *svc = NULL;
271 	scf_instance_t *inst = NULL;
272 	scf_snapshot_t *snap = NULL;
273 	scf_snapshot_t *isnap = NULL;
274 	scf_propertygroup_t *pg = NULL;
275 	scf_property_t *prop = NULL;
276 	scf_value_t *val = NULL;
277 	scf_iter_t *siter = NULL;
278 	scf_iter_t *iiter = NULL;
279 	char *fmri;
280 	ssize_t length;
281 
282 	uint64_t uint64;
283 	ssize_t bytes;
284 
285 	length = scf_limit(SCF_LIMIT_MAX_FMRI_LENGTH);
286 	if (length <= 0)
287 		return;
288 
289 	length++;
290 	fmri = alloca(length * sizeof (char));
291 
292 	if ((h = scf_handle_create(SCF_VERSION)) == NULL)
293 		return;
294 
295 	if (scf_handle_bind(h) != 0) {
296 		scf_handle_destroy(h);
297 		return;
298 	}
299 
300 	if ((sc = scf_scope_create(h)) == NULL ||
301 	    (svc = scf_service_create(h)) == NULL ||
302 	    (inst = scf_instance_create(h)) == NULL ||
303 	    (snap = scf_snapshot_create(h)) == NULL ||
304 	    (pg = scf_pg_create(h)) == NULL ||
305 	    (prop = scf_property_create(h)) == NULL ||
306 	    (val = scf_value_create(h)) == NULL ||
307 	    (siter = scf_iter_create(h)) == NULL ||
308 	    (iiter = scf_iter_create(h)) == NULL)
309 		goto out;
310 
311 	if (scf_handle_get_scope(h, SCF_SCOPE_LOCAL, sc) != 0)
312 		goto out;
313 
314 	if (scf_iter_scope_services(siter, sc) != 0)
315 		goto out;
316 
317 	while (scf_iter_next_service(siter, svc) == 1) {
318 
319 		if (scf_iter_service_instances(iiter, svc) != 0)
320 			continue;
321 
322 		while (scf_iter_next_instance(iiter, inst) == 1) {
323 
324 			if ((scf_instance_get_snapshot(inst, "running",
325 			    snap)) != 0)
326 				isnap = NULL;
327 			else
328 				isnap = snap;
329 
330 			if (scf_instance_get_pg_composed(inst, isnap,
331 			    SCF_PG_GENERAL, pg) != 0)
332 				continue;
333 
334 			if (scf_pg_get_property(pg, SCF_PROPERTY_RESTARTER,
335 			    prop) != 0 ||
336 			    scf_property_get_value(prop, val) != 0)
337 				continue;
338 
339 			bytes = scf_value_get_astring(val, fmri, length);
340 			if (bytes <= 0 || bytes >= length)
341 				continue;
342 
343 			if (strlcat(fmri, FMRI_CONTRACT_PROP, length) >=
344 			    length)
345 				continue;
346 
347 			if (scf_handle_decode_fmri(h, fmri, NULL, NULL,
348 			    NULL, NULL, prop, SCF_DECODE_FMRI_EXACT) != 0)
349 				continue;
350 
351 			if (scf_property_is_type(prop, SCF_TYPE_COUNT) != 0 ||
352 			    scf_property_get_value(prop, val) != 0 ||
353 			    scf_value_get_count(val, &uint64) != 0)
354 				continue;
355 
356 			ctid = (ctid_t)uint64;
357 			if (save_ctid(ctid) == 0) {
358 				(void) sigsend(P_CTID, ctid, SIGSTOP);
359 			}
360 		}
361 	}
362 out:
363 	scf_scope_destroy(sc);
364 	scf_service_destroy(svc);
365 	scf_instance_destroy(inst);
366 	scf_snapshot_destroy(snap);
367 	scf_pg_destroy(pg);
368 	scf_property_destroy(prop);
369 	scf_value_destroy(val);
370 	scf_iter_destroy(siter);
371 	scf_iter_destroy(iiter);
372 
373 	(void) scf_handle_unbind(h);
374 	scf_handle_destroy(h);
375 }
376 
377 static void
378 continue_delegates()
379 {
380 	ctidlist_t *next;
381 	for (next = ctidlist; next != NULL; next = next->next)
382 		(void) sigsend(P_CTID, next->ctid, SIGCONT);
383 }
384 
385 #define	FMRI_GDM "svc:/application/graphical-login/gdm:default"
386 #define	GDM_STOP_TIMEOUT	10	/* Give gdm 10 seconds to shut down */
387 
388 /*
389  * If gdm is running, try to stop gdm.
390  * Returns  0 on success, -1 on failure.
391  */
392 static int
393 stop_gdm()
394 {
395 	char *gdm_state = NULL;
396 	int retry = 0;
397 
398 	/*
399 	 * If gdm is running, try to stop gdm.
400 	 */
401 	while ((gdm_state = smf_get_state(FMRI_GDM)) != NULL &&
402 	    strcmp(gdm_state, SCF_STATE_STRING_ONLINE) == 0 &&
403 	    retry++ < GDM_STOP_TIMEOUT) {
404 
405 		free(gdm_state);
406 
407 		/*
408 		 * Only need to disable once.
409 		 */
410 		if (retry == 1 &&
411 		    smf_disable_instance(FMRI_GDM, SMF_TEMPORARY) != 0) {
412 			(void) fprintf(stderr,
413 			    gettext("%s: Failed to stop %s: %s.\n"),
414 			    cmdname, FMRI_GDM, scf_strerror(scf_error()));
415 			return (-1);
416 		}
417 		(void) sleep(1);
418 	}
419 
420 	if (retry >= GDM_STOP_TIMEOUT) {
421 		(void) fprintf(stderr, gettext("%s: Failed to stop %s.\n"),
422 		    cmdname, FMRI_GDM);
423 		return (-1);
424 	}
425 
426 	return (0);
427 }
428 
429 
430 static void
431 stop_restarters()
432 {
433 	stop_startd();
434 	stop_delegates();
435 }
436 
437 static void
438 continue_restarters()
439 {
440 	continue_startd();
441 	continue_delegates();
442 }
443 
444 /*
445  * Copy an array of strings into buf, separated by spaces.  Returns 0 on
446  * success.
447  */
448 static int
449 gather_args(char **args, char *buf, size_t buf_sz)
450 {
451 	if (strlcpy(buf, *args, buf_sz) >= buf_sz)
452 		return (-1);
453 
454 	for (++args; *args != NULL; ++args) {
455 		if (strlcat(buf, " ", buf_sz) >= buf_sz)
456 			return (-1);
457 		if (strlcat(buf, *args, buf_sz) >= buf_sz)
458 			return (-1);
459 	}
460 
461 	return (0);
462 }
463 
464 /*
465  * Halt every zone on the system.  We are committed to doing a shutdown
466  * even if something goes wrong here. If something goes wrong, we just
467  * continue with the shutdown.  Return non-zero if we need to wait for zones to
468  * halt later on.
469  */
470 static int
471 halt_zones()
472 {
473 	pid_t pid;
474 	zoneid_t *zones;
475 	size_t nz = 0, old_nz;
476 	int i;
477 	char zname[ZONENAME_MAX];
478 
479 	/*
480 	 * Get a list of zones. If the number of zones changes in between the
481 	 * two zone_list calls, try again.
482 	 */
483 
484 	for (;;) {
485 		(void) zone_list(NULL, &nz);
486 		if (nz == 1)
487 			return (0);
488 		old_nz = nz;
489 		zones = calloc(sizeof (zoneid_t), nz);
490 		if (zones == NULL) {
491 			(void) fprintf(stderr,
492 			    gettext("%s: Could not halt zones"
493 			    " (out of memory).\n"), cmdname);
494 			return (0);
495 		}
496 
497 		(void) zone_list(zones, &nz);
498 		if (old_nz == nz)
499 			break;
500 		free(zones);
501 	}
502 
503 	if (nz == 2) {
504 		(void) fprintf(stderr, gettext("%s: Halting 1 zone.\n"),
505 		    cmdname);
506 	} else {
507 		(void) fprintf(stderr, gettext("%s: Halting %i zones.\n"),
508 		    cmdname, nz - 1);
509 	}
510 
511 	for (i = 0; i < nz; i++) {
512 		if (zones[i] == GLOBAL_ZONEID)
513 			continue;
514 		if (getzonenamebyid(zones[i], zname, sizeof (zname)) < 0) {
515 			/*
516 			 * getzonenamebyid should only fail if we raced with
517 			 * another process trying to shut down the zone.
518 			 * We assume this happened and ignore the error.
519 			 */
520 			if (errno != EINVAL) {
521 				(void) fprintf(stderr,
522 				    gettext("%s: Unexpected error while "
523 				    "looking up zone %ul: %s.\n"),
524 				    cmdname, zones[i], strerror(errno));
525 			}
526 
527 			continue;
528 		}
529 		pid = fork();
530 		if (pid < 0) {
531 			(void) fprintf(stderr,
532 			    gettext("%s: Zone \"%s\" could not be"
533 			    " halted (could not fork(): %s).\n"),
534 			    cmdname, zname, strerror(errno));
535 			continue;
536 		}
537 		if (pid == 0) {
538 			(void) execl(ZONEADM_PROG, ZONEADM_PROG,
539 			    "-z", zname, "halt", NULL);
540 			(void) fprintf(stderr,
541 			    gettext("%s: Zone \"%s\" could not be halted"
542 			    " (cannot exec(" ZONEADM_PROG "): %s).\n"),
543 			    cmdname, zname, strerror(errno));
544 			exit(0);
545 		}
546 	}
547 
548 	return (1);
549 }
550 
551 /*
552  * This function tries to wait for all non-global zones to go away.
553  * It will timeout if no progress is made for 5 seconds, or a total of
554  * 30 seconds elapses.
555  */
556 
557 static void
558 check_zones_haltedness()
559 {
560 	int t = 0, t_prog = 0;
561 	size_t nz = 0, last_nz;
562 
563 	do {
564 		last_nz = nz;
565 		(void) zone_list(NULL, &nz);
566 		if (nz == 1)
567 			return;
568 
569 		(void) sleep(1);
570 
571 		if (last_nz > nz)
572 			t_prog = 0;
573 
574 		t++;
575 		t_prog++;
576 
577 		if (t == 10) {
578 			if (nz == 2) {
579 				(void) fprintf(stderr,
580 				    gettext("%s: Still waiting for 1 zone to "
581 				    "halt. Will wait up to 20 seconds.\n"),
582 				    cmdname);
583 			} else {
584 				(void) fprintf(stderr,
585 				    gettext("%s: Still waiting for %i zones "
586 				    "to halt. Will wait up to 20 seconds.\n"),
587 				    cmdname, nz - 1);
588 			}
589 		}
590 
591 	} while ((t < 30) && (t_prog < 5));
592 }
593 
594 
595 /*
596  * Validate that this is a root disk or dataset
597  * Returns 0 if it is a root disk or dataset;
598  * returns 1 if it is a disk argument or dataset, but not valid or not root;
599  * returns -1 if it is not a valid argument or a disk argument.
600  */
601 static int
602 validate_disk(char *arg, char *mountpoint)
603 {
604 	static char root_dev_path[] = "/dev/dsk";
605 	char kernpath[MAXPATHLEN];
606 	struct stat64 statbuf;
607 	int rc = 0;
608 
609 	if (strlen(arg) > MAXPATHLEN) {
610 		(void) fprintf(stderr,
611 		    gettext("%s: Argument is too long\n"), cmdname);
612 		return (-1);
613 	}
614 
615 	bcopy(FASTBOOT_MOUNTPOINT, mountpoint, sizeof (FASTBOOT_MOUNTPOINT));
616 
617 	if (strstr(arg, mountpoint) == NULL) {
618 		/*
619 		 * Do a force umount just in case some other filesystem has
620 		 * been mounted there.
621 		 */
622 		(void) umount2(mountpoint, MS_FORCE);
623 	}
624 
625 	/* Create the directory if it doesn't already exist */
626 	if (lstat64(mountpoint, &statbuf) != 0) {
627 		if (mkdirp(mountpoint, 0755) != 0) {
628 			(void) fprintf(stderr,
629 			    gettext("Failed to create mountpoint %s\n"),
630 			    mountpoint);
631 			return (-1);
632 		}
633 	}
634 
635 	if (strncmp(arg, root_dev_path, strlen(root_dev_path)) == 0) {
636 		/* ufs root disk argument */
637 		rc = validate_ufs_disk(arg, mountpoint);
638 	} else {
639 		/* zfs root pool argument */
640 		rc = validate_zfs_pool(arg, mountpoint);
641 	}
642 
643 	if (rc != 0)
644 		return (rc);
645 
646 	/*
647 	 * Check for the usual case: 64-bit kernel
648 	 */
649 	(void) snprintf(kernpath, MAXPATHLEN,
650 	    "%s/platform/i86pc/kernel/amd64/unix", mountpoint);
651 	if (stat64(kernpath, &statbuf) == 0)
652 		return (0);
653 
654 	/*
655 	 * We no longer build 32-bit kernel but in a case we are trying to boot
656 	 * some ancient filesystem with 32-bit only kernel we should be able to
657 	 * proceed too
658 	 */
659 	(void) snprintf(kernpath, MAXPATHLEN, "%s/platform/i86pc/kernel/unix",
660 	    mountpoint);
661 
662 	if (stat64(kernpath, &statbuf) != 0) {
663 		(void) fprintf(stderr,
664 		    gettext("%s: %s is not a root disk or dataset\n"),
665 		    cmdname, arg);
666 		return (1);
667 	}
668 
669 	return (0);
670 }
671 
672 
673 static int
674 validate_ufs_disk(char *arg, char *mountpoint)
675 {
676 	struct ufs_args	ufs_args = { 0 };
677 	char mntopts[MNT_LINE_MAX] = MNTOPT_LARGEFILES;
678 
679 	/* perform the mount */
680 	ufs_args.flags = UFSMNT_LARGEFILES;
681 	if (mount(arg, mountpoint, MS_DATA|MS_OPTIONSTR,
682 	    MNTTYPE_UFS, &ufs_args, sizeof (ufs_args),
683 	    mntopts, sizeof (mntopts)) != 0) {
684 		perror(cmdname);
685 		(void) fprintf(stderr,
686 		    gettext("%s: Failed to mount %s\n"), cmdname, arg);
687 		return (-1);
688 	}
689 
690 	return (0);
691 }
692 
693 static int
694 validate_zfs_pool(char *arg, char *mountpoint)
695 {
696 	zfs_handle_t *zhp = NULL;
697 	char mntopts[MNT_LINE_MAX] = { '\0' };
698 	int rc = 0;
699 
700 	if ((g_zfs = libzfs_init()) == NULL) {
701 		(void) fprintf(stderr, gettext("Internal error: failed to "
702 		    "initialize ZFS library\n"));
703 		return (-1);
704 	}
705 
706 	/* Try to open the dataset */
707 	if ((zhp = zfs_open(g_zfs, arg,
708 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_DATASET)) == NULL)
709 		return (-1);
710 
711 	/* perform the mount */
712 	if (mount(zfs_get_name(zhp), mountpoint, MS_DATA|MS_OPTIONSTR|MS_RDONLY,
713 	    MNTTYPE_ZFS, NULL, 0, mntopts, sizeof (mntopts)) != 0) {
714 		perror(cmdname);
715 		(void) fprintf(stderr,
716 		    gettext("%s: Failed to mount %s\n"), cmdname, arg);
717 		rc = -1;
718 	}
719 
720 validate_zfs_err_out:
721 	if (zhp != NULL)
722 		zfs_close(zhp);
723 
724 	libzfs_fini(g_zfs);
725 	return (rc);
726 }
727 
728 /*
729  * Return 0 if not zfs, or is zfs and have successfully constructed the
730  * boot argument; returns non-zero otherwise.
731  * At successful completion fpth contains pointer where mount point ends.
732  * NOTE: arg is supposed to be the resolved path
733  */
734 static int
735 get_zfs_bootfs_arg(const char *arg, const char ** fpth, int *is_zfs,
736     char *bootfs_arg)
737 {
738 	zfs_handle_t *zhp = NULL;
739 	zpool_handle_t *zpoolp = NULL;
740 	FILE *mtabp = NULL;
741 	struct mnttab mnt;
742 	char *poolname = NULL;
743 	char physpath[MAXPATHLEN];
744 	char mntsp[ZFS_MAX_DATASET_NAME_LEN];
745 	char bootfs[ZFS_MAX_DATASET_NAME_LEN];
746 	int rc = 0;
747 	size_t mntlen = 0;
748 	size_t msz;
749 	static char fmt[] = "-B zfs-bootfs=%s,bootpath=\"%s\"";
750 
751 	*fpth = arg;
752 	*is_zfs = 0;
753 
754 	bzero(physpath, sizeof (physpath));
755 	bzero(bootfs, sizeof (bootfs));
756 
757 	if ((mtabp = fopen(MNTTAB, "r")) == NULL) {
758 		return (-1);
759 	}
760 
761 	while (getmntent(mtabp, &mnt) == 0) {
762 		if (strstr(arg, mnt.mnt_mountp) == arg &&
763 		    (msz = strlen(mnt.mnt_mountp)) > mntlen) {
764 			mntlen = msz;
765 			*is_zfs = strcmp(MNTTYPE_ZFS, mnt.mnt_fstype) == 0;
766 			(void) strlcpy(mntsp, mnt.mnt_special, sizeof (mntsp));
767 		}
768 	}
769 
770 	(void) fclose(mtabp);
771 
772 	if (mntlen > 1)
773 		*fpth += mntlen;
774 
775 	if (!*is_zfs)
776 		return (0);
777 
778 	if ((g_zfs = libzfs_init()) == NULL)
779 		return (-1);
780 
781 	/* Try to open the dataset */
782 	if ((zhp = zfs_open(g_zfs, mntsp,
783 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_DATASET)) == NULL) {
784 		(void) fprintf(stderr, gettext("Cannot open %s\n"), mntsp);
785 		rc = -1;
786 		goto validate_zfs_err_out;
787 	}
788 
789 	(void) strlcpy(bootfs, mntsp, sizeof (bootfs));
790 
791 	if ((poolname = strtok(mntsp, "/")) == NULL) {
792 		rc = -1;
793 		goto validate_zfs_err_out;
794 	}
795 
796 	if ((zpoolp = zpool_open(g_zfs, poolname)) == NULL) {
797 		(void) fprintf(stderr, gettext("Cannot open %s\n"), poolname);
798 		rc = -1;
799 		goto validate_zfs_err_out;
800 	}
801 
802 	if (zpool_get_physpath(zpoolp, physpath, sizeof (physpath)) != 0) {
803 		(void) fprintf(stderr, gettext("Cannot find phys_path\n"));
804 		rc = -1;
805 		goto validate_zfs_err_out;
806 	}
807 
808 	/*
809 	 * For the mirror physpath would contain the list of all
810 	 * bootable devices, pick up the first one.
811 	 */
812 	(void) strtok(physpath, " ");
813 	if (snprintf(bootfs_arg, BOOTARGS_MAX, fmt, bootfs, physpath) >=
814 	    BOOTARGS_MAX) {
815 		rc = E2BIG;
816 		(void) fprintf(stderr,
817 		    gettext("Boot arguments are too long\n"));
818 	}
819 
820 validate_zfs_err_out:
821 	if (zhp != NULL)
822 		zfs_close(zhp);
823 
824 	if (zpoolp != NULL)
825 		zpool_close(zpoolp);
826 
827 	libzfs_fini(g_zfs);
828 	return (rc);
829 }
830 
831 /*
832  * Validate that the file exists, and is an ELF file.
833  * Returns 0 on success, -1 on failure.
834  */
835 static int
836 validate_unix(char *arg, int *mplen, int *is_zfs, char *bootfs_arg)
837 {
838 	const char *location;
839 	int class, format;
840 	unsigned char ident[EI_NIDENT];
841 	char physpath[MAXPATHLEN];
842 	int elffd = -1;
843 	size_t	sz;
844 
845 	if ((sz = resolvepath(arg, physpath, sizeof (physpath) - 1)) ==
846 	    (size_t)-1) {
847 		(void) fprintf(stderr,
848 		    gettext("Cannot resolve path for %s: %s\n"),
849 		    arg, strerror(errno));
850 		return (-1);
851 	}
852 	(void) strlcpy(arg, physpath, sz + 1);
853 
854 	if (strlen(arg) > MAXPATHLEN) {
855 		(void) fprintf(stderr,
856 		    gettext("%s: New kernel name is too long\n"), cmdname);
857 		return (-1);
858 	}
859 
860 	if (strncmp(basename(arg), "unix", 4) != 0) {
861 		(void) fprintf(stderr,
862 		    gettext("%s: %s: Kernel name must be unix\n"),
863 		    cmdname, arg);
864 		return (-1);
865 	}
866 
867 	if (get_zfs_bootfs_arg(arg, &location, is_zfs, bootfs_arg) != 0)
868 		goto err_out;
869 
870 	*mplen = location - arg;
871 
872 	if (strstr(location, "/boot/platform") == location) {
873 		/*
874 		 * Rebooting to failsafe.
875 		 * Clear bootfs_arg and is_zfs flag.
876 		 */
877 		bootfs_arg[0] = 0;
878 		*is_zfs = 0;
879 	} else if (strstr(location, "/platform") != location) {
880 		(void) fprintf(stderr,
881 		    gettext("%s: %s: No /platform in file name\n"),
882 		    cmdname, arg);
883 		goto err_out;
884 	}
885 
886 	if ((elffd = open64(arg, O_RDONLY)) < 0 ||
887 	    (pread64(elffd, ident, EI_NIDENT, 0) != EI_NIDENT)) {
888 		(void) fprintf(stderr, "%s: %s: %s\n",
889 		    cmdname, arg, strerror(errno));
890 		goto err_out;
891 	}
892 
893 	class = ident[EI_CLASS];
894 
895 	if ((class != ELFCLASS32 && class != ELFCLASS64) ||
896 	    memcmp(&ident[EI_MAG0], ELFMAG, 4) != 0) {
897 		(void) fprintf(stderr,
898 		    gettext("%s: %s: Not a valid ELF file\n"), cmdname, arg);
899 		goto err_out;
900 	}
901 
902 	format = ident[EI_DATA];
903 
904 	if (format != CUR_ELFDATA) {
905 		(void) fprintf(stderr, gettext("%s: %s: Invalid data format\n"),
906 		    cmdname, arg);
907 		goto err_out;
908 	}
909 
910 	return (0);
911 
912 err_out:
913 	if (elffd >= 0) {
914 		(void) close(elffd);
915 		elffd = -1;
916 	}
917 	return (-1);
918 }
919 
920 static int
921 halt_exec(const char *path, ...)
922 {
923 	pid_t		pid;
924 	int		i;
925 	int		st;
926 	const char	*arg;
927 	va_list	vp;
928 	const char	*argv[256];
929 
930 	if ((pid = fork()) == -1) {
931 		return (errno);
932 	} else if (pid == 0) {
933 		(void) fclose(stdout);
934 		(void) fclose(stderr);
935 
936 		argv[0] = path;
937 		i = 1;
938 
939 		va_start(vp, path);
940 
941 		do {
942 			arg = va_arg(vp, const char *);
943 			argv[i] = arg;
944 		} while (arg != NULL &&
945 		    ++i != sizeof (argv) / sizeof (argv[0]));
946 
947 		va_end(vp);
948 
949 		(void) execve(path, (char * const *)argv, NULL);
950 		(void) fprintf(stderr, gettext("Cannot execute %s: %s\n"),
951 		    path, strerror(errno));
952 		exit(-1);
953 	} else {
954 		if (waitpid(pid, &st, 0) == pid &&
955 		    !WIFSIGNALED(st) && WIFEXITED(st))
956 			st = WEXITSTATUS(st);
957 		else
958 			st = -1;
959 	}
960 	return (st);
961 }
962 
963 /*
964  * Mount the specified BE.
965  *
966  * Upon success returns zero and copies bename string to mountpoint[]
967  */
968 static int
969 fastboot_bename(const char *bename, char *mountpoint, size_t mpsz)
970 {
971 	int rc;
972 
973 	/*
974 	 * Attempt to unmount the BE first in case it's already mounted
975 	 * elsewhere.
976 	 */
977 	(void) halt_exec(BEADM_PROG, "umount", bename, NULL);
978 
979 	if ((rc = halt_exec(BEADM_PROG, "mount", bename, FASTBOOT_MOUNTPOINT,
980 	    NULL)) != 0)
981 		(void) fprintf(stderr,
982 		    gettext("%s: Unable to mount BE \"%s\" at %s\n"),
983 		    cmdname, bename, FASTBOOT_MOUNTPOINT);
984 	else
985 		(void) strlcpy(mountpoint, FASTBOOT_MOUNTPOINT, mpsz);
986 
987 	return (rc);
988 }
989 
990 /*
991  * Returns 0 on successful parsing of the arguments;
992  * returns EINVAL on parsing failures that should abort the reboot attempt;
993  * returns other error code to fall back to regular reboot.
994  */
995 static int
996 parse_fastboot_args(char *bootargs_buf, size_t buf_size,
997     int *is_dryrun, const char *bename)
998 {
999 	char mountpoint[MAXPATHLEN];
1000 	char bootargs_saved[BOOTARGS_MAX];
1001 	char bootargs_scratch[BOOTARGS_MAX];
1002 	char bootfs_arg[BOOTARGS_MAX];
1003 	char unixfile[BOOTARGS_MAX];
1004 	char *head, *newarg;
1005 	int buflen;		/* length of the bootargs_buf */
1006 	int mplen;		/* length of the mount point */
1007 	int rootlen = 0;	/* length of the root argument */
1008 	int unixlen = 0;	/* length of the unix argument */
1009 	int off = 0;		/* offset into the new boot argument */
1010 	int is_zfs = 0;
1011 	int rc = 0;
1012 
1013 	bzero(mountpoint, sizeof (mountpoint));
1014 
1015 	/*
1016 	 * If argc is not 0, buflen is length of the argument being passed in;
1017 	 * else it is 0 as bootargs_buf has been initialized to all 0's.
1018 	 */
1019 	buflen = strlen(bootargs_buf);
1020 
1021 	/* Save a copy of the original argument */
1022 	bcopy(bootargs_buf, bootargs_saved, buflen);
1023 	bzero(&bootargs_saved[buflen], sizeof (bootargs_saved) - buflen);
1024 
1025 	/* Save another copy to be used by strtok */
1026 	bcopy(bootargs_buf, bootargs_scratch, buflen);
1027 	bzero(&bootargs_scratch[buflen], sizeof (bootargs_scratch) - buflen);
1028 	head = &bootargs_scratch[0];
1029 
1030 	/* Get the first argument */
1031 	newarg = strtok(bootargs_scratch, " ");
1032 
1033 	/*
1034 	 * If this is a dry run request, verify that the drivers can handle
1035 	 * fast reboot.
1036 	 */
1037 	if (newarg && strncasecmp(newarg, "dryrun", strlen("dryrun")) == 0) {
1038 		*is_dryrun = 1;
1039 		(void) system("/usr/sbin/devfsadm");
1040 	}
1041 
1042 	/*
1043 	 * Always perform a dry run to identify all the drivers that
1044 	 * need to implement devo_reset().
1045 	 */
1046 	if (uadmin(A_SHUTDOWN, AD_FASTREBOOT_DRYRUN,
1047 	    (uintptr_t)bootargs_saved) != 0) {
1048 		(void) fprintf(stderr, gettext("%s: Not all drivers "
1049 		    "have implemented quiesce(9E)\n"
1050 		    "\tPlease see /var/adm/messages for drivers that haven't\n"
1051 		    "\timplemented quiesce(9E).\n"), cmdname);
1052 	} else if (*is_dryrun) {
1053 		(void) fprintf(stderr, gettext("%s: All drivers have "
1054 		    "implemented quiesce(9E)\n"), cmdname);
1055 	}
1056 
1057 	/* Return if it is a true dry run. */
1058 	if (*is_dryrun)
1059 		return (rc);
1060 
1061 #if defined(__i386)
1062 	/* Read boot args from GRUB menu */
1063 	if ((bootargs_buf[0] == 0 || isdigit(bootargs_buf[0])) &&
1064 	    bename == NULL) {
1065 		/*
1066 		 * If no boot arguments are given, or a GRUB menu entry
1067 		 * number is provided, process the GRUB menu.
1068 		 */
1069 		int entnum;
1070 		if (bootargs_buf[0] == 0)
1071 			entnum = GRUB_ENTRY_DEFAULT;
1072 		else {
1073 			errno = 0;
1074 			entnum = strtoul(bootargs_buf, NULL, 10);
1075 			rc = errno;
1076 		}
1077 
1078 		if (rc == 0 && (rc = grub_get_boot_args(&fbarg, NULL,
1079 		    entnum)) == 0) {
1080 			if (strlcpy(bootargs_buf, fbarg.gba_bootargs,
1081 			    buf_size) >= buf_size) {
1082 				grub_cleanup_boot_args(&fbarg);
1083 				bcopy(bootargs_saved, bootargs_buf, buf_size);
1084 				rc = E2BIG;
1085 			}
1086 		}
1087 		/* Failed to read GRUB menu, fall back to normal reboot */
1088 		if (rc != 0) {
1089 			(void) fprintf(stderr,
1090 			    gettext("%s: Failed to process GRUB menu "
1091 			    "entry for fast reboot.\n\t%s\n"),
1092 			    cmdname, grub_strerror(rc));
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	/* __i386 */
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 = NULL;
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(__i386)
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(__i386)
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(__i386)
1519 	/* set new default entry in the GRUB entry */
1520 	if (fbarg_entnum != GRUB_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	/* __i386 */
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 		int	start, end, delta;
1600 
1601 		(void) kill(-1, SIGTERM);
1602 		start = time(NULL);
1603 
1604 		if (zoneid == GLOBAL_ZONEID && !nosync)
1605 			do_archives_update(fast_reboot);
1606 
1607 		end = time(NULL);
1608 		delta = end - start;
1609 		if (delta < 5)
1610 			(void) sleep(5 - delta);
1611 	}
1612 
1613 	(void) signal(SIGINT, SIG_IGN);
1614 
1615 	if (!qflag && !nosync) {
1616 		struct utmpx wtmpx;
1617 
1618 		bzero(&wtmpx, sizeof (struct utmpx));
1619 		(void) strcpy(wtmpx.ut_line, "~");
1620 		(void) time(&wtmpx.ut_tv.tv_sec);
1621 
1622 		if (cmd == A_DUMP)
1623 			(void) strcpy(wtmpx.ut_name, "crash dump");
1624 		else
1625 			(void) strcpy(wtmpx.ut_name, "shutdown");
1626 
1627 		(void) updwtmpx(WTMPX_FILE, &wtmpx);
1628 		sync();
1629 	}
1630 
1631 	if (cmd == A_DUMP && nosync != 0)
1632 		(void) uadmin(A_DUMP, AD_NOSYNC, NULL);
1633 
1634 	if (fast_reboot)
1635 		fcn = AD_FASTREBOOT;
1636 
1637 	if (uadmin(cmd, fcn, mdep) == -1)
1638 		(void) fprintf(stderr, "%s: uadmin failed: %s\n",
1639 		    cmdname, strerror(errno));
1640 	else
1641 		(void) fprintf(stderr, "%s: uadmin unexpectedly returned 0\n",
1642 		    cmdname);
1643 
1644 	do {
1645 		r = remove(resetting);
1646 	} while (r != 0 && errno == EINTR);
1647 
1648 	if (r != 0 && errno != ENOENT)
1649 		(void) fprintf(stderr, gettext("%s: could not remove %s.\n"),
1650 		    cmdname, resetting);
1651 
1652 	if (direct_init(PCRUN) == -1) {
1653 		/*
1654 		 * TRANSLATION_NOTE
1655 		 * Don't translate the word "init"
1656 		 */
1657 		(void) fprintf(stderr,
1658 		    gettext("%s: can't resume init\n"), cmdname);
1659 	}
1660 
1661 	continue_restarters();
1662 
1663 	if (get_initpid() != -1)
1664 		/* tell init to restate current level */
1665 		(void) kill(get_initpid(), SIGHUP);
1666 
1667 fail:
1668 	if (fcn == AD_BOOT)
1669 		(void) audit_reboot_fail();
1670 	else
1671 		(void) audit_halt_fail();
1672 
1673 	if (fast_reboot == 1) {
1674 		if (bename) {
1675 			(void) halt_exec(BEADM_PROG, "umount", bename, NULL);
1676 
1677 		} else if (strlen(fastboot_mounted) != 0) {
1678 			(void) umount(fastboot_mounted);
1679 #if defined(__i386)
1680 		} else if (fbarg_used != NULL) {
1681 			grub_cleanup_boot_args(fbarg_used);
1682 #endif	/* __i386 */
1683 		}
1684 	}
1685 
1686 	return (1);
1687 }
1688