xref: /freebsd/bin/df/df.c (revision 70e0bbedef95258a4dadc996d641a9bebd3f107d)
1 /*-
2  * Copyright (c) 1980, 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if 0
36 #ifndef lint
37 static const char copyright[] =
38 "@(#) Copyright (c) 1980, 1990, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 static char sccsid[] = "@(#)df.c	8.9 (Berkeley) 5/8/95";
44 #endif /* not lint */
45 #endif
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 #include <sys/mount.h>
52 #include <sys/sysctl.h>
53 #include <ufs/ufs/ufsmount.h>
54 #include <err.h>
55 #include <libutil.h>
56 #include <stdint.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <sysexits.h>
61 #include <unistd.h>
62 
63 #include "extern.h"
64 
65 #define UNITS_SI	1
66 #define UNITS_2		2
67 
68 /* Maximum widths of various fields. */
69 struct maxwidths {
70 	int	mntfrom;
71 	int	fstype;
72 	int	total;
73 	int	used;
74 	int	avail;
75 	int	iused;
76 	int	ifree;
77 };
78 
79 static void	  addstat(struct statfs *, struct statfs *);
80 static char	 *getmntpt(const char *);
81 static int	  int64width(int64_t);
82 static char	 *makenetvfslist(void);
83 static void	  prthuman(const struct statfs *, int64_t);
84 static void	  prthumanval(int64_t);
85 static intmax_t	  fsbtoblk(int64_t, uint64_t, u_long);
86 static void	  prtstat(struct statfs *, struct maxwidths *);
87 static size_t	  regetmntinfo(struct statfs **, long, const char **);
88 static void	  update_maxwidths(struct maxwidths *, const struct statfs *);
89 static void	  usage(void);
90 
91 static __inline int
92 imax(int a, int b)
93 {
94 	return (a > b ? a : b);
95 }
96 
97 static int	aflag = 0, cflag, hflag, iflag, kflag, lflag = 0, nflag, Tflag;
98 static struct	ufs_args mdev;
99 
100 int
101 main(int argc, char *argv[])
102 {
103 	struct stat stbuf;
104 	struct statfs statfsbuf, totalbuf;
105 	struct maxwidths maxwidths;
106 	struct statfs *mntbuf;
107 	const char *fstype;
108 	char *mntpath, *mntpt;
109 	const char **vfslist;
110 	int i, mntsize;
111 	int ch, rv;
112 
113 	fstype = "ufs";
114 
115 	memset(&totalbuf, 0, sizeof(totalbuf));
116 	totalbuf.f_bsize = DEV_BSIZE;
117 	strlcpy(totalbuf.f_mntfromname, "total", MNAMELEN);
118 	vfslist = NULL;
119 	while ((ch = getopt(argc, argv, "abcgHhiklmnPt:T")) != -1)
120 		switch (ch) {
121 		case 'a':
122 			aflag = 1;
123 			break;
124 		case 'b':
125 				/* FALLTHROUGH */
126 		case 'P':
127 			/*
128 			 * POSIX specifically discusses the behavior of
129 			 * both -k and -P. It states that the blocksize should
130 			 * be set to 1024. Thus, if this occurs, simply break
131 			 * rather than clobbering the old blocksize.
132 			 */
133 			if (kflag)
134 				break;
135 			setenv("BLOCKSIZE", "512", 1);
136 			hflag = 0;
137 			break;
138 		case 'c':
139 			cflag = 1;
140 			break;
141 		case 'g':
142 			setenv("BLOCKSIZE", "1g", 1);
143 			hflag = 0;
144 			break;
145 		case 'H':
146 			hflag = UNITS_SI;
147 			break;
148 		case 'h':
149 			hflag = UNITS_2;
150 			break;
151 		case 'i':
152 			iflag = 1;
153 			break;
154 		case 'k':
155 			kflag++;
156 			setenv("BLOCKSIZE", "1024", 1);
157 			hflag = 0;
158 			break;
159 		case 'l':
160 			if (vfslist != NULL)
161 				errx(1, "-l and -t are mutually exclusive.");
162 			vfslist = makevfslist(makenetvfslist());
163 			lflag = 1;
164 			break;
165 		case 'm':
166 			setenv("BLOCKSIZE", "1m", 1);
167 			hflag = 0;
168 			break;
169 		case 'n':
170 			nflag = 1;
171 			break;
172 		case 't':
173 			if (lflag)
174 				errx(1, "-l and -t are mutually exclusive.");
175 			if (vfslist != NULL)
176 				errx(1, "only one -t option may be specified");
177 			fstype = optarg;
178 			vfslist = makevfslist(optarg);
179 			break;
180 		case 'T':
181 			Tflag = 1;
182 			break;
183 		case '?':
184 		default:
185 			usage();
186 		}
187 	argc -= optind;
188 	argv += optind;
189 
190 	rv = 0;
191 	if (!*argv) {
192 		/* everything (modulo -t) */
193 		mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
194 		mntsize = regetmntinfo(&mntbuf, mntsize, vfslist);
195 	} else {
196 		/* just the filesystems specified on the command line */
197 		mntbuf = malloc(argc * sizeof(*mntbuf));
198 		if (mntbuf == 0)
199 			err(1, "malloc()");
200 		mntsize = 0;
201 		/* continued in for loop below */
202 	}
203 
204 	/* iterate through specified filesystems */
205 	for (; *argv; argv++) {
206 		if (stat(*argv, &stbuf) < 0) {
207 			if ((mntpt = getmntpt(*argv)) == 0) {
208 				warn("%s", *argv);
209 				rv = 1;
210 				continue;
211 			}
212 		} else if (S_ISCHR(stbuf.st_mode)) {
213 			if ((mntpt = getmntpt(*argv)) == 0) {
214 				mdev.fspec = *argv;
215 				mntpath = strdup("/tmp/df.XXXXXX");
216 				if (mntpath == NULL) {
217 					warn("strdup failed");
218 					rv = 1;
219 					continue;
220 				}
221 				mntpt = mkdtemp(mntpath);
222 				if (mntpt == NULL) {
223 					warn("mkdtemp(\"%s\") failed", mntpath);
224 					rv = 1;
225 					free(mntpath);
226 					continue;
227 				}
228 				if (mount(fstype, mntpt, MNT_RDONLY,
229 				    &mdev) != 0) {
230 					warn("%s", *argv);
231 					rv = 1;
232 					(void)rmdir(mntpt);
233 					free(mntpath);
234 					continue;
235 				} else if (statfs(mntpt, &statfsbuf) == 0) {
236 					statfsbuf.f_mntonname[0] = '\0';
237 					prtstat(&statfsbuf, &maxwidths);
238 					if (cflag)
239 						addstat(&totalbuf, &statfsbuf);
240 				} else {
241 					warn("%s", *argv);
242 					rv = 1;
243 				}
244 				(void)unmount(mntpt, 0);
245 				(void)rmdir(mntpt);
246 				free(mntpath);
247 				continue;
248 			}
249 		} else
250 			mntpt = *argv;
251 
252 		/*
253 		 * Statfs does not take a `wait' flag, so we cannot
254 		 * implement nflag here.
255 		 */
256 		if (statfs(mntpt, &statfsbuf) < 0) {
257 			warn("%s", mntpt);
258 			rv = 1;
259 			continue;
260 		}
261 
262 		/*
263 		 * Check to make sure the arguments we've been given are
264 		 * satisfied.  Return an error if we have been asked to
265 		 * list a mount point that does not match the other args
266 		 * we've been given (-l, -t, etc.).
267 		 */
268 		if (checkvfsname(statfsbuf.f_fstypename, vfslist)) {
269 			rv = 1;
270 			continue;
271 		}
272 
273 		/* the user asked for it, so ignore the ignore flag */
274 		statfsbuf.f_flags &= ~MNT_IGNORE;
275 
276 		/* add to list */
277 		mntbuf[mntsize++] = statfsbuf;
278 	}
279 
280 	bzero(&maxwidths, sizeof(maxwidths));
281 	for (i = 0; i < mntsize; i++) {
282 		if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0) {
283 			update_maxwidths(&maxwidths, &mntbuf[i]);
284 			if (cflag)
285 				addstat(&totalbuf, &mntbuf[i]);
286 		}
287 	}
288 	for (i = 0; i < mntsize; i++)
289 		if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
290 			prtstat(&mntbuf[i], &maxwidths);
291 	if (cflag)
292 		prtstat(&totalbuf, &maxwidths);
293 	return (rv);
294 }
295 
296 static char *
297 getmntpt(const char *name)
298 {
299 	size_t mntsize, i;
300 	struct statfs *mntbuf;
301 
302 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
303 	for (i = 0; i < mntsize; i++) {
304 		if (!strcmp(mntbuf[i].f_mntfromname, name))
305 			return (mntbuf[i].f_mntonname);
306 	}
307 	return (0);
308 }
309 
310 /*
311  * Make a pass over the file system info in ``mntbuf'' filtering out
312  * file system types not in vfslist and possibly re-stating to get
313  * current (not cached) info.  Returns the new count of valid statfs bufs.
314  */
315 static size_t
316 regetmntinfo(struct statfs **mntbufp, long mntsize, const char **vfslist)
317 {
318 	int error, i, j;
319 	struct statfs *mntbuf;
320 
321 	if (vfslist == NULL)
322 		return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
323 
324 	mntbuf = *mntbufp;
325 	for (j = 0, i = 0; i < mntsize; i++) {
326 		if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
327 			continue;
328 		/*
329 		 * XXX statfs(2) can fail for various reasons. It may be
330 		 * possible that the user does not have access to the
331 		 * pathname, if this happens, we will fall back on
332 		 * "stale" filesystem statistics.
333 		 */
334 		error = statfs(mntbuf[i].f_mntonname, &mntbuf[j]);
335 		if (nflag || error < 0)
336 			if (i != j) {
337 				if (error < 0)
338 					warnx("%s stats possibly stale",
339 					    mntbuf[i].f_mntonname);
340 				mntbuf[j] = mntbuf[i];
341 			}
342 		j++;
343 	}
344 	return (j);
345 }
346 
347 static void
348 prthuman(const struct statfs *sfsp, int64_t used)
349 {
350 
351 	prthumanval(sfsp->f_blocks * sfsp->f_bsize);
352 	prthumanval(used * sfsp->f_bsize);
353 	prthumanval(sfsp->f_bavail * sfsp->f_bsize);
354 }
355 
356 static void
357 prthumanval(int64_t bytes)
358 {
359 	char buf[6];
360 	int flags;
361 
362 	flags = HN_B | HN_NOSPACE | HN_DECIMAL;
363 	if (hflag == UNITS_SI)
364 		flags |= HN_DIVISOR_1000;
365 
366 	humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
367 	    bytes, "", HN_AUTOSCALE, flags);
368 
369 	(void)printf("  %6s", buf);
370 }
371 
372 /*
373  * Print an inode count in "human-readable" format.
374  */
375 static void
376 prthumanvalinode(int64_t bytes)
377 {
378 	char buf[6];
379 	int flags;
380 
381 	flags = HN_NOSPACE | HN_DECIMAL | HN_DIVISOR_1000;
382 
383 	humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
384 	    bytes, "", HN_AUTOSCALE, flags);
385 
386 	(void)printf(" %5s", buf);
387 }
388 
389 /*
390  * Convert statfs returned file system size into BLOCKSIZE units.
391  * Attempts to avoid overflow for large file systems.
392  */
393 static intmax_t
394 fsbtoblk(int64_t num, uint64_t fsbs, u_long bs)
395 {
396 
397 	if (fsbs != 0 && fsbs < bs)
398 		return (num / (intmax_t)(bs / fsbs));
399 	else
400 		return (num * (intmax_t)(fsbs / bs));
401 }
402 
403 /*
404  * Print out status about a file system.
405  */
406 static void
407 prtstat(struct statfs *sfsp, struct maxwidths *mwp)
408 {
409 	static long blocksize;
410 	static int headerlen, timesthrough = 0;
411 	static const char *header;
412 	int64_t used, availblks, inodes;
413 
414 	if (++timesthrough == 1) {
415 		mwp->mntfrom = imax(mwp->mntfrom, (int)strlen("Filesystem"));
416 		mwp->fstype = imax(mwp->fstype, (int)strlen("Type"));
417 		if (hflag) {
418 			header = "   Size";
419 			mwp->total = mwp->used = mwp->avail =
420 			    (int)strlen(header);
421 		} else {
422 			header = getbsize(&headerlen, &blocksize);
423 			mwp->total = imax(mwp->total, headerlen);
424 		}
425 		mwp->used = imax(mwp->used, (int)strlen("Used"));
426 		mwp->avail = imax(mwp->avail, (int)strlen("Avail"));
427 
428 		(void)printf("%-*s", mwp->mntfrom, "Filesystem");
429 		if (Tflag)
430 			(void)printf("  %-*s", mwp->fstype, "Type");
431 		(void)printf(" %-*s %*s %*s Capacity", mwp->total, header,
432 		    mwp->used, "Used", mwp->avail, "Avail");
433 		if (iflag) {
434 			mwp->iused = imax(hflag ? 0 : mwp->iused,
435 			    (int)strlen("  iused"));
436 			mwp->ifree = imax(hflag ? 0 : mwp->ifree,
437 			    (int)strlen("ifree"));
438 			(void)printf(" %*s %*s %%iused",
439 			    mwp->iused - 2, "iused", mwp->ifree, "ifree");
440 		}
441 		(void)printf("  Mounted on\n");
442 	}
443 	(void)printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
444 	if (Tflag)
445 		(void)printf("  %-*s", mwp->fstype, sfsp->f_fstypename);
446 	used = sfsp->f_blocks - sfsp->f_bfree;
447 	availblks = sfsp->f_bavail + used;
448 	if (hflag) {
449 		prthuman(sfsp, used);
450 	} else {
451 		(void)printf(" %*jd %*jd %*jd",
452 		    mwp->total, fsbtoblk(sfsp->f_blocks,
453 		    sfsp->f_bsize, blocksize),
454 		    mwp->used, fsbtoblk(used, sfsp->f_bsize, blocksize),
455 		    mwp->avail, fsbtoblk(sfsp->f_bavail,
456 		    sfsp->f_bsize, blocksize));
457 	}
458 	(void)printf(" %5.0f%%",
459 	    availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
460 	if (iflag) {
461 		inodes = sfsp->f_files;
462 		used = inodes - sfsp->f_ffree;
463 		if (hflag) {
464 			(void)printf("  ");
465 			prthumanvalinode(used);
466 			prthumanvalinode(sfsp->f_ffree);
467 		} else {
468 			(void)printf(" %*jd %*jd", mwp->iused, (intmax_t)used,
469 			    mwp->ifree, (intmax_t)sfsp->f_ffree);
470 		}
471 		(void)printf(" %4.0f%% ", inodes == 0 ? 100.0 :
472 		    (double)used / (double)inodes * 100.0);
473 	} else
474 		(void)printf("  ");
475 	if (strncmp(sfsp->f_mntfromname, "total", MNAMELEN) != 0)
476 		(void)printf("  %s", sfsp->f_mntonname);
477 	(void)printf("\n");
478 }
479 
480 static void
481 addstat(struct statfs *totalfsp, struct statfs *statfsp)
482 {
483 	uint64_t bsize;
484 
485 	bsize = statfsp->f_bsize / totalfsp->f_bsize;
486 	totalfsp->f_blocks += statfsp->f_blocks * bsize;
487 	totalfsp->f_bfree += statfsp->f_bfree * bsize;
488 	totalfsp->f_bavail += statfsp->f_bavail * bsize;
489 	totalfsp->f_files += statfsp->f_files;
490 	totalfsp->f_ffree += statfsp->f_ffree;
491 }
492 
493 /*
494  * Update the maximum field-width information in `mwp' based on
495  * the file system specified by `sfsp'.
496  */
497 static void
498 update_maxwidths(struct maxwidths *mwp, const struct statfs *sfsp)
499 {
500 	static long blocksize = 0;
501 	int dummy;
502 
503 	if (blocksize == 0)
504 		getbsize(&dummy, &blocksize);
505 
506 	mwp->mntfrom = imax(mwp->mntfrom, (int)strlen(sfsp->f_mntfromname));
507 	mwp->fstype = imax(mwp->fstype, (int)strlen(sfsp->f_fstypename));
508 	mwp->total = imax(mwp->total, int64width(
509 	    fsbtoblk((int64_t)sfsp->f_blocks, sfsp->f_bsize, blocksize)));
510 	mwp->used = imax(mwp->used,
511 	    int64width(fsbtoblk((int64_t)sfsp->f_blocks -
512 	    (int64_t)sfsp->f_bfree, sfsp->f_bsize, blocksize)));
513 	mwp->avail = imax(mwp->avail, int64width(fsbtoblk(sfsp->f_bavail,
514 	    sfsp->f_bsize, blocksize)));
515 	mwp->iused = imax(mwp->iused, int64width((int64_t)sfsp->f_files -
516 	    sfsp->f_ffree));
517 	mwp->ifree = imax(mwp->ifree, int64width(sfsp->f_ffree));
518 }
519 
520 /* Return the width in characters of the specified value. */
521 static int
522 int64width(int64_t val)
523 {
524 	int len;
525 
526 	len = 0;
527 	/* Negative or zero values require one extra digit. */
528 	if (val <= 0) {
529 		val = -val;
530 		len++;
531 	}
532 	while (val > 0) {
533 		len++;
534 		val /= 10;
535 	}
536 
537 	return (len);
538 }
539 
540 static void
541 usage(void)
542 {
543 
544 	(void)fprintf(stderr,
545 "usage: df [-b | -g | -H | -h | -k | -m | -P] [-acilnT] [-t type] [file | filesystem ...]\n");
546 	exit(EX_USAGE);
547 }
548 
549 static char *
550 makenetvfslist(void)
551 {
552 	char *str, *strptr, **listptr;
553 	struct xvfsconf *xvfsp, *keep_xvfsp;
554 	size_t buflen;
555 	int cnt, i, maxvfsconf;
556 
557 	if (sysctlbyname("vfs.conflist", NULL, &buflen, NULL, 0) < 0) {
558 		warn("sysctl(vfs.conflist)");
559 		return (NULL);
560 	}
561 	xvfsp = malloc(buflen);
562 	if (xvfsp == NULL) {
563 		warnx("malloc failed");
564 		return (NULL);
565 	}
566 	keep_xvfsp = xvfsp;
567 	if (sysctlbyname("vfs.conflist", xvfsp, &buflen, NULL, 0) < 0) {
568 		warn("sysctl(vfs.conflist)");
569 		free(keep_xvfsp);
570 		return (NULL);
571 	}
572 	maxvfsconf = buflen / sizeof(struct xvfsconf);
573 
574 	if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
575 		warnx("malloc failed");
576 		free(keep_xvfsp);
577 		return (NULL);
578 	}
579 
580 	for (cnt = 0, i = 0; i < maxvfsconf; i++) {
581 		if (xvfsp->vfc_flags & VFCF_NETWORK) {
582 			listptr[cnt++] = strdup(xvfsp->vfc_name);
583 			if (listptr[cnt-1] == NULL) {
584 				warnx("malloc failed");
585 				free(listptr);
586 				free(keep_xvfsp);
587 				return (NULL);
588 			}
589 		}
590 		xvfsp++;
591 	}
592 
593 	if (cnt == 0 ||
594 	    (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
595 		if (cnt > 0)
596 			warnx("malloc failed");
597 		free(listptr);
598 		free(keep_xvfsp);
599 		return (NULL);
600 	}
601 
602 	*str = 'n'; *(str + 1) = 'o';
603 	for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
604 		strlcpy(strptr, listptr[i], 32);
605 		strptr += strlen(listptr[i]);
606 		*strptr = ',';
607 		free(listptr[i]);
608 	}
609 	*(--strptr) = '\0';
610 
611 	free(keep_xvfsp);
612 	free(listptr);
613 	return (str);
614 }
615