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