xref: /netbsd-src/bin/df/df.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: df.c,v 1.68 2005/06/26 19:10:49 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1980, 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #ifndef lint
39 __COPYRIGHT(
40 "@(#) Copyright (c) 1980, 1990, 1993, 1994\n\
41 	The Regents of the University of California.  All rights reserved.\n");
42 #endif /* not lint */
43 
44 #ifndef lint
45 #if 0
46 static char sccsid[] = "@(#)df.c	8.7 (Berkeley) 4/2/94";
47 #else
48 __RCSID("$NetBSD: df.c,v 1.68 2005/06/26 19:10:49 christos Exp $");
49 #endif
50 #endif /* not lint */
51 
52 #include <sys/param.h>
53 #include <sys/stat.h>
54 #include <sys/mount.h>
55 
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <util.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 extern char *strpct(u_long, u_long, u_int);
66 
67 int	 main(int, char *[]);
68 int	 bread(off_t, void *, int);
69 char	*getmntpt(char *);
70 void	 prtstat(struct statvfs *, int);
71 int	 selected(const char *);
72 void	 maketypelist(char *);
73 long	 regetmntinfo(struct statvfs **, long);
74 void	 usage(void);
75 void	 prthumanval(int64_t, const char *);
76 void	 prthuman(struct statvfs *, int64_t, int64_t);
77 const char *
78 	strpct64(uint64_t, uint64_t, u_int);
79 
80 int	aflag, gflag, hflag, iflag, kflag, lflag, mflag, nflag, Pflag;
81 char	**typelist = NULL;
82 
83 int
84 main(int argc, char *argv[])
85 {
86 	struct stat stbuf;
87 	struct statvfs *mntbuf;
88 	long mntsize;
89 	int ch, i, maxwidth, width;
90 	char *mntpt;
91 
92 	while ((ch = getopt(argc, argv, "aghiklmnPt:")) != -1)
93 		switch (ch) {
94 		case 'a':
95 			aflag = 1;
96 			break;
97 		case 'g':
98 			gflag = 1;
99 			break;
100 		case 'h':
101 			hflag = 1;
102 			break;
103 		case 'i':
104 			iflag = 1;
105 			break;
106 		case 'k':
107 			kflag = 1;
108 			break;
109 		case 'l':
110 			lflag = 1;
111 			break;
112 		case 'm':
113 			mflag = 1;
114 			break;
115 		case 'n':
116 			nflag = 1;
117 			break;
118 		case 'P':
119 			Pflag = 1;
120 			break;
121 		case 't':
122 			if (typelist != NULL)
123 				errx(1, "only one -t option may be specified.");
124 			maketypelist(optarg);
125 			break;
126 		case '?':
127 		default:
128 			usage();
129 		}
130 	argc -= optind;
131 	argv += optind;
132 
133 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
134 	if (mntsize == 0)
135 		err(1, "retrieving information on mounted file systems");
136 
137 	if (*argv == NULL) {
138 		mntsize = regetmntinfo(&mntbuf, mntsize);
139 	} else {
140 		mntbuf = malloc(argc * sizeof(*mntbuf));
141 		mntsize = 0;
142 		for (; *argv != NULL; argv++) {
143 			if (stat(*argv, &stbuf) < 0) {
144 				if ((mntpt = getmntpt(*argv)) == 0) {
145 					warn("%s", *argv);
146 					continue;
147 				}
148 			} else if (S_ISBLK(stbuf.st_mode)) {
149 				if ((mntpt = getmntpt(*argv)) == 0)
150 					mntpt = *argv;
151 			} else
152 				mntpt = *argv;
153 			/*
154 			 * Statfs does not take a `wait' flag, so we cannot
155 			 * implement nflag here.
156 			 */
157 			if (!statvfs(mntpt, &mntbuf[mntsize]))
158 				if (lflag &&
159 				    (mntbuf[mntsize].f_flag & MNT_LOCAL) == 0)
160 					warnx("Warning: %s is not a local %s",
161 					    *argv, "file system");
162 				else if
163 				    (!selected(mntbuf[mntsize].f_fstypename))
164 					warnx("Warning: %s mounted as a %s %s",
165 					    *argv,
166 					    mntbuf[mntsize].f_fstypename,
167 					    "file system");
168 				else
169 					++mntsize;
170 			else
171 				warn("%s", *argv);
172 		}
173 	}
174 
175 	maxwidth = 0;
176 	for (i = 0; i < mntsize; i++) {
177 		width = strlen(mntbuf[i].f_mntfromname);
178 		if (width > maxwidth)
179 			maxwidth = width;
180 	}
181 	for (i = 0; i < mntsize; i++)
182 		prtstat(&mntbuf[i], maxwidth);
183 	exit(0);
184 	/* NOTREACHED */
185 }
186 
187 char *
188 getmntpt(char *name)
189 {
190 	long mntsize, i;
191 	struct statvfs *mntbuf;
192 
193 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
194 	for (i = 0; i < mntsize; i++) {
195 		if (!strcmp(mntbuf[i].f_mntfromname, name))
196 			return (mntbuf[i].f_mntonname);
197 	}
198 	return (0);
199 }
200 
201 static enum { IN_LIST, NOT_IN_LIST } which;
202 
203 int
204 selected(const char *type)
205 {
206 	char **av;
207 
208 	/* If no type specified, it's always selected. */
209 	if (typelist == NULL)
210 		return (1);
211 	for (av = typelist; *av != NULL; ++av)
212 		if (!strncmp(type, *av, MFSNAMELEN))
213 			return (which == IN_LIST ? 1 : 0);
214 	return (which == IN_LIST ? 0 : 1);
215 }
216 
217 void
218 maketypelist(char *fslist)
219 {
220 	int i;
221 	char *nextcp, **av;
222 
223 	if ((fslist == NULL) || (fslist[0] == '\0'))
224 		errx(1, "empty type list");
225 
226 	/*
227 	 * XXX
228 	 * Note: the syntax is "noxxx,yyy" for no xxx's and
229 	 * no yyy's, not the more intuitive "noyyy,noyyy".
230 	 */
231 	if (fslist[0] == 'n' && fslist[1] == 'o') {
232 		fslist += 2;
233 		which = NOT_IN_LIST;
234 	} else
235 		which = IN_LIST;
236 
237 	/* Count the number of types. */
238 	for (i = 1, nextcp = fslist;
239 	    (nextcp = strchr(nextcp, ',')) != NULL; i++)
240 		++nextcp;
241 
242 	/* Build an array of that many types. */
243 	if ((av = typelist = malloc((i + 1) * sizeof(char *))) == NULL)
244 		err(1, "can't allocate type array");
245 	av[0] = fslist;
246 	for (i = 1, nextcp = fslist;
247 	    (nextcp = strchr(nextcp, ',')) != NULL; i++) {
248 		*nextcp = '\0';
249 		av[i] = ++nextcp;
250 	}
251 	/* Terminate the array. */
252 	av[i] = NULL;
253 }
254 
255 /*
256  * Make a pass over the filesystem info in ``mntbuf'' filtering out
257  * filesystem types not in ``fsmask'' and possibly re-stating to get
258  * current (not cached) info.  Returns the new count of valid statvfs bufs.
259  */
260 long
261 regetmntinfo(struct statvfs **mntbufp, long mntsize)
262 {
263 	int i, j;
264 	struct statvfs *mntbuf;
265 
266 	if (!lflag && typelist == NULL && aflag)
267 		return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
268 
269 	mntbuf = *mntbufp;
270 	j = 0;
271 	for (i = 0; i < mntsize; i++) {
272 		if (!aflag && (mntbuf[i].f_flag & MNT_IGNORE) != 0)
273 			continue;
274 		if (lflag && (mntbuf[i].f_flag & MNT_LOCAL) == 0)
275 			continue;
276 		if (!selected(mntbuf[i].f_fstypename))
277 			continue;
278 		if (nflag)
279 			mntbuf[j] = mntbuf[i];
280 		else {
281 			struct statvfs layerbuf = mntbuf[i];
282 			(void)statvfs(mntbuf[i].f_mntonname, &mntbuf[j]);
283 			/*
284 			 * If the FS name changed, then new data is for
285 			 * a different layer and we don't want it.
286 			 */
287 			if (memcmp(layerbuf.f_mntfromname,
288 			    mntbuf[j].f_mntfromname, MNAMELEN))
289 				mntbuf[j] = layerbuf;
290 		}
291 		j++;
292 	}
293 	return (j);
294 }
295 
296 void
297 prthumanval(int64_t bytes, const char *pad)
298 {
299 	char buf[6];
300 
301 	humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
302 	    bytes, "", HN_AUTOSCALE,
303 	    HN_B | HN_NOSPACE | HN_DECIMAL);
304 
305 	(void)printf("%s %6s", pad, buf);
306 }
307 
308 void
309 prthuman(struct statvfs *sfsp, int64_t used, int64_t bavail)
310 {
311 
312 	prthumanval(sfsp->f_blocks * sfsp->f_frsize, "");
313 	prthumanval(used * sfsp->f_frsize, "  ");
314 	prthumanval(bavail * sfsp->f_frsize, "   ");
315 }
316 
317 /*
318  * Convert statvfs returned filesystem size into BLOCKSIZE units.
319  * Attempts to avoid overflow for large filesystems.
320  */
321 #define fsbtoblk(num, fsbs, bs)					\
322 	(((fsbs) != 0 && (fsbs) < (bs)) ?			\
323 	    (int64_t)(num) / (int64_t)((bs) / (fsbs)) :		\
324 	    (int64_t)(num) * ((fsbs) / (bs)))
325 
326 /*
327  * Print out status about a filesystem.
328  */
329 void
330 prtstat(struct statvfs *sfsp, int maxwidth)
331 {
332 	static long blocksize;
333 	static int headerlen, timesthrough;
334 	static const char *header;
335 	static const char full[] = "100%";
336 	static const char empty[] = "  0%";
337 	int64_t used, availblks, inodes;
338 	int64_t bavail;
339 
340 	if (maxwidth < 11)
341 		maxwidth = 11;
342 	if (++timesthrough == 1) {
343 		if (kflag) {
344 			blocksize = 1024;
345 			header = Pflag ? "1024-blocks" : "1K-blocks";
346 			headerlen = strlen(header);
347 		} else if (mflag) {
348 			blocksize = 1024 * 1024;
349 			header = Pflag ? "1048576-blocks" : "1M-blocks";
350 			headerlen = strlen(header);
351 		} else if (gflag) {
352 			blocksize = 1024 * 1024 * 1024;
353 			header = Pflag ? "1073741824-blocks" : "1G-blocks";
354 			headerlen = strlen(header);
355 		} else if (hflag) {
356 			header = "  Size";
357 			headerlen = strlen(header);
358 		} else
359 			header = getbsize(&headerlen, &blocksize);
360 		(void)printf("%-*.*s %s      Used %9s Capacity",
361 		    maxwidth, maxwidth, "Filesystem", header,
362 		    Pflag ? "Available" : "Avail");
363 		if (iflag)
364 			(void)printf("  iused    ifree  %%iused");
365 		(void)printf("  Mounted on\n");
366 	}
367 	(void)printf("%-*.*s", maxwidth, maxwidth, sfsp->f_mntfromname);
368 	used = sfsp->f_blocks - sfsp->f_bfree;
369 	bavail = sfsp->f_bfree - sfsp->f_bresvd;
370 	availblks = bavail + used;
371 	if (hflag)
372 		prthuman(sfsp, used, bavail);
373 	else
374 		(void)printf(" %*" PRId64 " %9" PRId64 " %9" PRId64, headerlen,
375 		    fsbtoblk(sfsp->f_blocks, sfsp->f_frsize, blocksize),
376 		    fsbtoblk(used, sfsp->f_frsize, blocksize),
377 		    fsbtoblk(bavail, sfsp->f_frsize, blocksize));
378 	(void)printf("%7s",
379 	    availblks == 0 ? full :
380 	    /* We know that these values are never negative */
381 	    strpct64((uint64_t)used, (uint64_t)availblks, 0));
382 	if (iflag) {
383 		inodes = sfsp->f_files;
384 		used = inodes - sfsp->f_ffree;
385 		(void)printf(" %8ld %8ld %6s ",
386 		    (u_long)used, (u_long)sfsp->f_ffree,
387 		    inodes == 0 ? (used == 0 ? empty : full) :
388 		    strpct64((uint64_t)used, (uint64_t)inodes, 0));
389 	} else
390 		(void)printf("  ");
391 	(void)printf("  %s\n", sfsp->f_mntonname);
392 }
393 
394 void
395 usage(void)
396 {
397 
398 	(void)fprintf(stderr,
399 	    "usage: %s [-aghiklmnP] [-t type] [file | file_system ...]\n",
400 	    getprogname());
401 	exit(1);
402 	/* NOTREACHED */
403 }
404 
405 const char *
406 strpct64(uint64_t numerator, uint64_t denominator, u_int digits)
407 {
408 
409 	while (denominator > ULONG_MAX) {
410 		numerator >>= 1;
411 		denominator >>= 1;
412 	}
413 	return (strpct((u_long)numerator, (u_long)denominator, digits));
414 }
415