xref: /titanic_44/usr/src/cmd/fs.d/umount.c (revision bf56214c0556fa6864189c826d39dbe156bb22a0)
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 2007 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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 #include	<stdio.h>
33 #include	<stdio_ext.h>
34 #include	<limits.h>
35 #include	<unistd.h>
36 #include	<stdlib.h>
37 #include	<string.h>
38 #include	<sys/signal.h>
39 #include	<sys/mnttab.h>
40 #include	<errno.h>
41 #include	<sys/types.h>
42 #include	<sys/stat.h>
43 #include	<sys/param.h>
44 #include	<sys/wait.h>
45 #include	<sys/vfstab.h>
46 #include	<sys/fcntl.h>
47 #include	<sys/resource.h>
48 #include	<sys/mntent.h>
49 #include	<sys/ctfs.h>
50 #include	<locale.h>
51 #include	<stdarg.h>
52 #include	<sys/mount.h>
53 #include	<sys/objfs.h>
54 #include	"fslib.h"
55 #include	<sharefs/share.h>
56 
57 #define	FS_PATH		"/usr/lib/fs"
58 #define	ALT_PATH	"/etc/fs"
59 #define	FULLPATH_MAX	32
60 #define	FSTYPE_MAX	8
61 #define	ARGV_MAX	16
62 
63 int	aflg, oflg, Vflg, dashflg, dflg, fflg;
64 
65 extern void	rpterr(), usage(), mnterror();
66 
67 extern	char	*optarg;	/* used by getopt */
68 extern	int	optind, opterr;
69 
70 static char	*myname;
71 char	fs_path[] = FS_PATH;
72 char	alt_path[] = ALT_PATH;
73 char	mnttab[MAXPATHLEN + 1];
74 char	*oarg, *farg;
75 int	maxrun, nrun;
76 int	no_mnttab;
77 int	lofscnt;		/* presence of lofs prohibits parallel */
78 				/* umounting */
79 int	exitcode;
80 char	resolve[MAXPATHLEN];
81 static  char ibuf[BUFSIZ];
82 
83 /*
84  * Currently, mounting cachefs's simultaneous uncovers various problems.
85  * For the short term, we serialize cachefs activity while we fix
86  * these cachefs bugs.
87  */
88 #define	CACHEFS_BUG
89 #ifdef	CACHEFS_BUG
90 #include	<sys/fs/cachefs_fs.h>	/* for BACKMNT_NAME */
91 int	cachefs_running;	/* parallel cachefs not supported yet */
92 #endif
93 
94 /*
95  * The basic mount struct that describes an mnttab entry.
96  * It is used both in an array and as a linked list elem.
97  */
98 
99 typedef struct mountent {
100 	struct mnttab	ment;		/* the mnttab data */
101 	int		mlevel;		/* mount level of the mount pt */
102 	pid_t		pid;		/* the pid of this mount process */
103 #define	RDPIPE		0
104 #define	WRPIPE		1
105 	int		sopipe[2];	/* pipe attached to child's stdout */
106 	int		sepipe[2];	/* pipe attached to child's stderr */
107 	struct mountent *link;		/* used when in linked list */
108 } mountent_t;
109 
110 static mountent_t	*mntll;		/* head of global linked list of */
111 					/* mountents */
112 int			listlength;	/* # of elems in this list */
113 
114 /*
115  * If the automatic flag (-a) is given and mount points are not specified
116  * on the command line, then do not attempt to umount these.  These
117  * generally need to be kept mounted until system shutdown.
118  */
119 static const char   *keeplist[] = {
120 	"/",
121 	"/dev",
122 	"/dev/fd",
123 	"/devices",
124 	"/etc/mnttab",
125 	"/etc/svc/volatile",
126 	"/lib",
127 	"/proc",
128 	"/sbin",
129 	CTFS_ROOT,
130 	OBJFS_ROOT,
131 	"/tmp",
132 	"/usr",
133 	"/var",
134 	"/var/adm",
135 	"/var/run",
136 	SHARETAB,
137 	NULL
138 };
139 
140 static void	nomem();
141 static void	doexec(struct mnttab *);
142 static int	setup_iopipe(mountent_t *);
143 static void	setup_output(mountent_t *);
144 static void	doio(mountent_t *);
145 static void	do_umounts(mountent_t **);
146 static int	dowait();
147 static int	parumount();
148 static int	mcompar(const void *, const void *);
149 static void	cleanup(int);
150 
151 static mountent_t	**make_mntarray(char **, int);
152 static mountent_t	*getmntall();
153 static mountent_t 	*new_mountent(struct mnttab *);
154 static mountent_t	*getmntlast(mountent_t *, char *, char *);
155 
156 int
157 main(int argc, char **argv)
158 {
159 	int 	cc;
160 	struct mnttab  mget;
161 	char 	*mname, *is_special;
162 	int	fscnt;
163 	mountent_t	*mp;
164 
165 	(void) setlocale(LC_ALL, "");
166 
167 #if !defined(TEXT_DOMAIN)
168 #define	TEXT_DOMAIN "SYS_TEST"
169 #endif
170 	(void) textdomain(TEXT_DOMAIN);
171 
172 	myname = strrchr(argv[0], '/');
173 	if (myname)
174 		myname++;
175 	else
176 		myname = argv[0];
177 
178 	/*
179 	 * Process the args.
180 	 * "-d" for compatibility
181 	 */
182 	while ((cc = getopt(argc, argv, "ado:Vf?")) != -1)
183 		switch (cc) {
184 		case 'a':
185 			aflg++;
186 			break;
187 #ifdef DEBUG
188 		case 'd':
189 			dflg++;
190 			break;
191 #endif
192 
193 		case '?':
194 			usage();
195 			break;
196 		case 'o':
197 			if (oflg)
198 				usage();
199 			else {
200 				oflg++;
201 				oarg = optarg;
202 			}
203 			break;
204 		case 'f':
205 			fflg++;
206 			break;
207 		case 'V':
208 			if (Vflg)
209 				usage();
210 			else
211 				Vflg++;
212 			break;
213 		default:
214 			usage();
215 			break;
216 		}
217 
218 	fscnt = argc - optind;
219 	if (!aflg && fscnt != 1)
220 		usage();
221 
222 	/* copy '--' to specific */
223 	if (strcmp(argv[optind-1], "--") == 0)
224 		dashflg++;
225 
226 	/*
227 	 * mnttab may be a symlink to a file in another file system.
228 	 * This happens during install when / is mounted read-only
229 	 * and /etc/mnttab is symlinked to a file in /tmp.
230 	 * If this is the case, we need to follow the symlink to the
231 	 * read-write file itself so that the subsequent mnttab.temp
232 	 * open and rename will work.
233 	 */
234 	if (realpath(MNTTAB, mnttab) == NULL) {
235 		strcpy(mnttab, MNTTAB);
236 	}
237 
238 	/*
239 	 * bugid 1205242
240 	 * call the realpath() here, so that if the user is
241 	 * trying to umount an autofs directory, the directory
242 	 * is forced to mount.
243 	 */
244 
245 	mname = argv[optind];
246 	is_special = realpath(mname, resolve);
247 
248 	/*
249 	 * Read the whole mnttab into memory.
250 	 */
251 	mntll = getmntall();
252 
253 	if (aflg && fscnt != 1)
254 		exit(parumount(argv + optind, fscnt));
255 
256 	aflg = 0;
257 
258 	mntnull(&mget);
259 	if (listlength == 0) {
260 		fprintf(stderr, gettext(
261 			"%s: warning: no entries found in %s\n"),
262 				myname, mnttab);
263 		mget.mnt_mountp = mname;	/* assume mount point */
264 		no_mnttab++;
265 		doexec(&mget);
266 		exit(0);
267 	}
268 
269 	mp = NULL;
270 
271 	/*
272 	 * if realpath fails, it can't be a mount point, so we'll
273 	 * go straight to the code that treats the arg as a special.
274 	 * if realpath succeeds, it could be a special or a mount point;
275 	 * we'll start by assuming it's a mount point, and if it's not,
276 	 * try to treat it as a special.
277 	 */
278 	if (is_special != NULL) {
279 		/*
280 		 * if this succeeds,
281 		 * we'll have the appropriate record; if it fails
282 		 * we'll assume the arg is a special of some sort
283 		 */
284 		mp = getmntlast(mntll, NULL, resolve);
285 	}
286 	/*
287 	 * Since stackable mount is allowed (RFE 2001535),
288 	 * we will un-mount the last entry in the MNTTAB that matches.
289 	 */
290 	if (mp == NULL) {
291 		/*
292 		 * Perhaps there is a bogus mnttab entry that
293 		 * can't be resolved:
294 		 */
295 		if ((mp = getmntlast(mntll, NULL, mname)) == NULL)
296 			/*
297 			 * assume it's a device (special) now
298 			 */
299 			mp = getmntlast(mntll, mname, NULL);
300 		if (mp) {
301 			/*
302 			 * Found it.
303 			 * This is a device. Now we want to know if
304 			 * it stackmounted on by something else.
305 			 * The original fix for bug 1103850 has a
306 			 * problem with lockfs (bug 1119731). This
307 			 * is a revised method.
308 			 */
309 			mountent_t *lmp;
310 			lmp = getmntlast(mntll, NULL, mp->ment.mnt_mountp);
311 
312 			if (lmp && strcmp(lmp->ment.mnt_special,
313 					mp->ment.mnt_special)) {
314 				errno = EBUSY;
315 				rpterr(mname);
316 				exit(1);
317 			}
318 		} else {
319 			fprintf(stderr, gettext(
320 				"%s: warning: %s not in mnttab\n"),
321 				myname, mname);
322 			if (Vflg)
323 				exit(1);
324 				/*
325 				 * same error as mount -V
326 				 * would give for unknown
327 				 * mount point
328 				 */
329 			mget.mnt_special = mget.mnt_mountp = mname;
330 		}
331 	}
332 
333 	if (mp)
334 		doexec(&mp->ment);
335 	else
336 		doexec(&mget);
337 
338 	return (0);
339 }
340 
341 void
342 doexec(struct mnttab *ment)
343 {
344 	int 	ret;
345 
346 #ifdef DEBUG
347 	if (dflg)
348 		fprintf(stderr, "%d: umounting %s\n",
349 			getpid(), ment->mnt_mountp);
350 #endif
351 
352 	/* try to exec the dependent portion */
353 	if ((ment->mnt_fstype != NULL) || Vflg) {
354 		char	full_path[FULLPATH_MAX];
355 		char	alter_path[FULLPATH_MAX];
356 		char	*newargv[ARGV_MAX];
357 		int 	ii;
358 
359 		if (strlen(ment->mnt_fstype) > (size_t)FSTYPE_MAX) {
360 			fprintf(stderr, gettext(
361 				"%s: FSType %s exceeds %d characters\n"),
362 				myname, ment->mnt_fstype, FSTYPE_MAX);
363 			exit(1);
364 		}
365 
366 		/* build the full pathname of the fstype dependent command. */
367 		sprintf(full_path, "%s/%s/%s", fs_path, ment->mnt_fstype,
368 					myname);
369 		sprintf(alter_path, "%s/%s/%s", alt_path, ment->mnt_fstype,
370 					myname);
371 
372 		/*
373 		 * create the new arg list, and end the list with a
374 		 * null pointer
375 		 */
376 		ii = 2;
377 		if (oflg) {
378 			newargv[ii++] = "-o";
379 			newargv[ii++] = oarg;
380 		}
381 		if (dashflg) {
382 			newargv[ii++] = "--";
383 		}
384 		if (fflg) {
385 			newargv[ii++] = "-f";
386 		}
387 		newargv[ii++] = (ment->mnt_mountp)
388 				? ment->mnt_mountp : ment->mnt_special;
389 		newargv[ii] = NULL;
390 
391 		/* set the new argv[0] to the filename */
392 		newargv[1] = myname;
393 
394 		if (Vflg) {
395 			printf("%s", myname);
396 			for (ii = 2; newargv[ii]; ii++)
397 				printf(" %s", newargv[ii]);
398 			printf("\n");
399 			fflush(stdout);
400 			exit(0);
401 		}
402 
403 		/* Try to exec the fstype dependent umount. */
404 		execv(full_path, &newargv[1]);
405 		if (errno == ENOEXEC) {
406 			newargv[0] = "sh";
407 			newargv[1] = full_path;
408 			execv("/sbin/sh", &newargv[0]);
409 		}
410 		newargv[1] = myname;
411 		execv(alter_path, &newargv[1]);
412 		if (errno == ENOEXEC) {
413 			newargv[0] = "sh";
414 			newargv[1] = alter_path;
415 			execv("/sbin/sh", &newargv[0]);
416 		}
417 		/* exec failed */
418 		if (errno != ENOENT) {
419 			fprintf(stderr, gettext("umount: cannot execute %s\n"),
420 					full_path);
421 			exit(1);
422 		}
423 	}
424 	/*
425 	 * No fstype independent executable then.  We'll go generic
426 	 * from here.
427 	 */
428 
429 	/* don't use -o with generic */
430 	if (oflg) {
431 		fprintf(stderr, gettext(
432 	"%s: %s specific umount does not exist; -o suboption ignored\n"),
433 		myname, ment->mnt_fstype ? ment->mnt_fstype : "<null>");
434 	}
435 
436 	signal(SIGHUP,  SIG_IGN);
437 	signal(SIGQUIT, SIG_IGN);
438 	signal(SIGINT,  SIG_IGN);
439 	/*
440 	 * Try to umount the mountpoint.
441 	 * If that fails, try the corresponding special.
442 	 * (This ordering is necessary for nfs umounts.)
443 	 * (for remote resources:  if the first umount returns EBUSY
444 	 * don't call umount again - umount() with a resource name
445 	 * will return a misleading error to the user
446 	 */
447 	if (fflg) {
448 		if (((ret = umount2(ment->mnt_mountp, MS_FORCE)) < 0) &&
449 				(errno != EBUSY && errno != ENOTSUP &&
450 				errno != EPERM))
451 			ret = umount2(ment->mnt_special, MS_FORCE);
452 	} else {
453 		if (((ret = umount2(ment->mnt_mountp, 0)) < 0) &&
454 				(errno != EBUSY) && (errno != EPERM))
455 			ret = umount2(ment->mnt_special, 0);
456 	}
457 
458 	if (ret < 0) {
459 		rpterr(ment->mnt_mountp);
460 		if (errno != EINVAL && errno != EFAULT)
461 			exit(1);
462 
463 		exitcode = 1;
464 	}
465 
466 	exit(exitcode);
467 }
468 
469 void
470 rpterr(char *sp)
471 {
472 	switch (errno) {
473 	case EPERM:
474 		fprintf(stderr, gettext("%s: permission denied\n"), myname);
475 		break;
476 	case ENXIO:
477 		fprintf(stderr, gettext("%s: %s no device\n"), myname, sp);
478 		break;
479 	case ENOENT:
480 		fprintf(stderr,
481 			gettext("%s: %s no such file or directory\n"),
482 			myname, sp);
483 		break;
484 	case EINVAL:
485 		fprintf(stderr, gettext("%s: %s not mounted\n"), myname, sp);
486 		break;
487 	case EBUSY:
488 		fprintf(stderr, gettext("%s: %s busy\n"), myname, sp);
489 		break;
490 	case ENOTBLK:
491 		fprintf(stderr,
492 			gettext("%s: %s block device required\n"), myname, sp);
493 		break;
494 	case ECOMM:
495 		fprintf(stderr,
496 			gettext("%s: warning: broken link detected\n"), myname);
497 		break;
498 	default:
499 		perror(myname);
500 		fprintf(stderr, gettext("%s: cannot unmount %s\n"), myname, sp);
501 	}
502 }
503 
504 void
505 usage(void)
506 {
507 	fprintf(stderr, gettext(
508 "Usage:\n%s [-f] [-V] [-o specific_options] {special | mount-point}\n"),
509 		myname);
510 	fprintf(stderr, gettext(
511 "%s -a [-f] [-V] [-o specific_options] [mount_point ...]\n"), myname);
512 	exit(1);
513 }
514 
515 void
516 mnterror(int flag)
517 {
518 	switch (flag) {
519 	case MNT_TOOLONG:
520 		fprintf(stderr,
521 			gettext("%s: line in mnttab exceeds %d characters\n"),
522 			myname, MNT_LINE_MAX-2);
523 		break;
524 	case MNT_TOOFEW:
525 		fprintf(stderr,
526 			gettext("%s: line in mnttab has too few entries\n"),
527 			myname);
528 		break;
529 	default:
530 		break;
531 	}
532 }
533 
534 /*
535  * Search the mlist linked list for the
536  * first match of specp or mntp.  The list is expected to be in reverse
537  * order of /etc/mnttab.
538  * If both are specified, then both have to match.
539  * Returns the (mountent_t *) of the match, otherwise returns NULL.
540  */
541 mountent_t *
542 getmntlast(mountent_t *mlist, char *specp, char *mntp)
543 {
544 	int		mfound, sfound;
545 
546 	for (/* */; mlist; mlist = mlist->link) {
547 		mfound = sfound = 0;
548 		if (mntp && (strcmp(mlist->ment.mnt_mountp, mntp) == 0)) {
549 			if (specp == NULL)
550 				return (mlist);
551 			mfound++;
552 		}
553 		if (specp && (strcmp(mlist->ment.mnt_special, specp) == 0)) {
554 			if (mntp == NULL)
555 				return (mlist);
556 			sfound++;
557 		}
558 		if (mfound && sfound)
559 			return (mlist);
560 	}
561 	return (NULL);
562 }
563 
564 
565 
566 /*
567  * Perform the parallel version of umount.  Returns 0 if no errors occurred,
568  * non zero otherwise.
569  */
570 int
571 parumount(char **mntlist, int count)
572 {
573 	int 		maxfd = OPEN_MAX;
574 	struct rlimit 	rl;
575 	mountent_t	**mntarray, **ml, *mp;
576 
577 	/*
578 	 * If no mount points are specified and none were found in mnttab,
579 	 * then end it all here.
580 	 */
581 	if (count == 0 && mntll == NULL)
582 		return (0);
583 
584 	/*
585 	 * This is the process scaling section.  After running a series
586 	 * of tests based on the number of simultaneous processes and
587 	 * processors available, optimum performance was achieved near or
588 	 * at (PROCN * 2).
589 	 */
590 	if ((maxrun = sysconf(_SC_NPROCESSORS_ONLN)) == -1)
591 		maxrun = 4;
592 	else
593 		maxrun = maxrun * 2 + 1;
594 
595 	if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
596 		rl.rlim_cur = rl.rlim_max;
597 		if (setrlimit(RLIMIT_NOFILE, &rl) == 0)
598 			maxfd = (int)rl.rlim_cur;
599 		(void) enable_extended_FILE_stdio(-1, -1);
600 	}
601 
602 	/*
603 	 * The parent needs to maintain 3 of its own fd's, plus 2 for
604 	 * each child (the stdout and stderr pipes).
605 	 */
606 	maxfd = (maxfd / 2) - 6;	/* 6 takes care of temporary  */
607 					/* periods of open fds */
608 	if (maxfd < maxrun)
609 		maxrun = maxfd;
610 	if (maxrun < 4)
611 		maxrun = 4;		/* sanity check */
612 
613 	mntarray = make_mntarray(mntlist, count);
614 
615 	if (listlength == 0) {
616 		if (count == 0)		/* not an error, just none found */
617 			return (0);
618 		fprintf(stderr, gettext("%s: no valid entries found in %s\n"),
619 				myname, mnttab);
620 		return (1);
621 	}
622 
623 	/*
624 	 * Sort the entries based on their mount level only if lofs's are
625 	 * not present.
626 	 */
627 	if (lofscnt == 0) {
628 		qsort((void *)mntarray, listlength, sizeof (mountent_t *),
629 			mcompar);
630 		/*
631 		 * If we do not detect a lofs by now, we never will.
632 		 */
633 		lofscnt = -1;
634 	}
635 	/*
636 	 * Now link them up so that a given pid is easier to find when
637 	 * we go to clean up after they are done.
638 	 */
639 	mntll = mntarray[0];
640 	for (ml = mntarray; mp = *ml; /* */)
641 		mp->link = *++ml;
642 
643 	/*
644 	 * Try to handle interrupts in a reasonable way.
645 	 */
646 	sigset(SIGHUP, cleanup);
647 	sigset(SIGQUIT, cleanup);
648 	sigset(SIGINT, cleanup);
649 
650 	do_umounts(mntarray);	/* do the umounts */
651 	return (exitcode);
652 }
653 
654 /*
655  * Returns a mountent_t array based on mntlist.  If mntlist is NULL, then
656  * it returns all mnttab entries with a few exceptions.  Sets the global
657  * variable listlength to the number of entries in the array.
658  */
659 mountent_t **
660 make_mntarray(char **mntlist, int count)
661 {
662 	mountent_t 	*mp, **mpp;
663 	int 		ndx;
664 	char		*cp;
665 
666 	if (count > 0)
667 		listlength = count;
668 
669 	mpp = (mountent_t **)malloc(sizeof (*mp) * (listlength + 1));
670 	if (mpp == NULL)
671 		nomem();
672 
673 	if (count == 0) {
674 		if (mntll == NULL) {	/* no entries? */
675 			listlength = 0;
676 			return (NULL);
677 		}
678 		/*
679 		 * No mount list specified: take all mnttab mount points
680 		 * except for a few cases.
681 		 */
682 		for (ndx = 0, mp = mntll; mp; mp = mp->link) {
683 			if (fsstrinlist(mp->ment.mnt_mountp, keeplist))
684 				continue;
685 			mp->mlevel = fsgetmlevel(mp->ment.mnt_mountp);
686 			if (mp->ment.mnt_fstype &&
687 			    (strcmp(mp->ment.mnt_fstype, MNTTYPE_LOFS) == 0))
688 				lofscnt++;
689 
690 			mpp[ndx++] = mp;
691 		}
692 		mpp[ndx] = NULL;
693 		listlength = ndx;
694 		return (mpp);
695 	}
696 
697 	/*
698 	 * A list of mount points was specified on the command line.
699 	 * Build an array out of these.
700 	 */
701 	for (ndx = 0; count--; ) {
702 		cp = *mntlist++;
703 		if (realpath(cp, resolve) == NULL) {
704 			fprintf(stderr,
705 				gettext("%s: warning: can't resolve %s\n"),
706 				myname, cp);
707 			exitcode = 1;
708 			mp = getmntlast(mntll, NULL, cp); /* try anyways */
709 		} else
710 			mp = getmntlast(mntll, NULL, resolve);
711 		if (mp == NULL) {
712 			struct mnttab mnew;
713 			/*
714 			 * Then we've reached the end without finding
715 			 * what we are looking for, but we still have to
716 			 * try to umount it: append it to mntarray.
717 			 */
718 			fprintf(stderr, gettext(
719 				"%s: warning: %s not found in %s\n"),
720 				myname, resolve, mnttab);
721 			exitcode = 1;
722 			mntnull(&mnew);
723 			mnew.mnt_special = mnew.mnt_mountp = strdup(resolve);
724 			if (mnew.mnt_special == NULL)
725 				nomem();
726 			mp = new_mountent(&mnew);
727 		}
728 		if (mp->ment.mnt_fstype &&
729 		    (strcmp(mp->ment.mnt_fstype, MNTTYPE_LOFS) == 0))
730 			lofscnt++;
731 
732 		mp->mlevel = fsgetmlevel(mp->ment.mnt_mountp);
733 		mpp[ndx++] = mp;
734 	}
735 	mpp[ndx] = NULL;
736 	listlength = ndx;
737 	return (mpp);
738 }
739 
740 /*
741  * Returns the tail of a linked list of all mnttab entries.  I.e, it's faster
742  * to return the mnttab in reverse order.
743  * Sets listlength to the number of entries in the list.
744  * Returns NULL if none are found.
745  */
746 mountent_t *
747 getmntall(void)
748 {
749 	FILE		*fp;
750 	mountent_t	*mtail;
751 	int		cnt = 0, ret;
752 	struct mnttab	mget;
753 
754 	if ((fp = fopen(mnttab, "r")) == NULL) {
755 		fprintf(stderr, gettext("%s: warning cannot open %s\n"),
756 				myname, mnttab);
757 		return (0);
758 	}
759 	mtail = NULL;
760 
761 	while ((ret = getmntent(fp, &mget)) != -1) {
762 		mountent_t	*mp;
763 
764 		if (ret > 0) {
765 			mnterror(ret);
766 			continue;
767 		}
768 
769 		mp = new_mountent(&mget);
770 		mp->link = mtail;
771 		mtail = mp;
772 		cnt++;
773 	}
774 	fclose(fp);
775 	if (mtail == NULL) {
776 		listlength = 0;
777 		return (NULL);
778 	}
779 	listlength = cnt;
780 	return (mtail);
781 }
782 
783 void
784 do_umounts(mountent_t **mntarray)
785 {
786 	mountent_t *mp, *mpprev, **ml = mntarray;
787 	int	cnt = listlength;
788 
789 	/*
790 	 * Main loop for the forked children:
791 	 */
792 	for (mpprev = *ml; mp = *ml; mpprev = mp, ml++, cnt--) {
793 		pid_t	pid;
794 
795 		/*
796 		 * Check to see if we cross a mount level: e.g.,
797 		 * /a/b/c -> /a/b.  If so, we need to wait for all current
798 		 * umounts to finish before umounting the rest.
799 		 *
800 		 * Also, we unmount serially as long as there are lofs's
801 		 * to mount to avoid improper umount ordering.
802 		 */
803 		if (mp->mlevel < mpprev->mlevel || lofscnt > 0)
804 			while (nrun > 0 && (dowait() != -1))
805 				;
806 
807 		if (lofscnt == 0) {
808 			/*
809 			 * We can now go to parallel umounting.
810 			 */
811 			qsort((void *)ml, cnt, sizeof (mountent_t *), mcompar);
812 			mp = *ml;	/* possible first entry */
813 			lofscnt--;	/* so we don't do this again */
814 		}
815 
816 		while (setup_iopipe(mp) == -1 && (dowait() != -1))
817 			;
818 
819 		while (nrun >= maxrun && (dowait() != -1))	/* throttle */
820 			;
821 
822 #ifdef CACHEFS_BUG
823 		/*
824 		 * If this is the back file system, then let cachefs/umount
825 		 * unmount it.
826 		 */
827 		if (strstr(mp->ment.mnt_mountp, BACKMNT_NAME))
828 			continue;
829 
830 
831 		if (mp->ment.mnt_fstype &&
832 		    (strcmp(mp->ment.mnt_fstype, "cachefs") == 0)) {
833 			while (cachefs_running && (dowait() != -1))
834 					;
835 			cachefs_running = 1;
836 		}
837 #endif
838 
839 		if ((pid = fork()) == -1) {
840 			perror("fork");
841 			cleanup(-1);
842 			/* not reached */
843 		}
844 #ifdef DEBUG
845 		if (dflg && pid > 0) {
846 			fprintf(stderr, "parent %d: umounting %d %s\n",
847 				getpid(), pid, mp->ment.mnt_mountp);
848 		}
849 #endif
850 		if (pid == 0) {		/* child */
851 			signal(SIGHUP, SIG_IGN);
852 			signal(SIGQUIT, SIG_IGN);
853 			signal(SIGINT, SIG_IGN);
854 			setup_output(mp);
855 			doexec(&mp->ment);
856 			perror("exec");
857 			exit(1);
858 		}
859 
860 		/* parent */
861 		(void) close(mp->sopipe[WRPIPE]);
862 		(void) close(mp->sepipe[WRPIPE]);
863 		mp->pid = pid;
864 		nrun++;
865 	}
866 	cleanup(0);
867 }
868 
869 /*
870  * cleanup the existing children and exit with an error
871  * if asig != 0.
872  */
873 void
874 cleanup(int asig)
875 {
876 	/*
877 	 * Let the stragglers finish.
878 	 */
879 	while (nrun > 0 && (dowait() != -1))
880 		;
881 	if (asig != 0)
882 		exit(1);
883 }
884 
885 
886 /*
887  * Waits for 1 child to die.
888  *
889  * Returns -1 if no children are left to wait for.
890  * Returns 0 if a child died without an error.
891  * Returns 1 if a child died with an error.
892  * Sets the global exitcode if an error occurred.
893  */
894 int
895 dowait(void)
896 {
897 	int		wstat, child, ret;
898 	mountent_t 	*mp, *prevp;
899 
900 	if ((child = wait(&wstat)) == -1)
901 		return (-1);
902 
903 	if (WIFEXITED(wstat))		/* this should always be true */
904 		ret = WEXITSTATUS(wstat);
905 	else
906 		ret = 1;		/* assume some kind of error */
907 	nrun--;
908 	if (ret)
909 		exitcode = 1;
910 
911 	/*
912 	 * Find our child so we can process its std output, if any.
913 	 * This search gets smaller and smaller as children are cleaned
914 	 * up.
915 	 */
916 	for (prevp = NULL, mp = mntll; mp; mp = mp->link) {
917 		if (mp->pid != child) {
918 			prevp = mp;
919 			continue;
920 		}
921 		/*
922 		 * Found: let's remove it from this list.
923 		 */
924 		if (prevp) {
925 			prevp->link = mp->link;
926 			mp->link = NULL;
927 		}
928 		break;
929 	}
930 
931 	if (mp == NULL) {
932 		/*
933 		 * This should never happen.
934 		 */
935 #ifdef DEBUG
936 		fprintf(stderr, gettext(
937 			"%s: unknown child %d\n"), myname, child);
938 #endif
939 		exitcode = 1;
940 		return (1);
941 	}
942 	doio(mp);	/* Any output? */
943 
944 	if (mp->ment.mnt_fstype &&
945 	    (strcmp(mp->ment.mnt_fstype, MNTTYPE_LOFS) == 0))
946 		lofscnt--;
947 
948 #ifdef CACHEFS_BUG
949 	if (mp->ment.mnt_fstype &&
950 	    (strcmp(mp->ment.mnt_fstype, "cachefs") == 0))
951 		cachefs_running = 0;
952 #endif
953 
954 	return (ret);
955 }
956 
957 static const mountent_t zmount = { 0 };
958 
959 mountent_t *
960 new_mountent(struct mnttab *ment)
961 {
962 	mountent_t *new;
963 
964 	new = (mountent_t *)malloc(sizeof (*new));
965 	if (new == NULL)
966 		nomem();
967 
968 	*new = zmount;
969 	if (ment->mnt_special &&
970 	    (new->ment.mnt_special = strdup(ment->mnt_special)) == NULL)
971 		nomem();
972 	if (ment->mnt_mountp &&
973 	    (new->ment.mnt_mountp = strdup(ment->mnt_mountp)) == NULL)
974 		nomem();
975 	if (ment->mnt_fstype &&
976 	    (new->ment.mnt_fstype = strdup(ment->mnt_fstype)) == NULL)
977 		nomem();
978 	return (new);
979 }
980 
981 
982 /*
983  * Sort in descending order of "mount level".  For example, /a/b/c is
984  * placed before /a/b .
985  */
986 int
987 mcompar(const void *a, const void *b)
988 {
989 	mountent_t *a1, *b1;
990 
991 	a1 = *(mountent_t **)a;
992 	b1 = *(mountent_t **)b;
993 	return (b1->mlevel - a1->mlevel);
994 }
995 
996 /*
997  * The purpose of this routine is to form stdout and stderr
998  * pipes for the children's output.  The parent then reads and writes it
999  * out it serially in order to ensure that the output is
1000  * not garbled.
1001  */
1002 
1003 int
1004 setup_iopipe(mountent_t *mp)
1005 {
1006 	/*
1007 	 * Make a stdout and stderr pipe.  This should never fail.
1008 	 */
1009 	if (pipe(mp->sopipe) == -1)
1010 		return (-1);
1011 	if (pipe(mp->sepipe) == -1) {
1012 		(void) close(mp->sopipe[RDPIPE]);
1013 		(void) close(mp->sopipe[WRPIPE]);
1014 		return (-1);
1015 	}
1016 	/*
1017 	 * Don't block on an empty pipe.
1018 	 */
1019 	(void) fcntl(mp->sopipe[RDPIPE], F_SETFL, O_NDELAY|O_NONBLOCK);
1020 	(void) fcntl(mp->sepipe[RDPIPE], F_SETFL, O_NDELAY|O_NONBLOCK);
1021 	return (0);
1022 }
1023 
1024 /*
1025  * Called by a child to attach its stdout and stderr to the write side of
1026  * the pipes.
1027  */
1028 void
1029 setup_output(mountent_t *mp)
1030 {
1031 	(void) close(fileno(stdout));
1032 	(void) dup(mp->sopipe[WRPIPE]);
1033 	(void) close(mp->sopipe[WRPIPE]);
1034 
1035 	(void) close(fileno(stderr));
1036 	(void) dup(mp->sepipe[WRPIPE]);
1037 	(void) close(mp->sepipe[WRPIPE]);
1038 }
1039 
1040 /*
1041  * Parent uses this to print any stdout or stderr output issued by
1042  * the child.
1043  */
1044 static void
1045 doio(mountent_t *mp)
1046 {
1047 	int bytes;
1048 
1049 	while ((bytes = read(mp->sepipe[RDPIPE], ibuf, sizeof (ibuf))) > 0)
1050 		write(fileno(stderr), ibuf, bytes);
1051 	while ((bytes = read(mp->sopipe[RDPIPE], ibuf, sizeof (ibuf))) > 0)
1052 		write(fileno(stdout), ibuf, bytes);
1053 
1054 	(void) close(mp->sopipe[RDPIPE]);
1055 	(void) close(mp->sepipe[RDPIPE]);
1056 }
1057 
1058 void
1059 nomem(void)
1060 {
1061 	fprintf(stderr, gettext("%s: out of memory\n"), myname);
1062 	/*
1063 	 * Let the stragglers finish.
1064 	 */
1065 	while (nrun > 0 && (dowait() != -1))
1066 		;
1067 	exit(1);
1068 }
1069