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