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