xref: /titanic_44/usr/src/cmd/fs.d/ufs/df/df.c (revision ee519a1f9541a20bb76ef306dfc8e5616f8a5e26)
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 2005 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  */
38 
39 #pragma ident	"%Z%%M%	%I%	%E% SMI"
40 
41 /*
42  * df
43  */
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <sys/param.h>
47 #include <sys/types.h>
48 #include <sys/mntent.h>
49 #include <sys/fs/ufs_fs.h>
50 #include <sys/stat.h>
51 #include <sys/vfs.h>
52 #include <sys/file.h>
53 #include <sys/statvfs.h>
54 #include <sys/mnttab.h>
55 #include <sys/mkdev.h>
56 #include <locale.h>
57 #include <stdarg.h>
58 #include <string.h>
59 #include <errno.h>
60 #include <libintl.h>
61 
62 extern char	*getenv();
63 extern char	*getcwd();
64 extern char	*realpath();
65 extern off_t	lseek();
66 
67 /*
68  * Raw name to block device name translation function.
69  * This comes from libadm.
70  */
71 extern char 	*getfullblkname();
72 
73 static  void		usage(), pheader();
74 static  char		*mpath(char *);
75 static  char		*zap_chroot(char *);
76 static  char		*pathsuffix(char *, char *);
77 static  char		*xmalloc(unsigned int);
78 static  int		chroot_stat(char *, int (*)(), char *, char **);
79 static  int		bread(char *, int, daddr_t, char *, int);
80 static  int		subpath(char *, char *);
81 static	int		abspath(char *, char *, char *);
82 static  void		show_inode_usage();
83 static  void		dfreedev(char *);
84 static  void		dfreemnt(char *, struct mnttab *);
85 static  void		print_totals();
86 static  void		print_itotals();
87 static  void		print_statvfs(struct statvfs64 *);
88 static  int 		mdev(char *, struct mnttab **);
89 static struct mntlist	*mkmntlist();
90 static struct mnttab	*mntdup(struct mnttab *mnt);
91 static struct mntlist	*findmntent(char *, struct stat64 *, struct mntlist *);
92 
93 #define	bcopy(f, t, n)	memcpy(t, f, n)
94 #define	bzero(s, n)	memset(s, 0, n)
95 #define	bcmp(s, d, n)	memcmp(s, d, n)
96 
97 #define	index(s, r)	strchr(s, r)
98 #define	rindex(s, r)	strrchr(s, r)
99 
100 #define	dbtok(x, b) \
101 	((b) < (fsblkcnt64_t)1024 ? \
102 	(x) / ((fsblkcnt64_t)1024 / (b)) : (x) * ((b) / (fsblkcnt64_t)1024))
103 
104 int	aflag = 0;		/* even the uninteresting ones */
105 int	bflag = 0;		/* print only number of kilobytes free */
106 int	eflag = 0;		/* print only number of file entries free */
107 int	gflag = 0;		/* print entire statvfs structure */
108 int	hflag = 0;		/* don't print header */
109 int	iflag = 0;		/* information for inodes */
110 int	nflag = 0;		/* print VFStype name */
111 int	tflag = 0;		/* print totals */
112 int	errflag = 0;
113 int 	errcode = 0;
114 char	*typestr = "ufs";
115 fsblkcnt64_t	t_totalblks, t_avail, t_free, t_used, t_reserved;
116 int	t_inodes, t_iused, t_ifree;
117 
118 /*
119  * cached information recording previous chroot history.
120  */
121 static	char	*chrootpath;
122 
123 extern	int	optind;
124 extern	char	*optarg;
125 
126 union {
127 	struct fs iu_fs;
128 	char dummy[SBSIZE];
129 } sb;
130 #define	sblock	sb.iu_fs
131 
132 /*
133  * This structure is used to chain mntent structures into a list
134  * and to cache stat information for each member of the list.
135  */
136 struct mntlist {
137 	struct mnttab	*mntl_mnt;
138 	struct mntlist	*mntl_next;
139 	dev_t		mntl_dev;
140 	int		mntl_devvalid;
141 };
142 
143 char *subopts [] = {
144 #define	A_FLAG		0
145 	"a",
146 #define	I_FLAG		1
147 	"i",
148 	NULL
149 };
150 
151 int
152 main(int argc, char *argv[])
153 {
154 	struct mnttab 		mnt;
155 	int			opt;
156 	char			*suboptions, *value;
157 
158 	(void) setlocale(LC_ALL, "");
159 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
160 #define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it weren't */
161 #endif
162 	(void) textdomain(TEXT_DOMAIN);
163 
164 	while ((opt = getopt(argc, argv, "beghkno:t")) != EOF) {
165 		switch (opt) {
166 
167 		case 'b':	/* print only number of kilobytes free */
168 			bflag++;
169 			break;
170 
171 		case 'e':
172 			eflag++; /* print only number of file entries free */
173 			iflag++;
174 			break;
175 
176 		case 'g':
177 			gflag++;
178 			break;
179 
180 		case 'n':
181 			nflag++;
182 			break;
183 
184 		case 'k':
185 			break;
186 
187 		case 'h':
188 			hflag++;
189 			break;
190 
191 		case 'o':
192 			/*
193 			 * ufs specific options.
194 			 */
195 			suboptions = optarg;
196 			while (*suboptions != '\0') {
197 				switch (getsubopt(&suboptions,
198 				    subopts, &value)) {
199 
200 				case I_FLAG:	/* information for inodes */
201 					iflag++;
202 					break;
203 
204 				default:
205 					usage();
206 				}
207 			}
208 			break;
209 
210 		case 't':		/* print totals */
211 			tflag++;
212 			break;
213 
214 		case 'V':		/* Print command line */
215 			{
216 				char			*opt_text;
217 				int			opt_count;
218 
219 				(void) fprintf(stdout, "df -F ufs ");
220 				for (opt_count = 1; opt_count < argc;
221 				    opt_count++) {
222 					opt_text = argv[opt_count];
223 					if (opt_text)
224 						(void) fprintf(stdout, " %s ",
225 						    opt_text);
226 				}
227 				(void) fprintf(stdout, "\n");
228 			}
229 			break;
230 
231 		case '?':
232 			errflag++;
233 		}
234 	}
235 	if (errflag)
236 		usage();
237 	if (gflag && iflag) {
238 		printf(gettext("df: '-g' and '-o i' are mutually exclusive\n"));
239 		exit(1);
240 	}
241 	if (bflag || eflag)
242 		tflag = 0;
243 
244 	/*
245 	 * Cache CHROOT information for later use; assume that $CHROOT matches
246 	 * the cumulative arguments given to chroot calls.
247 	 */
248 	chrootpath = getenv("CHROOT");
249 	if (chrootpath != NULL && strcmp(chrootpath, "/") == 0)
250 		chrootpath = NULL;
251 
252 	if (argc <= optind) {
253 		/*
254 		 * Take this path when "/usr/lib/fs/ufs/df" is specified, and
255 		 * there are no mountpoints specified.
256 		 * E.g., these command lines take us down this path
257 		 * 	/usr/lib/fs/ufs/df -o i
258 		 *	/usr/lib/fs/ufs/df
259 		 */
260 		FILE *mtabp;
261 
262 		if ((mtabp = fopen(MNTTAB, "r")) == NULL) {
263 			(void) fprintf(stderr, "df: ");
264 			perror(MNTTAB);
265 			exit(1);
266 		}
267 		pheader();
268 		while (getmntent(mtabp, &mnt) == 0) {
269 			if (strcmp(typestr, mnt.mnt_fstype) != 0) {
270 				continue;
271 			}
272 			dfreemnt(mnt.mnt_mountp, &mnt);
273 		}
274 		if (tflag)
275 			if (iflag)
276 				print_itotals();
277 			else
278 				print_totals();
279 		(void) fclose(mtabp);
280 	} else {
281 		int i;
282 		struct mntlist *mntl;
283 		struct stat64    *argstat;
284 		char **devnames;
285 		char *cp;
286 
287 		/*
288 		 * Obtain stat64 information for each argument before
289 		 * constructing the list of mounted file systems.  This
290 		 * ordering forces the automounter to establish any
291 		 * mounts required to access the arguments, so that the
292 		 * corresponding mount table entries will exist when
293 		 * we look for them.
294 		 */
295 		argv++;
296 		argc--;
297 		argstat = (struct stat64 *)xmalloc(argc * sizeof (*argstat));
298 		devnames = (char **)xmalloc(argc * sizeof (char *));
299 		for (i = 0; i < argc; i++) {
300 
301 			/*
302 			 * Given a raw device name, get the block device name
303 			 */
304 			cp = getfullblkname(argv[i]);
305 			if (cp == NULL || *cp == '\0') {
306 				if (cp != NULL)
307 					free(cp);
308 				cp = strdup(argv[i]);
309 
310 				if (cp == NULL) {
311 					int j;
312 
313 					fprintf(stderr, gettext(
314 					"df: memory allocation failure\n"));
315 
316 					for (j = 0; j < i; j++)
317 						free(devnames[j]);
318 					free(devnames);
319 					free(argstat);
320 					exit(1);
321 				}
322 			}
323 			if (stat64(cp, &argstat[i]) < 0) {
324 				errcode = errno;
325 				/*
326 				 * Mark as no longer interesting.
327 				 */
328 				argv[i] = NULL;
329 				devnames[i] = NULL;
330 				free(cp);
331 			} else {
332 				devnames[i] = cp;
333 			}
334 		}
335 
336 		pheader();
337 		aflag++;
338 		/*
339 		 * Construct the list of mounted file systems.
340 		 */
341 		mntl = mkmntlist();
342 
343 		/*
344 		 * Iterate through the argument list, reporting on each one.
345 		 */
346 		for (i = 0; i < argc; i++) {
347 			struct mntlist *mlp;
348 			int isblk;
349 
350 			/*
351 			 * Skip if we've already determined that we can't
352 			 * process it.
353 			 */
354 			if (argv[i] == NULL)
355 				continue;
356 
357 			/*
358 			 * If the argument names a device, report on the file
359 			 * system associated with the device rather than on
360 			 * the one containing the device's directory entry
361 			 */
362 			cp = devnames[i];
363 			if ((isblk = (argstat[i].st_mode&S_IFMT) == S_IFBLK) ||
364 			    (argstat[i].st_mode & S_IFMT) == S_IFCHR) {
365 				if (isblk && strcmp(mpath(cp), "") != 0) {
366 					struct mnttab *mp;
367 					if (mdev(cp, &mp))
368 						return (1);
369 					dfreemnt(mp->mnt_mountp, mp);
370 				} else {
371 					dfreedev(cp);
372 				}
373 				free(cp);
374 				devnames[i] = NULL;
375 				continue;
376 			}
377 
378 			/*
379 			 * Get this argument's corresponding mount table
380 			 * entry.
381 			 */
382 			mlp = findmntent(cp, &argstat[i], mntl);
383 			free(cp);
384 			devnames[i] = NULL;
385 
386 			if (mlp == NULL) {
387 				(void) fprintf(stderr,
388 				gettext("Could not find mount point for %s\n"),
389 				    argv[i]);
390 				continue;
391 			}
392 
393 			dfreemnt(mlp->mntl_mnt->mnt_mountp, mlp->mntl_mnt);
394 		}
395 		free(devnames);
396 		free(argstat);
397 	}
398 	return (0);
399 }
400 
401 void
402 pheader()
403 {
404 	if (hflag)
405 		return;
406 	if (nflag)
407 		(void) printf(gettext("VFStype name - ufs\n"));
408 	if (iflag) {
409 		if (eflag)
410 			/*
411 			 * TRANSLATION_NOTE
412 			 * Following string is used as a table header.
413 			 * Translated items should start at the same
414 			 * columns as the original items.
415 			 */
416 			(void) printf(gettext(
417 "Filesystem             ifree\n"));
418 		else {
419 			/*
420 			 * TRANSLATION_NOTE
421 			 * Following string is used as a table header.
422 			 * Translated items should start at the same
423 			 * columns as the original items.
424 			 */
425 			(void) printf(gettext(
426 "Filesystem             iused   ifree  %%iused  Mounted on\n"));
427 		}
428 	} else {
429 		if (gflag)
430 			/*
431 			 * TRANSLATION_NOTE
432 			 * Following string is used as a table header.
433 			 * Translated items should start at the same
434 			 * columns as the original items.
435 			 */
436 			(void) printf(gettext(
437 "Filesystem        f_type f_fsize f_bfree f_bavail f_files f_ffree "
438 "f_fsid f_flag f_fstr\n"));
439 		else
440 			if (bflag)
441 				/*
442 				 * TRANSLATION_NOTE
443 				 * Following string is used as a table header.
444 				 * Translated items should start at the same
445 				 * columns as the original items.
446 				 */
447 				(void) printf(gettext(
448 "Filesystem             avail\n"));
449 			else {
450 				/*
451 				 * TRANSLATION_NOTE
452 				 * Following string is used as a table header.
453 				 * Translated items should start at the same
454 				 * columns as the original items.
455 				 */
456 				(void) printf(gettext(
457 "Filesystem            kbytes    used   avail capacity  Mounted on\n"));
458 			}
459 		}
460 }
461 
462 /*
463  * Report on a block or character special device. Assumed not to be
464  * mounted.  N.B. checks for a valid UFS superblock.
465  */
466 void
467 dfreedev(char *file)
468 {
469 	fsblkcnt64_t totalblks, availblks, avail, free, used;
470 	int fi;
471 
472 	fi = open64(file, 0);
473 	if (fi < 0) {
474 		(void) fprintf(stderr, "df: ");
475 		perror(file);
476 		return;
477 	}
478 	if (bread(file, fi, SBLOCK, (char *)&sblock, SBSIZE) == 0) {
479 		(void) close(fi);
480 		return;
481 	}
482 	if ((sblock.fs_magic != FS_MAGIC) &&
483 	    (sblock.fs_magic != MTB_UFS_MAGIC)) {
484 		(void) fprintf(stderr, gettext(
485 "df: %s: not a ufs file system\n"),
486 		    file);
487 		(void) close(fi);
488 		return;
489 	}
490 	if (sblock.fs_magic == FS_MAGIC &&
491 	    (sblock.fs_version != UFS_EFISTYLE4NONEFI_VERSION_2 &&
492 	    sblock.fs_version != UFS_VERSION_MIN)) {
493 		(void) fprintf(stderr, gettext(
494 "df: %s: unrecognized version of UFS: %d\n"),
495 		    file, sblock.fs_version);
496 		(void) close(fi);
497 		return;
498 	}
499 	if (sblock.fs_magic == MTB_UFS_MAGIC &&
500 	    (sblock.fs_version > MTB_UFS_VERSION_1 ||
501 	    sblock.fs_version < MTB_UFS_VERSION_MIN)) {
502 		(void) fprintf(stderr, gettext(
503 "df: %s: unrecognized version of UFS: %d\n"),
504 		    file, sblock.fs_version);
505 		(void) close(fi);
506 		return;
507 	}
508 	(void) printf("%-20.20s", file);
509 	if (iflag) {
510 		if (eflag) {
511 			(void) printf("%8ld", sblock.fs_cstotal.cs_nifree);
512 		} else {
513 			show_inode_usage(
514 		(fsfilcnt64_t)sblock.fs_ncg * (fsfilcnt64_t)sblock.fs_ipg,
515 			(fsfilcnt64_t)sblock.fs_cstotal.cs_nifree);
516 		}
517 	} else {
518 		totalblks = (fsblkcnt64_t)sblock.fs_dsize;
519 		free =
520 		    (fsblkcnt64_t)sblock.fs_cstotal.cs_nbfree *
521 		    (fsblkcnt64_t)sblock.fs_frag +
522 		    (fsblkcnt64_t)sblock.fs_cstotal.cs_nffree;
523 		used = totalblks - free;
524 		availblks = totalblks / (fsblkcnt64_t)100 *
525 		    ((fsblkcnt64_t)100 - (fsblkcnt64_t)sblock.fs_minfree);
526 		avail = availblks > used ? availblks - used : (fsblkcnt64_t)0;
527 		if (bflag) {
528 			(void) printf("%8lld\n", dbtok(avail,
529 					(fsblkcnt64_t)sblock.fs_fsize));
530 		} else {
531 			(void) printf(" %7lld %7lld %7lld",
532 			    dbtok(totalblks, (fsblkcnt64_t)sblock.fs_fsize),
533 			    dbtok(used, (fsblkcnt64_t)sblock.fs_fsize),
534 			    dbtok(avail, (fsblkcnt64_t)sblock.fs_fsize));
535 			(void) printf("%6.0f%%",
536 			    availblks == 0 ? 0.0 :
537 			    (double)used / (double)availblks * 100.0);
538 			(void) printf("  ");
539 		}
540 		if (tflag) {
541 			t_totalblks += dbtok(totalblks,
542 					(fsblkcnt64_t)sblock.fs_fsize);
543 			t_used += dbtok(used, (fsblkcnt64_t)sblock.fs_fsize);
544 			t_avail += dbtok(avail, (fsblkcnt64_t)sblock.fs_fsize);
545 			t_free += free;
546 		}
547 	}
548 	if ((!bflag) && (!eflag))
549 		(void) printf("  %s\n", mpath(file));
550 	else if (eflag)
551 		(void) printf("\n");
552 	(void) close(fi);
553 }
554 
555 void
556 dfreemnt(char *file, struct mnttab *mnt)
557 {
558 	struct statvfs64 fs;
559 
560 	if (statvfs64(file, &fs) < 0 &&
561 	    chroot_stat(file, statvfs64, (char *)&fs, &file) < 0) {
562 		(void) fprintf(stderr, "df: ");
563 		perror(file);
564 		return;
565 	}
566 
567 	if (!aflag && fs.f_blocks == 0) {
568 		return;
569 	}
570 	if (!isatty(fileno(stdout))) {
571 		(void) printf("%s", mnt->mnt_special);
572 	} else {
573 		if (strlen(mnt->mnt_special) > (size_t)20) {
574 			(void) printf("%s\n", mnt->mnt_special);
575 			(void) printf("                    ");
576 		} else {
577 			(void) printf("%-20.20s", mnt->mnt_special);
578 		}
579 	}
580 	if (iflag) {
581 		if (eflag) {
582 			(void) printf("%8lld", fs.f_ffree);
583 		} else {
584 			show_inode_usage(fs.f_files, fs.f_ffree);
585 		}
586 	} else {
587 		if (gflag) {
588 			print_statvfs(&fs);
589 		} else {
590 			fsblkcnt64_t totalblks, avail, free, used, reserved;
591 
592 			totalblks = fs.f_blocks;
593 			free = fs.f_bfree;
594 			used = totalblks - free;
595 			avail = fs.f_bavail;
596 			reserved = free - avail;
597 			if ((long long)avail < 0)
598 				avail = 0;
599 			if (bflag) {
600 				(void) printf("%8lld\n", dbtok(avail,
601 				(fsblkcnt64_t)fs.f_frsize));
602 			} else {
603 				(void) printf(" %7lld %7lld %7lld",
604 				dbtok(totalblks,
605 				(fsblkcnt64_t)fs.f_frsize),
606 				dbtok(used, (fsblkcnt64_t)fs.f_frsize),
607 				dbtok(avail, (fsblkcnt64_t)fs.f_frsize));
608 				totalblks -= reserved;
609 				(void) printf("%6.0f%%",
610 				    totalblks == 0 ? 0.0 :
611 				    (double)used / (double)totalblks * 100.0);
612 				(void) printf("  ");
613 				if (tflag) {
614 				t_totalblks += dbtok(totalblks + reserved,
615 				    (fsblkcnt64_t)fs.f_bsize);
616 				t_reserved += reserved;
617 				t_used += dbtok(used,
618 						(fsblkcnt64_t)fs.f_frsize);
619 				t_avail += dbtok(avail,
620 						(fsblkcnt64_t)fs.f_frsize);
621 				t_free += free;
622 				}
623 			}
624 		}
625 	}
626 	if ((!bflag) && (!eflag) && (!gflag))
627 		(void) printf("  %s\n", mnt->mnt_mountp);
628 	else if (eflag)
629 		(void) printf("\n");
630 }
631 
632 static void
633 show_inode_usage(fsfilcnt64_t total, fsfilcnt64_t free)
634 {
635 	fsfilcnt64_t used = total - free;
636 	int missing_info = ((long long)total == (long long)-1 ||
637 	    (long long)free == (long long)-1);
638 
639 	if (missing_info)
640 		(void) printf("%8s", "*");
641 	else
642 		(void) printf("%8lld", used);
643 	if ((long long)free == (long long)-1)
644 		(void) printf("%8s", "*");
645 	else
646 		(void) printf(" %7lld", free);
647 	if (missing_info)
648 		(void) printf("%6s  ", "*");
649 	else
650 		(void) printf("%6.0f%% ", (double)used / (double)total * 100.0);
651 }
652 
653 /*
654  * Return the suffix of path obtained by stripping off the prefix
655  * that is the value of the CHROOT environment variable.  If this
656  * value isn't obtainable or if it's not a prefix of path, return NULL.
657  */
658 static char *
659 zap_chroot(char *path)
660 {
661 	return (pathsuffix(path, chrootpath));
662 }
663 
664 /*
665  * Stat/statfs a file after stripping off leading directory to which we are
666  * chroot'd.  Used to find the TFS mount that applies to the current
667  * activated NSE environment.
668  */
669 static int
670 chroot_stat(char *dir, int (*statfunc)(), char *statp, char **dirp)
671 {
672 	if ((dir = zap_chroot(dir)) == NULL)
673 		return (-1);
674 	if (dirp)
675 		*dirp = dir;
676 	return (*statfunc)(dir, statp);
677 }
678 
679 /*
680  * Given a name like /dev/dsk/c1d0s2, returns the mounted path, like /usr.
681  */
682 char *
683 mpath(char *file)
684 {
685 	struct mnttab mnt;
686 	FILE *mnttab;
687 	struct stat64 device_stat, mount_stat;
688 	char *mname;
689 
690 	mnttab = fopen(MNTTAB, "r");
691 	if (mnttab == NULL) {
692 		return ("");
693 	}
694 	mname = "";
695 	while ((getmntent(mnttab, &mnt)) == 0) {
696 		if (strcmp(mnt.mnt_fstype, MNTTYPE_UFS) != 0) {
697 			continue;
698 		}
699 		if (strcmp(file, mnt.mnt_special) == 0) {
700 			if (stat64(mnt.mnt_mountp, &mount_stat) != 0)
701 				continue;
702 			if (stat64(mnt.mnt_special, &device_stat) != 0)
703 				continue;
704 
705 			if (device_stat.st_rdev == mount_stat.st_dev) {
706 				mname = mnt.mnt_mountp;
707 				break;
708 			}
709 		}
710 	}
711 	fclose(mnttab);
712 	return (mname);
713 }
714 
715 /*
716  * Given a special device, return mnttab entry
717  * Returns 0 on success
718  */
719 
720 int
721 mdev(char *spec, struct mnttab **mntbp)
722 {
723 	FILE *mntp;
724 	struct mnttab mnt;
725 
726 	if ((mntp = fopen(MNTTAB, "r")) == 0) {
727 		(void) fprintf(stderr, "df: ");
728 		perror(MNTTAB);
729 		return (1);
730 	}
731 
732 	while (getmntent(mntp, &mnt) == 0) {
733 		if (strcmp(spec, mnt.mnt_special) == 0) {
734 			(void) fclose(mntp);
735 			*mntbp =  mntdup(&mnt);
736 			return (0);
737 		}
738 	}
739 	(void) fclose(mntp);
740 	(void) fprintf(stderr, "df : couldn't find mnttab entry for %s", spec);
741 	return (1);
742 }
743 
744 /*
745  * Find the entry in mlist that corresponds to the file named by path
746  * (i.e., that names a mount table entry for the file system in which
747  * path lies).  The pstat argument must point to stat information for
748  * path.
749  *
750  * Return the entry or NULL if there's no match.
751  *
752  * As it becomes necessary to obtain stat information about previously
753  * unexamined mlist entries, gather the information and cache it with the
754  * entries.
755  *
756  * The routine's strategy is to convert path into its canonical, symlink-free
757  * representation canon (which will require accessing the file systems on the
758  * branch from the root to path and thus may cause the routine to hang if any
759  * of them are inaccessible) and to use it to search for a mount point whose
760  * name is a substring of canon and whose corresponding device matches that of
761  * canon.  This technique avoids accessing unnecessary file system resources
762  * and thus prevents the program from hanging on inaccessible resources unless
763  * those resources are necessary for accessing path.
764  */
765 static struct mntlist *
766 findmntent(char *path, struct stat64 *pstat, struct mntlist *mlist)
767 {
768 	static char		cwd[MAXPATHLEN];
769 	char			canon[MAXPATHLEN];
770 	char			scratch[MAXPATHLEN];
771 	struct mntlist *mlp;
772 
773 	/*
774 	 * If path is relative and we haven't already determined the current
775 	 * working directory, do so now.  Calculating the working directory
776 	 * here lets us do the work once, instead of (potentially) repeatedly
777 	 * in realpath().
778 	 */
779 	if (*path != '/' && cwd[0] == '\0') {
780 		if (getcwd(cwd, MAXPATHLEN) == NULL) {
781 			cwd[0] = '\0';
782 			return (NULL);
783 		}
784 	}
785 
786 	/*
787 	 * Find an absolute pathname in the native file system name space that
788 	 * corresponds to path, stuffing it into canon.
789 	 *
790 	 * If CHROOT is set in the environment, assume that chroot($CHROOT)
791 	 * (or an equivalent series of calls) was executed and convert the
792 	 * path to the equivalent name in the native file system's name space.
793 	 * Doing so allows direct comparison with the names in mtab entires,
794 	 * which are assumed to be recorded relative to the native name space.
795 	 */
796 	if (abspath(cwd, path, scratch) < 0)
797 		return (NULL);
798 	if (strcmp(scratch, "/") == 0 && chrootpath != NULL) {
799 		/*
800 		 * Force canon to be in canonical form; if the result from
801 		 * abspath was "/" and chrootpath isn't the null string, we
802 		 * must strip off a trailing slash.
803 		 */
804 		scratch[0] = '\0';
805 	}
806 	(void) sprintf(canon, "%s%s", chrootpath ? chrootpath : "", scratch);
807 
808 again:
809 	for (mlp = mlist; mlp; mlp = mlp->mntl_next) {
810 		struct mnttab *mnt = mlp->mntl_mnt;
811 
812 		/*
813 		 * Ignore uninteresting mounts.
814 		 */
815 		if (strcmp(mnt->mnt_fstype, typestr) != 0)
816 			continue;
817 
818 		/*
819 		 * The mount entry covers some prefix of the file.
820 		 * See whether it's the entry for the file system
821 		 * containing the file by comparing device ids.
822 		 */
823 		if (mlp->mntl_dev == NODEV) {
824 			struct stat64 fs_sb;
825 
826 			if (stat64(mnt->mnt_mountp, &fs_sb) < 0 &&
827 			    chroot_stat(mnt->mnt_mountp, stat64, (char *)&fs_sb,
828 			    (char **)NULL) < 0) {
829 				continue;
830 			}
831 			mlp->mntl_dev = fs_sb.st_dev;
832 		}
833 
834 		if (pstat->st_dev == mlp->mntl_dev)
835 			return (mlp);
836 	}
837 
838 	return (NULL);
839 }
840 
841 /*
842  * Convert the path given in raw to canonical, absolute, symlink-free
843  * form, storing the result in the buffer named by canon, which must be
844  * at least MAXPATHLEN bytes long.  "wd" contains the current working
845  * directory; accepting this value as an argument lets our caller cache
846  * the value, so that realpath (called from this routine) doesn't have
847  * to recalculate it each time it's given a relative pathname.
848  *
849  * Return 0 on success, -1 on failure.
850  */
851 static int
852 abspath(char *wd, char *raw, char *canon)
853 {
854 	char		absbuf[MAXPATHLEN];
855 
856 	/*
857 	 * Preliminary sanity check.
858 	 */
859 	if (wd == NULL || raw == NULL || canon == NULL)
860 		return (-1);
861 
862 	/*
863 	 * If the path is relative, convert it to absolute form,
864 	 * using wd if it's been supplied.
865 	 */
866 	if (raw[0] != '/') {
867 		char	*limit = absbuf + sizeof (absbuf);
868 		char	*d;
869 
870 		/* Fill in working directory. */
871 		if (strlcpy(absbuf, wd, sizeof (absbuf)) >= sizeof (absbuf))
872 			return (-1);
873 
874 		/* Add separating slash. */
875 		d = absbuf + strlen(absbuf);
876 		if (d < limit)
877 			*d++ = '/';
878 
879 		/* Glue on the relative part of the path. */
880 		while (d < limit && (*d++ = *raw++))
881 			continue;
882 
883 		raw = absbuf;
884 	}
885 
886 	/*
887 	 * Call realpath to canonicalize and resolve symlinks.
888 	 */
889 	return (realpath(raw, canon) == NULL ? -1 : 0);
890 }
891 
892 /*
893  * Return a pointer to the trailing suffix of full that follows the prefix
894  * given by pref.  If pref isn't a prefix of full, return NULL.  Apply
895  * pathname semantics to the prefix test, so that pref must match at a
896  * component boundary.
897  */
898 static char *
899 pathsuffix(char *full, char *pref)
900 {
901 	int preflen;
902 
903 	if (full == NULL || pref == NULL)
904 		return (NULL);
905 
906 	preflen = strlen(pref);
907 	if (strncmp(pref, full, preflen) != 0)
908 		return (NULL);
909 
910 	/*
911 	 * pref is a substring of full.  To be a subpath, it cannot cover a
912 	 * partial component of full.  The last clause of the test handles the
913 	 * special case of the root.
914 	 */
915 	if (full[preflen] != '\0' && full[preflen] != '/' && preflen > 1)
916 		return (NULL);
917 
918 	if (preflen == 1 && full[0] == '/')
919 		return (full);
920 	else
921 		return (full + preflen);
922 }
923 
924 /*
925  * Return zero iff the path named by sub is a leading subpath
926  * of the path named by full.
927  *
928  * Treat null paths as matching nothing.
929  */
930 static int
931 subpath(char *full, char *sub)
932 {
933 	return (pathsuffix(full, sub) == NULL);
934 }
935 
936 offset_t llseek();
937 
938 int
939 bread(char *file, int fi, daddr_t bno, char *buf, int cnt)
940 {
941 	int n;
942 
943 	(void) llseek(fi, (offset_t)bno * DEV_BSIZE, 0);
944 	if ((n = read(fi, buf, cnt)) < 0) {
945 		/* probably a dismounted disk if errno == EIO */
946 		if (errno != EIO) {
947 			(void) fprintf(stderr, gettext("df: read error on "));
948 			perror(file);
949 			(void) fprintf(stderr, "bno = %ld\n", bno);
950 		} else {
951 			(void) fprintf(stderr, gettext(
952 "df: premature EOF on %s\n"), file);
953 			(void) fprintf(stderr,
954 			"bno = %ld expected = %d count = %d\n", bno, cnt, n);
955 		}
956 		return (0);
957 	}
958 	return (1);
959 }
960 
961 char *
962 xmalloc(unsigned int size)
963 {
964 	char *ret;
965 	char *malloc();
966 
967 	if ((ret = (char *)malloc(size)) == NULL) {
968 		(void) fprintf(stderr, gettext("umount: ran out of memory!\n"));
969 		exit(1);
970 	}
971 	return (ret);
972 }
973 
974 struct mnttab *
975 mntdup(struct mnttab *mnt)
976 {
977 	struct mnttab *new;
978 
979 	new = (struct mnttab *)xmalloc(sizeof (*new));
980 
981 	new->mnt_special =
982 	    (char *)xmalloc((unsigned)(strlen(mnt->mnt_special) + 1));
983 	(void) strcpy(new->mnt_special, mnt->mnt_special);
984 
985 	new->mnt_mountp =
986 	    (char *)xmalloc((unsigned)(strlen(mnt->mnt_mountp) + 1));
987 	(void) strcpy(new->mnt_mountp, mnt->mnt_mountp);
988 
989 	new->mnt_fstype =
990 	    (char *)xmalloc((unsigned)(strlen(mnt->mnt_fstype) + 1));
991 	(void) strcpy(new->mnt_fstype, mnt->mnt_fstype);
992 
993 	if (mnt->mnt_mntopts != NULL) {
994 		new->mnt_mntopts =
995 		    (char *)xmalloc((unsigned)(strlen(mnt->mnt_mntopts) + 1));
996 		(void) strcpy(new->mnt_mntopts, mnt->mnt_mntopts);
997 	} else {
998 		new->mnt_mntopts = NULL;
999 	}
1000 
1001 #ifdef never
1002 	new->mnt_freq = mnt->mnt_freq;
1003 	new->mnt_passno = mnt->mnt_passno;
1004 #endif /* never */
1005 
1006 	return (new);
1007 }
1008 
1009 void
1010 usage()
1011 {
1012 
1013 	(void) fprintf(stderr, gettext(
1014 "ufs usage: df [generic options] [-o i] [directory | special]\n"));
1015 	exit(1);
1016 }
1017 
1018 struct mntlist *
1019 mkmntlist()
1020 {
1021 	FILE *mounted;
1022 	struct mntlist *mntl;
1023 	struct mntlist *mntst = NULL;
1024 	struct extmnttab mnt;
1025 
1026 	if ((mounted = fopen(MNTTAB, "r")) == NULL) {
1027 		(void) fprintf(stderr, "df : ");
1028 		perror(MNTTAB);
1029 		exit(1);
1030 	}
1031 	resetmnttab(mounted);
1032 	while (getextmntent(mounted, &mnt, sizeof (struct extmnttab)) == NULL) {
1033 		mntl = (struct mntlist *)xmalloc(sizeof (*mntl));
1034 		mntl->mntl_mnt = mntdup((struct mnttab *)(&mnt));
1035 		mntl->mntl_next = mntst;
1036 		mntl->mntl_devvalid = 1;
1037 		mntl->mntl_dev = makedev(mnt.mnt_major, mnt.mnt_minor);
1038 		mntst = mntl;
1039 	}
1040 	(void) fclose(mounted);
1041 	return (mntst);
1042 }
1043 
1044 void
1045 print_statvfs(struct statvfs64 *fs)
1046 {
1047 	int	i;
1048 
1049 	for (i = 0; i < FSTYPSZ; i++)
1050 		(void) printf("%c", fs->f_basetype[i]);
1051 	(void) printf(" %7d %7lld %7lld",
1052 	    fs->f_frsize,
1053 	    fs->f_blocks,
1054 	    fs->f_bavail);
1055 	(void) printf(" %7lld %7lld %7d",
1056 	    fs->f_files,
1057 	    fs->f_ffree,
1058 	    fs->f_fsid);
1059 	(void) printf(" 0x%x ",
1060 	    fs->f_flag);
1061 	for (i = 0; i < 14; i++)
1062 		(void) printf("%c",
1063 		    (fs->f_fstr[i] == '\0') ? ' ' : fs->f_fstr[i]);
1064 	printf("\n");
1065 }
1066 
1067 void
1068 print_totals()
1069 {
1070 	/*
1071 	 * TRANSLATION_NOTE
1072 	 * Following string is used as a table header.
1073 	 * Translated items should start at the same
1074 	 * columns as the original items.
1075 	 */
1076 	(void) printf(gettext("Totals              %8lld %7lld %7lld"),
1077 		t_totalblks, t_used, t_avail);
1078 	(void) printf("%6.0f%%\n",
1079 	    (t_totalblks - t_reserved) == (fsblkcnt64_t)0 ?
1080 		0.0 :
1081 		(double)t_used / (double)(t_totalblks - t_reserved) * 100.0);
1082 }
1083 
1084 void
1085 print_itotals()
1086 {
1087 	/*
1088 	 * TRANSLATION_NOTE
1089 	 * Following string is used as a table header.
1090 	 * Translated items should start at the same
1091 	 * columns as the original items.
1092 	 */
1093 	(void) printf(gettext("Totals              %8d %7d%6.0f%%\n"),
1094 	    t_iused,
1095 	    t_ifree,
1096 	    t_inodes == 0 ? 0.0 : (double)t_iused / (double)t_inodes * 100.0);
1097 }
1098