xref: /freebsd/bin/df/df.c (revision 595e514d0df2bac5b813d35f83e32875dbf16a83)
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 <locale.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sysexits.h>
62 #include <unistd.h>
63 
64 #include "extern.h"
65 
66 #define UNITS_SI	1
67 #define UNITS_2		2
68 
69 /* Maximum widths of various fields. */
70 struct maxwidths {
71 	int	mntfrom;
72 	int	fstype;
73 	int	total;
74 	int	used;
75 	int	avail;
76 	int	iused;
77 	int	ifree;
78 };
79 
80 static void	  addstat(struct statfs *, struct statfs *);
81 static char	 *getmntpt(const char *);
82 static int	  int64width(int64_t);
83 static char	 *makenetvfslist(void);
84 static void	  prthuman(const struct statfs *, int64_t);
85 static void	  prthumanval(int64_t);
86 static intmax_t	  fsbtoblk(int64_t, uint64_t, u_long);
87 static void	  prtstat(struct statfs *, struct maxwidths *);
88 static size_t	  regetmntinfo(struct statfs **, long, const char **);
89 static void	  update_maxwidths(struct maxwidths *, const struct statfs *);
90 static void	  usage(void);
91 
92 static __inline int
93 imax(int a, int b)
94 {
95 	return (a > b ? a : b);
96 }
97 
98 static int	aflag = 0, cflag, hflag, iflag, kflag, lflag = 0, nflag, Tflag;
99 static int	thousands;
100 static struct	ufs_args mdev;
101 
102 int
103 main(int argc, char *argv[])
104 {
105 	struct stat stbuf;
106 	struct statfs statfsbuf, totalbuf;
107 	struct maxwidths maxwidths;
108 	struct statfs *mntbuf;
109 	const char *fstype;
110 	char *mntpath, *mntpt;
111 	const char **vfslist;
112 	int i, mntsize;
113 	int ch, rv;
114 
115 	fstype = "ufs";
116 	(void)setlocale(LC_ALL, "");
117 	memset(&maxwidths, 0, sizeof(maxwidths));
118 	memset(&totalbuf, 0, sizeof(totalbuf));
119 	totalbuf.f_bsize = DEV_BSIZE;
120 	strlcpy(totalbuf.f_mntfromname, "total", MNAMELEN);
121 	vfslist = NULL;
122 	while ((ch = getopt(argc, argv, "abcgHhiklmnPt:T,")) != -1)
123 		switch (ch) {
124 		case 'a':
125 			aflag = 1;
126 			break;
127 		case 'b':
128 				/* FALLTHROUGH */
129 		case 'P':
130 			/*
131 			 * POSIX specifically discusses the behavior of
132 			 * both -k and -P. It states that the blocksize should
133 			 * be set to 1024. Thus, if this occurs, simply break
134 			 * rather than clobbering the old blocksize.
135 			 */
136 			if (kflag)
137 				break;
138 			setenv("BLOCKSIZE", "512", 1);
139 			hflag = 0;
140 			break;
141 		case 'c':
142 			cflag = 1;
143 			break;
144 		case 'g':
145 			setenv("BLOCKSIZE", "1g", 1);
146 			hflag = 0;
147 			break;
148 		case 'H':
149 			hflag = UNITS_SI;
150 			break;
151 		case 'h':
152 			hflag = UNITS_2;
153 			break;
154 		case 'i':
155 			iflag = 1;
156 			break;
157 		case 'k':
158 			kflag++;
159 			setenv("BLOCKSIZE", "1024", 1);
160 			hflag = 0;
161 			break;
162 		case 'l':
163 			if (vfslist != NULL)
164 				errx(1, "-l and -t are mutually exclusive.");
165 			vfslist = makevfslist(makenetvfslist());
166 			lflag = 1;
167 			break;
168 		case 'm':
169 			setenv("BLOCKSIZE", "1m", 1);
170 			hflag = 0;
171 			break;
172 		case 'n':
173 			nflag = 1;
174 			break;
175 		case 't':
176 			if (lflag)
177 				errx(1, "-l and -t are mutually exclusive.");
178 			if (vfslist != NULL)
179 				errx(1, "only one -t option may be specified");
180 			fstype = optarg;
181 			vfslist = makevfslist(optarg);
182 			break;
183 		case 'T':
184 			Tflag = 1;
185 			break;
186 		case ',':
187 			thousands = 1;
188 			break;
189 		case '?':
190 		default:
191 			usage();
192 		}
193 	argc -= optind;
194 	argv += optind;
195 
196 	rv = 0;
197 	if (!*argv) {
198 		/* everything (modulo -t) */
199 		mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
200 		mntsize = regetmntinfo(&mntbuf, mntsize, vfslist);
201 	} else {
202 		/* just the filesystems specified on the command line */
203 		mntbuf = malloc(argc * sizeof(*mntbuf));
204 		if (mntbuf == NULL)
205 			err(1, "malloc()");
206 		mntsize = 0;
207 		/* continued in for loop below */
208 	}
209 
210 	/* iterate through specified filesystems */
211 	for (; *argv; argv++) {
212 		if (stat(*argv, &stbuf) < 0) {
213 			if ((mntpt = getmntpt(*argv)) == NULL) {
214 				warn("%s", *argv);
215 				rv = 1;
216 				continue;
217 			}
218 		} else if (S_ISCHR(stbuf.st_mode)) {
219 			if ((mntpt = getmntpt(*argv)) == NULL) {
220 				mdev.fspec = *argv;
221 				mntpath = strdup("/tmp/df.XXXXXX");
222 				if (mntpath == NULL) {
223 					warn("strdup failed");
224 					rv = 1;
225 					continue;
226 				}
227 				mntpt = mkdtemp(mntpath);
228 				if (mntpt == NULL) {
229 					warn("mkdtemp(\"%s\") failed", mntpath);
230 					rv = 1;
231 					free(mntpath);
232 					continue;
233 				}
234 				if (mount(fstype, mntpt, MNT_RDONLY,
235 				    &mdev) != 0) {
236 					warn("%s", *argv);
237 					rv = 1;
238 					(void)rmdir(mntpt);
239 					free(mntpath);
240 					continue;
241 				} else if (statfs(mntpt, &statfsbuf) == 0) {
242 					statfsbuf.f_mntonname[0] = '\0';
243 					prtstat(&statfsbuf, &maxwidths);
244 					if (cflag)
245 						addstat(&totalbuf, &statfsbuf);
246 				} else {
247 					warn("%s", *argv);
248 					rv = 1;
249 				}
250 				(void)unmount(mntpt, 0);
251 				(void)rmdir(mntpt);
252 				free(mntpath);
253 				continue;
254 			}
255 		} else
256 			mntpt = *argv;
257 
258 		/*
259 		 * Statfs does not take a `wait' flag, so we cannot
260 		 * implement nflag here.
261 		 */
262 		if (statfs(mntpt, &statfsbuf) < 0) {
263 			warn("%s", mntpt);
264 			rv = 1;
265 			continue;
266 		}
267 
268 		/*
269 		 * Check to make sure the arguments we've been given are
270 		 * satisfied.  Return an error if we have been asked to
271 		 * list a mount point that does not match the other args
272 		 * we've been given (-l, -t, etc.).
273 		 */
274 		if (checkvfsname(statfsbuf.f_fstypename, vfslist)) {
275 			rv = 1;
276 			continue;
277 		}
278 
279 		/* the user asked for it, so ignore the ignore flag */
280 		statfsbuf.f_flags &= ~MNT_IGNORE;
281 
282 		/* add to list */
283 		mntbuf[mntsize++] = statfsbuf;
284 	}
285 
286 	memset(&maxwidths, 0, sizeof(maxwidths));
287 	for (i = 0; i < mntsize; i++) {
288 		if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0) {
289 			update_maxwidths(&maxwidths, &mntbuf[i]);
290 			if (cflag)
291 				addstat(&totalbuf, &mntbuf[i]);
292 		}
293 	}
294 	for (i = 0; i < mntsize; i++)
295 		if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
296 			prtstat(&mntbuf[i], &maxwidths);
297 	if (cflag)
298 		prtstat(&totalbuf, &maxwidths);
299 	return (rv);
300 }
301 
302 static char *
303 getmntpt(const char *name)
304 {
305 	size_t mntsize, i;
306 	struct statfs *mntbuf;
307 
308 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
309 	for (i = 0; i < mntsize; i++) {
310 		if (!strcmp(mntbuf[i].f_mntfromname, name))
311 			return (mntbuf[i].f_mntonname);
312 	}
313 	return (NULL);
314 }
315 
316 /*
317  * Make a pass over the file system info in ``mntbuf'' filtering out
318  * file system types not in vfslist and possibly re-stating to get
319  * current (not cached) info.  Returns the new count of valid statfs bufs.
320  */
321 static size_t
322 regetmntinfo(struct statfs **mntbufp, long mntsize, const char **vfslist)
323 {
324 	int error, i, j;
325 	struct statfs *mntbuf;
326 
327 	if (vfslist == NULL)
328 		return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
329 
330 	mntbuf = *mntbufp;
331 	for (j = 0, i = 0; i < mntsize; i++) {
332 		if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
333 			continue;
334 		/*
335 		 * XXX statfs(2) can fail for various reasons. It may be
336 		 * possible that the user does not have access to the
337 		 * pathname, if this happens, we will fall back on
338 		 * "stale" filesystem statistics.
339 		 */
340 		error = statfs(mntbuf[i].f_mntonname, &mntbuf[j]);
341 		if (nflag || error < 0)
342 			if (i != j) {
343 				if (error < 0)
344 					warnx("%s stats possibly stale",
345 					    mntbuf[i].f_mntonname);
346 				mntbuf[j] = mntbuf[i];
347 			}
348 		j++;
349 	}
350 	return (j);
351 }
352 
353 static void
354 prthuman(const struct statfs *sfsp, int64_t used)
355 {
356 
357 	prthumanval(sfsp->f_blocks * sfsp->f_bsize);
358 	prthumanval(used * sfsp->f_bsize);
359 	prthumanval(sfsp->f_bavail * sfsp->f_bsize);
360 }
361 
362 static void
363 prthumanval(int64_t bytes)
364 {
365 	char buf[6];
366 	int flags;
367 
368 	flags = HN_B | HN_NOSPACE | HN_DECIMAL;
369 	if (hflag == UNITS_SI)
370 		flags |= HN_DIVISOR_1000;
371 
372 	humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
373 	    bytes, "", HN_AUTOSCALE, flags);
374 
375 	(void)printf("  %6s", buf);
376 }
377 
378 /*
379  * Print an inode count in "human-readable" format.
380  */
381 static void
382 prthumanvalinode(int64_t bytes)
383 {
384 	char buf[6];
385 	int flags;
386 
387 	flags = HN_NOSPACE | HN_DECIMAL | HN_DIVISOR_1000;
388 
389 	humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
390 	    bytes, "", HN_AUTOSCALE, flags);
391 
392 	(void)printf(" %5s", buf);
393 }
394 
395 /*
396  * Convert statfs returned file system size into BLOCKSIZE units.
397  */
398 static intmax_t
399 fsbtoblk(int64_t num, uint64_t fsbs, u_long bs)
400 {
401 	return (num * (intmax_t) fsbs / (int64_t) bs);
402 }
403 
404 /*
405  * Print out status about a file system.
406  */
407 static void
408 prtstat(struct statfs *sfsp, struct maxwidths *mwp)
409 {
410 	static long blocksize;
411 	static int headerlen, timesthrough = 0;
412 	static const char *header;
413 	int64_t used, availblks, inodes;
414 	const char *format;
415 
416 	if (++timesthrough == 1) {
417 		mwp->mntfrom = imax(mwp->mntfrom, (int)strlen("Filesystem"));
418 		mwp->fstype = imax(mwp->fstype, (int)strlen("Type"));
419 		if (thousands) {		/* make space for commas */
420 		    mwp->total += (mwp->total - 1) / 3;
421 		    mwp->used  += (mwp->used - 1) / 3;
422 		    mwp->avail += (mwp->avail - 1) / 3;
423 		    mwp->iused += (mwp->iused - 1) / 3;
424 		    mwp->ifree += (mwp->ifree - 1) / 3;
425 		}
426 		if (hflag) {
427 			header = "   Size";
428 			mwp->total = mwp->used = mwp->avail =
429 			    (int)strlen(header);
430 		} else {
431 			header = getbsize(&headerlen, &blocksize);
432 			mwp->total = imax(mwp->total, headerlen);
433 		}
434 		mwp->used = imax(mwp->used, (int)strlen("Used"));
435 		mwp->avail = imax(mwp->avail, (int)strlen("Avail"));
436 
437 		(void)printf("%-*s", mwp->mntfrom, "Filesystem");
438 		if (Tflag)
439 			(void)printf("  %-*s", mwp->fstype, "Type");
440 		(void)printf(" %*s %*s %*s Capacity", mwp->total, header,
441 		    mwp->used, "Used", mwp->avail, "Avail");
442 		if (iflag) {
443 			mwp->iused = imax(hflag ? 0 : mwp->iused,
444 			    (int)strlen("  iused"));
445 			mwp->ifree = imax(hflag ? 0 : mwp->ifree,
446 			    (int)strlen("ifree"));
447 			(void)printf(" %*s %*s %%iused",
448 			    mwp->iused - 2, "iused", mwp->ifree, "ifree");
449 		}
450 		(void)printf("  Mounted on\n");
451 	}
452 	/* Check for 0 block size.  Can this happen? */
453 	if (sfsp->f_bsize == 0) {
454 		warnx ("File system %s does not have a block size, assuming 512.",
455 		    sfsp->f_mntonname);
456 		sfsp->f_bsize = 512;
457 	}
458 	(void)printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
459 	if (Tflag)
460 		(void)printf("  %-*s", mwp->fstype, sfsp->f_fstypename);
461 	used = sfsp->f_blocks - sfsp->f_bfree;
462 	availblks = sfsp->f_bavail + used;
463 	if (hflag) {
464 		prthuman(sfsp, used);
465 	} else {
466 		if (thousands)
467 		    format = " %*j'd %*j'd %*j'd";
468 		else
469 		    format = " %*jd %*jd %*jd";
470 		(void)printf(format,
471 		    mwp->total, fsbtoblk(sfsp->f_blocks,
472 		    sfsp->f_bsize, blocksize),
473 		    mwp->used, fsbtoblk(used, sfsp->f_bsize, blocksize),
474 		    mwp->avail, fsbtoblk(sfsp->f_bavail,
475 		    sfsp->f_bsize, blocksize));
476 	}
477 	(void)printf(" %5.0f%%",
478 	    availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
479 	if (iflag) {
480 		inodes = sfsp->f_files;
481 		used = inodes - sfsp->f_ffree;
482 		if (hflag) {
483 			(void)printf("  ");
484 			prthumanvalinode(used);
485 			prthumanvalinode(sfsp->f_ffree);
486 		} else {
487 			if (thousands)
488 			    format = " %*j'd %*j'd";
489 			else
490 			    format = " %*jd %*jd";
491 			(void)printf(format, mwp->iused, (intmax_t)used,
492 			    mwp->ifree, (intmax_t)sfsp->f_ffree);
493 		}
494 		(void)printf(" %4.0f%% ", inodes == 0 ? 100.0 :
495 		    (double)used / (double)inodes * 100.0);
496 	} else
497 		(void)printf("  ");
498 	if (strncmp(sfsp->f_mntfromname, "total", MNAMELEN) != 0)
499 		(void)printf("  %s", sfsp->f_mntonname);
500 	(void)printf("\n");
501 }
502 
503 static void
504 addstat(struct statfs *totalfsp, struct statfs *statfsp)
505 {
506 	uint64_t bsize;
507 
508 	bsize = statfsp->f_bsize / totalfsp->f_bsize;
509 	totalfsp->f_blocks += statfsp->f_blocks * bsize;
510 	totalfsp->f_bfree += statfsp->f_bfree * bsize;
511 	totalfsp->f_bavail += statfsp->f_bavail * bsize;
512 	totalfsp->f_files += statfsp->f_files;
513 	totalfsp->f_ffree += statfsp->f_ffree;
514 }
515 
516 /*
517  * Update the maximum field-width information in `mwp' based on
518  * the file system specified by `sfsp'.
519  */
520 static void
521 update_maxwidths(struct maxwidths *mwp, const struct statfs *sfsp)
522 {
523 	static long blocksize = 0;
524 	int dummy;
525 
526 	if (blocksize == 0)
527 		getbsize(&dummy, &blocksize);
528 
529 	mwp->mntfrom = imax(mwp->mntfrom, (int)strlen(sfsp->f_mntfromname));
530 	mwp->fstype = imax(mwp->fstype, (int)strlen(sfsp->f_fstypename));
531 	mwp->total = imax(mwp->total, int64width(
532 	    fsbtoblk((int64_t)sfsp->f_blocks, sfsp->f_bsize, blocksize)));
533 	mwp->used = imax(mwp->used,
534 	    int64width(fsbtoblk((int64_t)sfsp->f_blocks -
535 	    (int64_t)sfsp->f_bfree, sfsp->f_bsize, blocksize)));
536 	mwp->avail = imax(mwp->avail, int64width(fsbtoblk(sfsp->f_bavail,
537 	    sfsp->f_bsize, blocksize)));
538 	mwp->iused = imax(mwp->iused, int64width((int64_t)sfsp->f_files -
539 	    sfsp->f_ffree));
540 	mwp->ifree = imax(mwp->ifree, int64width(sfsp->f_ffree));
541 }
542 
543 /* Return the width in characters of the specified value. */
544 static int
545 int64width(int64_t val)
546 {
547 	int len;
548 
549 	len = 0;
550 	/* Negative or zero values require one extra digit. */
551 	if (val <= 0) {
552 		val = -val;
553 		len++;
554 	}
555 	while (val > 0) {
556 		len++;
557 		val /= 10;
558 	}
559 
560 	return (len);
561 }
562 
563 static void
564 usage(void)
565 {
566 
567 	(void)fprintf(stderr,
568 "usage: df [-b | -g | -H | -h | -k | -m | -P] [-acilnT] [-t type] [-,]\n"
569 "          [file | filesystem ...]\n");
570 	exit(EX_USAGE);
571 }
572 
573 static char *
574 makenetvfslist(void)
575 {
576 	char *str, *strptr, **listptr;
577 	struct xvfsconf *xvfsp, *keep_xvfsp;
578 	size_t buflen;
579 	int cnt, i, maxvfsconf;
580 
581 	if (sysctlbyname("vfs.conflist", NULL, &buflen, NULL, 0) < 0) {
582 		warn("sysctl(vfs.conflist)");
583 		return (NULL);
584 	}
585 	xvfsp = malloc(buflen);
586 	if (xvfsp == NULL) {
587 		warnx("malloc failed");
588 		return (NULL);
589 	}
590 	keep_xvfsp = xvfsp;
591 	if (sysctlbyname("vfs.conflist", xvfsp, &buflen, NULL, 0) < 0) {
592 		warn("sysctl(vfs.conflist)");
593 		free(keep_xvfsp);
594 		return (NULL);
595 	}
596 	maxvfsconf = buflen / sizeof(struct xvfsconf);
597 
598 	if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
599 		warnx("malloc failed");
600 		free(keep_xvfsp);
601 		return (NULL);
602 	}
603 
604 	for (cnt = 0, i = 0; i < maxvfsconf; i++) {
605 		if (xvfsp->vfc_flags & VFCF_NETWORK) {
606 			listptr[cnt++] = strdup(xvfsp->vfc_name);
607 			if (listptr[cnt-1] == NULL) {
608 				warnx("malloc failed");
609 				free(listptr);
610 				free(keep_xvfsp);
611 				return (NULL);
612 			}
613 		}
614 		xvfsp++;
615 	}
616 
617 	if (cnt == 0 ||
618 	    (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
619 		if (cnt > 0)
620 			warnx("malloc failed");
621 		free(listptr);
622 		free(keep_xvfsp);
623 		return (NULL);
624 	}
625 
626 	*str = 'n'; *(str + 1) = 'o';
627 	for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
628 		strlcpy(strptr, listptr[i], 32);
629 		strptr += strlen(listptr[i]);
630 		*strptr = ',';
631 		free(listptr[i]);
632 	}
633 	*(--strptr) = '\0';
634 
635 	free(keep_xvfsp);
636 	free(listptr);
637 	return (str);
638 }
639