xref: /netbsd/bin/df/df.c (revision bf9ec67e)
1 /*	$NetBSD: df.c,v 1.42 2001/10/11 16:31:33 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. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #include <sys/cdefs.h>
42 #ifndef lint
43 __COPYRIGHT(
44 "@(#) Copyright (c) 1980, 1990, 1993, 1994\n\
45 	The Regents of the University of California.  All rights reserved.\n");
46 #endif /* not lint */
47 
48 #ifndef lint
49 #if 0
50 static char sccsid[] = "@(#)df.c	8.7 (Berkeley) 4/2/94";
51 #else
52 __RCSID("$NetBSD: df.c,v 1.42 2001/10/11 16:31:33 christos Exp $");
53 #endif
54 #endif /* not lint */
55 
56 #include <sys/param.h>
57 #include <sys/stat.h>
58 #include <sys/mount.h>
59 
60 #include <ufs/ufs/ufsmount.h>
61 
62 #include <err.h>
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 
70 extern char *strpct(u_long, u_long, u_int);
71 
72 int	 main(int, char *[]);
73 int	 bread(off_t, void *, int);
74 char	*getmntpt(char *);
75 void	 prtstat(struct statfs *, int);
76 int	 ufs_df(char *, struct statfs *);
77 int	 selected(const char *);
78 void	 maketypelist(char *);
79 long	 regetmntinfo(struct statfs **, long);
80 void	 usage(void);
81 
82 int	aflag, iflag, kflag, lflag, mflag, nflag, Pflag;
83 char	**typelist = NULL;
84 struct	ufs_args mdev;
85 
86 int
87 main(int argc, char *argv[])
88 {
89 	struct stat stbuf;
90 	struct statfs *mntbuf;
91 	long mntsize;
92 	int ch, i, maxwidth, width;
93 	char *mntpt;
94 
95 	while ((ch = getopt(argc, argv, "aiklmnPt:")) != -1)
96 		switch (ch) {
97 		case 'a':
98 			aflag = 1;
99 			break;
100 		case 'i':
101 			iflag = 1;
102 			break;
103 		case 'k':
104 			kflag = 1;
105 			break;
106 		case 'l':
107 			lflag = 1;
108 			break;
109 		case 'm':
110 			mflag = 1;
111 			break;
112 		case 'n':
113 			nflag = 1;
114 			break;
115 		case 'P':
116 			Pflag = 1;
117 			break;
118 		case 't':
119 			if (typelist != NULL)
120 				errx(1, "only one -t option may be specified.");
121 			maketypelist(optarg);
122 			break;
123 		case '?':
124 		default:
125 			usage();
126 		}
127 	argc -= optind;
128 	argv += optind;
129 
130 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
131 	if (mntsize == 0)
132 		err(1, "retrieving information on mounted file systems");
133 
134 	if (*argv == NULL) {
135 		mntsize = regetmntinfo(&mntbuf, mntsize);
136 	} else {
137 		mntbuf = malloc(argc * sizeof(struct statfs));
138 		mntsize = 0;
139 		for (; *argv != NULL; argv++) {
140 			if (stat(*argv, &stbuf) < 0) {
141 				if ((mntpt = getmntpt(*argv)) == 0) {
142 					warn("%s", *argv);
143 					continue;
144 				}
145 			} else if (S_ISCHR(stbuf.st_mode)) {
146 				if (!ufs_df(*argv, &mntbuf[mntsize]))
147 					++mntsize;
148 				continue;
149 			} else if (S_ISBLK(stbuf.st_mode)) {
150 				if ((mntpt = getmntpt(*argv)) == 0) {
151 					mntpt = strdup("/tmp/df.XXXXXX");
152 					if (!mkdtemp(mntpt)) {
153 						warn("%s", mntpt);
154 						continue;
155 					}
156 					mdev.fspec = *argv;
157 					if (mount(MOUNT_FFS, mntpt, MNT_RDONLY,
158 					    &mdev) != 0) {
159 						(void)rmdir(mntpt);
160 						if (!ufs_df(*argv,
161 						    &mntbuf[mntsize]))
162 							++mntsize;
163 						continue;
164 					} else if (!statfs(mntpt,
165 					    &mntbuf[mntsize])) {
166 						mntbuf[mntsize].f_mntonname[0] =
167 						    '\0';
168 						++mntsize;
169 					} else
170 						warn("%s", *argv);
171 					(void)unmount(mntpt, 0);
172 					(void)rmdir(mntpt);
173 					continue;
174 				}
175 			} else
176 				mntpt = *argv;
177 			/*
178 			 * Statfs does not take a `wait' flag, so we cannot
179 			 * implement nflag here.
180 			 */
181 			if (!statfs(mntpt, &mntbuf[mntsize]))
182 				if (lflag &&
183 				    (mntbuf[mntsize].f_flags & MNT_LOCAL) == 0)
184 					warnx("Warning: %s is not a local %s",
185 					    *argv, "file system");
186 				else if
187 				    (!selected(mntbuf[mntsize].f_fstypename))
188 					warnx("Warning: %s mounted as a %s %s",
189 					    *argv,
190 					    mntbuf[mntsize].f_fstypename,
191 					    "file system");
192 				else
193 					++mntsize;
194 			else
195 				warn("%s", *argv);
196 		}
197 	}
198 
199 	maxwidth = 0;
200 	for (i = 0; i < mntsize; i++) {
201 		width = strlen(mntbuf[i].f_mntfromname);
202 		if (width > maxwidth)
203 			maxwidth = width;
204 	}
205 	for (i = 0; i < mntsize; i++)
206 		prtstat(&mntbuf[i], maxwidth);
207 	exit(0);
208 	/* NOTREACHED */
209 }
210 
211 char *
212 getmntpt(char *name)
213 {
214 	long mntsize, i;
215 	struct statfs *mntbuf;
216 
217 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
218 	for (i = 0; i < mntsize; i++) {
219 		if (!strcmp(mntbuf[i].f_mntfromname, name))
220 			return (mntbuf[i].f_mntonname);
221 	}
222 	return (0);
223 }
224 
225 static enum { IN_LIST, NOT_IN_LIST } which;
226 
227 int
228 selected(const char *type)
229 {
230 	char **av;
231 
232 	/* If no type specified, it's always selected. */
233 	if (typelist == NULL)
234 		return (1);
235 	for (av = typelist; *av != NULL; ++av)
236 		if (!strncmp(type, *av, MFSNAMELEN))
237 			return (which == IN_LIST ? 1 : 0);
238 	return (which == IN_LIST ? 0 : 1);
239 }
240 
241 void
242 maketypelist(char *fslist)
243 {
244 	int i;
245 	char *nextcp, **av;
246 
247 	if ((fslist == NULL) || (fslist[0] == '\0'))
248 		errx(1, "empty type list");
249 
250 	/*
251 	 * XXX
252 	 * Note: the syntax is "noxxx,yyy" for no xxx's and
253 	 * no yyy's, not the more intuitive "noyyy,noyyy".
254 	 */
255 	if (fslist[0] == 'n' && fslist[1] == 'o') {
256 		fslist += 2;
257 		which = NOT_IN_LIST;
258 	} else
259 		which = IN_LIST;
260 
261 	/* Count the number of types. */
262 	for (i = 1, nextcp = fslist;
263 	    (nextcp = strchr(nextcp, ',')) != NULL; i++)
264 		++nextcp;
265 
266 	/* Build an array of that many types. */
267 	if ((av = typelist = malloc((i + 1) * sizeof(char *))) == NULL)
268 		err(1, "can't allocate type array");
269 	av[0] = fslist;
270 	for (i = 1, nextcp = fslist;
271 	    (nextcp = strchr(nextcp, ',')) != NULL; i++) {
272 		*nextcp = '\0';
273 		av[i] = ++nextcp;
274 	}
275 	/* Terminate the array. */
276 	av[i] = NULL;
277 }
278 
279 /*
280  * Make a pass over the filesystem info in ``mntbuf'' filtering out
281  * filesystem types not in ``fsmask'' and possibly re-stating to get
282  * current (not cached) info.  Returns the new count of valid statfs bufs.
283  */
284 long
285 regetmntinfo(struct statfs **mntbufp, long mntsize)
286 {
287 	int i, j;
288 	struct statfs *mntbuf;
289 
290 	if (!lflag && typelist == NULL && aflag)
291 		return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
292 
293 	mntbuf = *mntbufp;
294 	j = 0;
295 	for (i = 0; i < mntsize; i++) {
296 		if (!aflag && (mntbuf[i].f_flags & MNT_IGNORE) != 0)
297 			continue;
298 		if (lflag && (mntbuf[i].f_flags & MNT_LOCAL) == 0)
299 			continue;
300 		if (!selected(mntbuf[i].f_fstypename))
301 			continue;
302 		if (nflag)
303 			mntbuf[j] = mntbuf[i];
304 		else {
305 			struct statfs layerbuf = mntbuf[i];
306 			(void)statfs(mntbuf[i].f_mntonname, &mntbuf[j]);
307 			/*
308 			 * If the FS name changed, then new data is for
309 			 * a different layer and we don't want it.
310 			 */
311 			if (memcmp(layerbuf.f_mntfromname,
312 			    mntbuf[j].f_mntfromname, MNAMELEN))
313 				mntbuf[j] = layerbuf;
314 		}
315 		j++;
316 	}
317 	return (j);
318 }
319 
320 /*
321  * Convert statfs returned filesystem size into BLOCKSIZE units.
322  * Attempts to avoid overflow for large filesystems.
323  */
324 #define fsbtoblk(num, fsbs, bs)					\
325 	(((fsbs) != 0 && (fsbs) < (bs)) ?			\
326 	    (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
327 
328 /*
329  * Print out status about a filesystem.
330  */
331 void
332 prtstat(struct statfs *sfsp, int maxwidth)
333 {
334 	static long blocksize;
335 	static int headerlen, timesthrough;
336 	static char *header;
337 	long used, availblks, inodes;
338 	static char *full = "100%";
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
352 			header = getbsize(&headerlen, &blocksize);
353 		(void)printf("%-*.*s %s     Used %9s Capacity",
354 		    maxwidth, maxwidth, "Filesystem", header,
355 		    Pflag ? "Available" : "Avail");
356 		if (iflag)
357 			(void)printf(" iused   ifree  %%iused");
358 		(void)printf("  Mounted on\n");
359 	}
360 	(void)printf("%-*.*s", maxwidth, maxwidth, sfsp->f_mntfromname);
361 	used = sfsp->f_blocks - sfsp->f_bfree;
362 	availblks = sfsp->f_bavail + used;
363 	(void)printf(" %*ld %8ld %9ld", headerlen,
364 	    fsbtoblk(sfsp->f_blocks, sfsp->f_bsize, blocksize),
365 	    fsbtoblk(used, sfsp->f_bsize, blocksize),
366 	    fsbtoblk(sfsp->f_bavail, sfsp->f_bsize, blocksize));
367 	(void)printf("%7s",
368 	    availblks == 0 ? full : strpct((u_long)used, (u_long)availblks, 0));
369 	if (iflag) {
370 		inodes = sfsp->f_files;
371 		used = inodes - sfsp->f_ffree;
372 		(void)printf(" %7ld %7ld %6s ", used, sfsp->f_ffree,
373 		    inodes == 0 ? full :
374 		    strpct((u_long)used, (u_long)inodes, 0));
375 	} else
376 		(void)printf("  ");
377 	(void)printf("  %s\n", sfsp->f_mntonname);
378 }
379 
380 /*
381  * This code constitutes the pre-system call Berkeley df code for extracting
382  * information from filesystem superblocks.
383  */
384 #include <ufs/ufs/dinode.h>
385 #include <ufs/ffs/fs.h>
386 #include <errno.h>
387 #include <fstab.h>
388 
389 union {
390 	struct fs iu_fs;
391 	char dummy[SBSIZE];
392 } sb;
393 #define sblock sb.iu_fs
394 
395 int	rfd;
396 
397 int
398 ufs_df(char *file, struct statfs *sfsp)
399 {
400 	char *mntpt;
401 	static int synced;
402 
403 	if (synced++ == 0)
404 		sync();
405 
406 	if ((rfd = open(file, O_RDONLY)) < 0) {
407 		warn("%s", file);
408 		return (-1);
409 	}
410 	if (bread((off_t)SBOFF, &sblock, SBSIZE) == 0) {
411 		(void)close(rfd);
412 		return (-1);
413 	}
414 	sfsp->f_type = 0;
415 	sfsp->f_flags = 0;
416 	sfsp->f_bsize = sblock.fs_fsize;
417 	sfsp->f_iosize = sblock.fs_bsize;
418 	sfsp->f_blocks = sblock.fs_dsize;
419 	sfsp->f_bfree = sblock.fs_cstotal.cs_nbfree * sblock.fs_frag +
420 	    sblock.fs_cstotal.cs_nffree;
421 	sfsp->f_bavail =
422 	    ((int64_t)sblock.fs_dsize * (100 - sblock.fs_minfree) / 100) -
423 	    (sblock.fs_dsize - sfsp->f_bfree);
424 	if (sfsp->f_bavail < 0)
425 		sfsp->f_bavail = 0;
426 	sfsp->f_files = sblock.fs_ncg * sblock.fs_ipg;
427 	sfsp->f_ffree = sblock.fs_cstotal.cs_nifree;
428 	sfsp->f_fsid.val[0] = 0;
429 	sfsp->f_fsid.val[1] = 0;
430 	if ((mntpt = getmntpt(file)) == 0)
431 		mntpt = "";
432 	(void)memmove(&sfsp->f_mntonname[0], mntpt, MNAMELEN);
433 	(void)memmove(&sfsp->f_mntfromname[0], file, MNAMELEN);
434 	(void)strncpy(sfsp->f_fstypename, MOUNT_FFS, MFSNAMELEN);
435 	(void)close(rfd);
436 	return (0);
437 }
438 
439 int
440 bread(off, buf, cnt)
441 	off_t off;
442 	void *buf;
443 	int cnt;
444 {
445 	int nr;
446 
447 	(void)lseek(rfd, off, SEEK_SET);
448 	if ((nr = read(rfd, buf, cnt)) != cnt) {
449 		/* Probably a dismounted disk if errno == EIO. */
450 		if (errno != EIO)
451 			(void)fprintf(stderr, "\ndf: %lld: %s\n",
452 			    (long long)off, strerror(nr > 0 ? EIO : errno));
453 		return (0);
454 	}
455 	return (1);
456 }
457 
458 void
459 usage(void)
460 {
461 
462 	(void)fprintf(stderr,
463 	    "Usage: %s [-aiklmnP] [-t type] [file | file_system ...]\n",
464 	    getprogname());
465 	exit(1);
466 	/* NOTREACHED */
467 }
468