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