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