Home | History | Annotate | Line # | Download | only in df
df.c revision 1.81
      1 /*	$NetBSD: df.c,v 1.81 2008/03/04 18:55:57 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.81 2008/03/04 18:55:57 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 <assert.h>
     57 #include <err.h>
     58 #include <errno.h>
     59 #include <fcntl.h>
     60 #include <util.h>
     61 #include <stdio.h>
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <unistd.h>
     65 
     66 extern char *strpct(u_long, u_long, u_int);
     67 
     68 int	 main(int, char *[]);
     69 int	 bread(off_t, void *, int);
     70 char	*getmntpt(char *);
     71 void	 prtstat(struct statvfs *, int);
     72 int	 selected(const char *, size_t);
     73 void	 maketypelist(char *);
     74 long	 regetmntinfo(struct statvfs **, long);
     75 void	 usage(void);
     76 void	 prthumanval(int64_t, const char *);
     77 void	 prthuman(struct statvfs *, int64_t, int64_t);
     78 const char *
     79 	strpct64(uint64_t, uint64_t, u_int);
     80 
     81 int	aflag, gflag, hflag, iflag, lflag, nflag, Pflag;
     82 long	usize = 0;
     83 char	**typelist = NULL;
     84 
     85 int
     86 main(int argc, char *argv[])
     87 {
     88 	struct stat stbuf;
     89 	struct statvfs *mntbuf;
     90 	long mntsize;
     91 	int ch, i, maxwidth, width;
     92 	char *mntpt;
     93 
     94 	while ((ch = getopt(argc, argv, "aGghiklmnPt:")) != -1)
     95 		switch (ch) {
     96 		case 'a':
     97 			aflag = 1;
     98 			break;
     99 		case 'g':
    100 			hflag = 0;
    101 			usize = 1024 * 1024 * 1024;
    102 			break;
    103 		case 'G':
    104 			gflag = 1;
    105 			break;
    106 		case 'h':
    107 			hflag = 1;
    108 			usize = 0;
    109 			break;
    110 		case 'i':
    111 			iflag = 1;
    112 			break;
    113 		case 'k':
    114 			hflag = 0;
    115 			usize = 1024;
    116 			break;
    117 		case 'l':
    118 			lflag = 1;
    119 			break;
    120 		case 'm':
    121 			hflag = 0;
    122 			usize = 1024 * 1024;
    123 			break;
    124 		case 'n':
    125 			nflag = 1;
    126 			break;
    127 		case 'P':
    128 			Pflag = 1;
    129 			break;
    130 		case 't':
    131 			if (typelist != NULL)
    132 				errx(EXIT_FAILURE,
    133 				    "only one -t option may be specified.");
    134 			maketypelist(optarg);
    135 			break;
    136 		case '?':
    137 		default:
    138 			usage();
    139 		}
    140 
    141 	if (gflag && (Pflag || iflag))
    142 		errx(EXIT_FAILURE,
    143 		    "only one of -G and -P or -i may be specified");
    144 	if (Pflag && iflag)
    145 		errx(EXIT_FAILURE,
    146 		    "only one of -P and -i may be specified");
    147 #if 0
    148 	/*
    149 	 * The block size cannot be checked until after getbsize() is called.
    150 	 */
    151 	if (Pflag && (hflag || (usize != 1024 && usize != 512)))
    152 		errx(EXIT_FAILURE,
    153 		    "non-standard block size incompatible with -P");
    154 #endif
    155 	argc -= optind;
    156 	argv += optind;
    157 
    158 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
    159 	if (mntsize == 0)
    160 		err(EXIT_FAILURE,
    161 		    "retrieving information on mounted file systems");
    162 
    163 	if (*argv == NULL) {
    164 		mntsize = regetmntinfo(&mntbuf, mntsize);
    165 	} else {
    166 		if ((mntbuf = malloc(argc * sizeof(*mntbuf))) == NULL)
    167 			err(EXIT_FAILURE, "can't allocate statvfs array");
    168 		mntsize = 0;
    169 		for (/*EMPTY*/; *argv != NULL; argv++) {
    170 			if (stat(*argv, &stbuf) < 0) {
    171 				if ((mntpt = getmntpt(*argv)) == 0) {
    172 					warn("%s", *argv);
    173 					continue;
    174 				}
    175 			} else if (S_ISBLK(stbuf.st_mode)) {
    176 				if ((mntpt = getmntpt(*argv)) == 0)
    177 					mntpt = *argv;
    178 			} else
    179 				mntpt = *argv;
    180 			/*
    181 			 * Statfs does not take a `wait' flag, so we cannot
    182 			 * implement nflag here.
    183 			 */
    184 			if (!statvfs(mntpt, &mntbuf[mntsize]))
    185 				if (lflag &&
    186 				    (mntbuf[mntsize].f_flag & MNT_LOCAL) == 0)
    187 					warnx("Warning: %s is not a local %s",
    188 					    *argv, "file system");
    189 				else if
    190 				    (!selected(mntbuf[mntsize].f_fstypename,
    191 					sizeof(mntbuf[mntsize].f_fstypename)))
    192 					warnx("Warning: %s mounted as a %s %s",
    193 					    *argv,
    194 					    mntbuf[mntsize].f_fstypename,
    195 					    "file system");
    196 				else
    197 					++mntsize;
    198 			else
    199 				warn("%s", *argv);
    200 		}
    201 	}
    202 
    203 	maxwidth = 0;
    204 	for (i = 0; i < mntsize; i++) {
    205 		width = (int)strlen(mntbuf[i].f_mntfromname);
    206 		if (width > maxwidth)
    207 			maxwidth = width;
    208 	}
    209 	for (i = 0; i < mntsize; i++)
    210 		prtstat(&mntbuf[i], maxwidth);
    211 	exit(0);
    212 	/* NOTREACHED */
    213 }
    214 
    215 char *
    216 getmntpt(char *name)
    217 {
    218 	long mntsize, i;
    219 	struct statvfs *mntbuf;
    220 
    221 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
    222 	for (i = 0; i < mntsize; i++) {
    223 		if (!strcmp(mntbuf[i].f_mntfromname, name))
    224 			return (mntbuf[i].f_mntonname);
    225 	}
    226 	return (0);
    227 }
    228 
    229 static enum { IN_LIST, NOT_IN_LIST } which;
    230 
    231 int
    232 selected(const char *type, size_t len)
    233 {
    234 	char **av;
    235 
    236 	/* If no type specified, it's always selected. */
    237 	if (typelist == NULL)
    238 		return (1);
    239 	for (av = typelist; *av != NULL; ++av)
    240 		if (!strncmp(type, *av, len))
    241 			return (which == IN_LIST ? 1 : 0);
    242 	return (which == IN_LIST ? 0 : 1);
    243 }
    244 
    245 void
    246 maketypelist(char *fslist)
    247 {
    248 	int i;
    249 	char *nextcp, **av;
    250 
    251 	if ((fslist == NULL) || (fslist[0] == '\0'))
    252 		errx(EXIT_FAILURE, "empty type list");
    253 
    254 	/*
    255 	 * XXX
    256 	 * Note: the syntax is "noxxx,yyy" for no xxx's and
    257 	 * no yyy's, not the more intuitive "noyyy,noyyy".
    258 	 */
    259 	if (fslist[0] == 'n' && fslist[1] == 'o') {
    260 		fslist += 2;
    261 		which = NOT_IN_LIST;
    262 	} else
    263 		which = IN_LIST;
    264 
    265 	/* Count the number of types. */
    266 	for (i = 1, nextcp = fslist;
    267 	    (nextcp = strchr(nextcp, ',')) != NULL; i++)
    268 		++nextcp;
    269 
    270 	/* Build an array of that many types. */
    271 	if ((av = typelist = malloc((i + 1) * sizeof(char *))) == NULL)
    272 		err(EXIT_FAILURE, "can't allocate type array");
    273 	av[0] = fslist;
    274 	for (i = 1, nextcp = fslist;
    275 	    (nextcp = strchr(nextcp, ',')) != NULL; i++) {
    276 		*nextcp = '\0';
    277 		av[i] = ++nextcp;
    278 	}
    279 	/* Terminate the array. */
    280 	av[i] = NULL;
    281 }
    282 
    283 /*
    284  * Make a pass over the filesystem info in ``mntbuf'' filtering out
    285  * filesystem types not in ``fsmask'' and possibly re-stating to get
    286  * current (not cached) info.  Returns the new count of valid statvfs bufs.
    287  */
    288 long
    289 regetmntinfo(struct statvfs **mntbufp, long mntsize)
    290 {
    291 	int i, j;
    292 	struct statvfs *mntbuf;
    293 
    294 	if (!lflag && typelist == NULL && aflag)
    295 		return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
    296 
    297 	mntbuf = *mntbufp;
    298 	j = 0;
    299 	for (i = 0; i < mntsize; i++) {
    300 		if (!aflag && (mntbuf[i].f_flag & MNT_IGNORE) != 0)
    301 			continue;
    302 		if (lflag && (mntbuf[i].f_flag & MNT_LOCAL) == 0)
    303 			continue;
    304 		if (!selected(mntbuf[i].f_fstypename,
    305 		    sizeof(mntbuf[i].f_fstypename)))
    306 			continue;
    307 		if (nflag)
    308 			mntbuf[j] = mntbuf[i];
    309 		else {
    310 			struct statvfs layerbuf = mntbuf[i];
    311 			(void)statvfs(mntbuf[i].f_mntonname, &mntbuf[j]);
    312 			/*
    313 			 * If the FS name changed, then new data is for
    314 			 * a different layer and we don't want it.
    315 			 */
    316 			if (memcmp(layerbuf.f_mntfromname,
    317 			    mntbuf[j].f_mntfromname, MNAMELEN))
    318 				mntbuf[j] = layerbuf;
    319 		}
    320 		j++;
    321 	}
    322 	return (j);
    323 }
    324 
    325 void
    326 prthumanval(int64_t bytes, const char *pad)
    327 {
    328 	char buf[6];
    329 
    330 	(void)humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
    331 	    bytes, "", HN_AUTOSCALE,
    332 	    HN_B | HN_NOSPACE | HN_DECIMAL);
    333 
    334 	(void)printf("%s %6s", pad, buf);
    335 }
    336 
    337 void
    338 prthuman(struct statvfs *sfsp, int64_t used, int64_t bavail)
    339 {
    340 
    341 	prthumanval((int64_t)(sfsp->f_blocks * sfsp->f_frsize), "  ");
    342 	prthumanval((int64_t)(used * sfsp->f_frsize), "    ");
    343 	prthumanval((int64_t)(bavail * sfsp->f_frsize), "    ");
    344 }
    345 
    346 /*
    347  * Convert statvfs returned filesystem size into BLOCKSIZE units.
    348  * Attempts to avoid overflow for large filesystems.
    349  */
    350 #define fsbtoblk(num, fsbs, bs)					\
    351 	(((fsbs) != 0 && (fsbs) < (bs)) ?			\
    352 	    (int64_t)(num) / (int64_t)((bs) / (fsbs)) :		\
    353 	    (int64_t)(num) * ((fsbs) / (bs)))
    354 
    355 /*
    356  * Print out status about a filesystem.
    357  */
    358 void
    359 prtstat(struct statvfs *sfsp, int maxwidth)
    360 {
    361 	static long blocksize;
    362 	static int headerlen, timesthrough;
    363 	static const char *header;
    364 	static const char full[] = "100%";
    365 	static const char empty[] = "  0%";
    366 	int64_t used, availblks, inodes;
    367 	int64_t bavail;
    368 
    369 	if (gflag) {
    370 		/*
    371 		 * From SunOS-5.6:
    372 		 *
    373 		 * /var               (/dev/dsk/c0t0d0s3 ):         8192 block size          1024 frag size
    374 		 *   984242 total blocks     860692 free blocks   859708 available         249984 total files
    375 		 *   248691 free files      8388611 filesys id
    376 		 *      ufs fstype       0x00000004 flag             255 filename length
    377 		 *
    378 		 */
    379 		(void)printf("%10s (%-12s): %7ld block size %12ld frag size\n",
    380 		    sfsp->f_mntonname, sfsp->f_mntfromname,
    381 		    sfsp->f_iosize,	/* On UFS/FFS systems this is
    382 					 * also called the "optimal
    383 					 * transfer block size" but it
    384 					 * is of course the file
    385 					 * system's block size too.
    386 					 */
    387 		    sfsp->f_bsize);	/* not so surprisingly the
    388 					 * "fundamental file system
    389 					 * block size" is the frag
    390 					 * size.
    391 					 */
    392 		(void)printf("%10" PRId64 " total blocks %10" PRId64
    393 		    " free blocks  %10" PRId64 " available\n",
    394 		    (uint64_t)sfsp->f_blocks, (uint64_t)sfsp->f_bfree,
    395 		    (uint64_t)sfsp->f_bavail);
    396 		(void)printf("%10" PRId64 " total files  %10" PRId64
    397 		    " free files %12lx filesys id\n",
    398 		    (uint64_t)sfsp->f_ffree, (uint64_t)sfsp->f_files,
    399 		    sfsp->f_fsid);
    400 		(void)printf("%10s fstype  %#15lx flag  %17ld filename "
    401 		    "length\n", sfsp->f_fstypename, sfsp->f_flag,
    402 		    sfsp->f_namemax);
    403 		(void)printf("%10lu owner %17" PRId64 " syncwrites %12" PRId64
    404 		    " asyncwrites\n\n", (unsigned long)sfsp->f_owner,
    405 		    sfsp->f_syncwrites, sfsp->f_asyncwrites);
    406 
    407 		/*
    408 		 * a concession by the structured programming police to the
    409 		 * indentation police....
    410 		 */
    411 		return;
    412 	}
    413 	if (maxwidth < 12)
    414 		maxwidth = 12;
    415 	if (++timesthrough == 1) {
    416 		switch (blocksize = usize) {
    417 		case 1024:
    418 			header = Pflag ? "1024-blocks" : "1K-blocks";
    419 			headerlen = (int)strlen(header);
    420 			break;
    421 		case 1024 * 1024:
    422 			header = "1M-blocks";
    423 			headerlen = (int)strlen(header);
    424 			break;
    425 		case 1024 * 1024 * 1024:
    426 			header = "1G-blocks";
    427 			headerlen = (int)strlen(header);
    428 			break;
    429 		default:
    430 			if (hflag) {
    431 				header = "Size";
    432 				headerlen = (int)strlen(header);
    433 			} else
    434 				header = getbsize(&headerlen, &blocksize);
    435 			break;
    436 		}
    437 		if (Pflag) {
    438 			/*
    439 			 * either:
    440 			 *  "Filesystem 1024-blocks Used Available Capacity Mounted on\n"
    441 			 * or:
    442 			 *  "Filesystem 512-blocks Used Available Capacity Mounted on\n"
    443 			 */
    444 			if (blocksize != 1024 && blocksize != 512)
    445 				errx(EXIT_FAILURE,
    446 				    "non-standard block size incompatible with -P");
    447 			(void)printf("Filesystem %s Used Available Capacity "
    448 			    "Mounted on\n", header);
    449 		} else {
    450 			(void)printf("%-*.*s %s       Used      Avail %%Cap",
    451 			    maxwidth - (headerlen - 9),
    452 			    maxwidth - (headerlen - 9),
    453 			    "Filesystem", header);
    454 			if (iflag)
    455 				(void)printf("    iUsed   iAvail %%iCap");
    456 			(void)printf(" Mounted on\n");
    457 		}
    458 	}
    459 	used = sfsp->f_blocks - sfsp->f_bfree;
    460 	bavail = sfsp->f_bfree - sfsp->f_bresvd;
    461 	availblks = bavail + used;
    462 	if (Pflag) {
    463 		assert(hflag == 0);
    464 		assert(blocksize > 0);
    465 		/*
    466 		 * "%s %d %d %d %s %s\n", <file system name>, <total space>,
    467 		 * <space used>, <space free>, <percentage used>,
    468 		 * <file system root>
    469 		 */
    470 		(void)printf("%s %" PRId64 " %" PRId64 " %" PRId64 " %s %s\n",
    471 		    sfsp->f_mntfromname,
    472 		    fsbtoblk(sfsp->f_blocks, sfsp->f_bsize, blocksize),
    473 		    fsbtoblk(used, sfsp->f_bsize, blocksize),
    474 		    fsbtoblk(sfsp->f_bavail, sfsp->f_bsize, blocksize),
    475 		    availblks == 0 ? full : strpct64((uint64_t) used,
    476 		    (uint64_t) availblks, 0), sfsp->f_mntonname);
    477 		/*
    478 		 * another concession by the structured programming police to
    479 		 * the indentation police....
    480 		 *
    481 		 * Note iflag cannot be set when Pflag is set.
    482 		 */
    483 		return;
    484 	}
    485 
    486 	(void)printf("%-*.*s ", maxwidth, maxwidth, sfsp->f_mntfromname);
    487 
    488 	if (hflag)
    489 		prthuman(sfsp, used, bavail);
    490 	else
    491 		(void)printf("%10" PRId64 " %10" PRId64 " %10" PRId64,
    492 		    fsbtoblk(sfsp->f_blocks, sfsp->f_frsize, blocksize),
    493 		    fsbtoblk(used, sfsp->f_frsize, blocksize),
    494 		    fsbtoblk(bavail, sfsp->f_frsize, blocksize));
    495 	(void)printf(" %4s",
    496 	    availblks == 0 ? full :
    497 	    /* We know that these values are never negative */
    498 	    strpct64((uint64_t)used, (uint64_t)availblks, 0));
    499 	if (iflag) {
    500 		inodes = sfsp->f_files;
    501 		used = inodes - sfsp->f_ffree;
    502 		(void)printf(" %8jd %8jd %4s",
    503 		    (intmax_t)used, (intmax_t)sfsp->f_ffree,
    504 		    inodes == 0 ? (used == 0 ? empty : full) :
    505 		    strpct64((uint64_t)used, (uint64_t)inodes, 0));
    506 	}
    507 	(void)printf(" %s\n", sfsp->f_mntonname);
    508 }
    509 
    510 void
    511 usage(void)
    512 {
    513 
    514 	(void)fprintf(stderr,
    515 	    "Usage: %s [-aGgln] [-hkm|-ihkm|-Pk] [-t type] [file | "
    516 	    "file_system ...]\n",
    517 	    getprogname());
    518 	exit(1);
    519 	/* NOTREACHED */
    520 }
    521 
    522 const char *
    523 strpct64(uint64_t numerator, uint64_t denominator, u_int digits)
    524 {
    525 
    526 	while (denominator > ULONG_MAX) {
    527 		numerator >>= 1;
    528 		denominator >>= 1;
    529 	}
    530 	return (strpct((u_long)numerator, (u_long)denominator, digits));
    531 }
    532