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