file_cmds-220.4.tar.gz
[apple/file_cmds.git] / df / df.c
1 /*
2 * Copyright (c) 1980, 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39 #ifndef lint
40 static const char copyright[] =
41 "@(#) Copyright (c) 1980, 1990, 1993, 1994\n\
42 The Regents of the University of California. All rights reserved.\n";
43 #endif /* not lint */
44
45 #ifndef lint
46 #if 0
47 static char sccsid[] = "@(#)df.c 8.9 (Berkeley) 5/8/95";
48 #else
49 static const char rcsid[] =
50 "$FreeBSD: src/bin/df/df.c,v 1.23.2.9 2002/07/01 00:14:24 iedowse Exp $";
51 #endif
52 #endif /* not lint */
53
54 #ifdef __APPLE__
55 #define MNT_IGNORE 0
56 #endif
57
58 #include <sys/cdefs.h>
59 #include <sys/param.h>
60 #include <sys/stat.h>
61 #include <sys/mount.h>
62 #include <sys/sysctl.h>
63 #include <err.h>
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <fstab.h>
67 #include <math.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <sysexits.h>
72 #include <unistd.h>
73 #include <libutil.h>
74
75 #ifdef __APPLE__
76 #include "get_compat.h"
77 #else
78 #define COMPAT_MODE(func, mode) 1
79 #endif
80
81 #define UNITS_SI 1
82 #define UNITS_2 2
83
84 #define KILO_SZ(n) (n)
85 #define MEGA_SZ(n) ((n) * (n))
86 #define GIGA_SZ(n) ((n) * (n) * (n))
87 #define TERA_SZ(n) ((n) * (n) * (n) * (n))
88 #define PETA_SZ(n) ((n) * (n) * (n) * (n) * (n))
89
90 #define KILO_2_SZ (KILO_SZ(1024ULL))
91 #define MEGA_2_SZ (MEGA_SZ(1024ULL))
92 #define GIGA_2_SZ (GIGA_SZ(1024ULL))
93 #define TERA_2_SZ (TERA_SZ(1024ULL))
94 #define PETA_2_SZ (PETA_SZ(1024ULL))
95
96 #define KILO_SI_SZ (KILO_SZ(1000ULL))
97 #define MEGA_SI_SZ (MEGA_SZ(1000ULL))
98 #define GIGA_SI_SZ (GIGA_SZ(1000ULL))
99 #define TERA_SI_SZ (TERA_SZ(1000ULL))
100 #define PETA_SI_SZ (PETA_SZ(1000ULL))
101
102 /* Maximum widths of various fields. */
103 struct maxwidths {
104 int mntfrom;
105 int total;
106 int used;
107 int avail;
108 int iused;
109 int ifree;
110 };
111
112 unsigned long long vals_si [] = {1, KILO_SI_SZ, MEGA_SI_SZ, GIGA_SI_SZ, TERA_SI_SZ, PETA_SI_SZ};
113 unsigned long long vals_base2[] = {1, KILO_2_SZ, MEGA_2_SZ, GIGA_2_SZ, TERA_2_SZ, PETA_2_SZ};
114 unsigned long long *valp;
115
116 typedef enum { NONE, KILO, MEGA, GIGA, TERA, PETA, UNIT_MAX } unit_t;
117
118 unit_t unitp [] = { NONE, KILO, MEGA, GIGA, TERA, PETA };
119
120 int bread(off_t, void *, int);
121 int checkvfsname(const char *, char **);
122 char *getmntpt(char *);
123 int longwidth(long long);
124 char *makenetvfslist(void);
125 char **makevfslist(const char *);
126 void prthuman(struct statfs *, uint64_t);
127 void prthumanval(int64_t);
128 void prtstat(struct statfs *, struct maxwidths *);
129 long regetmntinfo(struct statfs **, long, char **);
130 unit_t unit_adjust(double *);
131 void update_maxwidths(struct maxwidths *, struct statfs *);
132 void usage(void);
133
134 int aflag = 0, hflag, iflag, nflag;
135
136 static __inline int imax(int a, int b)
137 {
138 return (a > b ? a : b);
139 }
140
141 int
142 main(int argc, char *argv[])
143 {
144 struct stat stbuf;
145 struct statfs statfsbuf, *mntbuf;
146 struct maxwidths maxwidths;
147 char *mntpt, **vfslist;
148 long mntsize;
149 int ch, i, rv, tflag = 0, kludge_tflag = 0;
150 int kflag = 0;
151 const char *options = "abgHhiklmnPt:T:";
152 if (COMPAT_MODE("bin/df", "unix2003")) {
153 /* Unix2003 requires -t be "include total capacity". which df
154 already does, but it conflicts with the old -t so we need to
155 *not* expect a string after -t (we provide -T in both cases
156 to cover the old use of -t) */
157 options = "abgHhiklmnPtT:";
158 iflag = 1;
159 }
160
161 vfslist = NULL;
162 while ((ch = getopt(argc, argv, options)) != -1)
163 switch (ch) {
164 case 'a':
165 aflag = 1;
166 break;
167 case 'b':
168 /* FALLTHROUGH */
169 case 'P':
170 if (COMPAT_MODE("bin/df", "unix2003")) {
171 if (!kflag) {
172 /* -k overrides -P */
173 putenv("BLOCKSIZE=512");
174 }
175 } else {
176 putenv("BLOCKSIZE=512");
177 }
178 hflag = 0;
179 break;
180 case 'g':
181 putenv("BLOCKSIZE=1g");
182 hflag = 0;
183 break;
184 case 'H':
185 hflag = UNITS_SI;
186 valp = vals_si;
187 break;
188 case 'h':
189 hflag = UNITS_2;
190 valp = vals_base2;
191 break;
192 case 'i':
193 iflag = 1;
194 break;
195 case 'k':
196 if (COMPAT_MODE("bin/df", "unix2003")) {
197 putenv("BLOCKSIZE=1024");
198 } else {
199 putenv("BLOCKSIZE=1k");
200 }
201 kflag = 1;
202 hflag = 0;
203 break;
204 case 'l':
205 if (tflag)
206 errx(1, "-l and -T are mutually exclusive.");
207 if (vfslist != NULL)
208 break;
209 vfslist = makevfslist(makenetvfslist());
210 break;
211 case 'm':
212 putenv("BLOCKSIZE=1m");
213 hflag = 0;
214 break;
215 case 'n':
216 nflag = 1;
217 break;
218 case 't':
219 /* Unix2003 uses -t for something we do by default */
220 if (COMPAT_MODE("bin/df", "unix2003")) {
221 kludge_tflag = 1;
222 break;
223 }
224 case 'T':
225 if (vfslist != NULL) {
226 if (tflag)
227 errx(1, "only one -%c option may be specified", ch);
228 else
229 errx(1, "-l and -%c are mutually exclusive.", ch);
230 }
231 tflag++;
232 vfslist = makevfslist(optarg);
233 break;
234 case '?':
235 default:
236 usage();
237 }
238 argc -= optind;
239 argv += optind;
240
241 /* If we are in unix2003 mode, have seen a -t but no -T and the first
242 non switch arg isn't a file, let's pretend they used -T on it.
243 This makes the Lexmark printer installer happy (PR-3918471) */
244 if (tflag == 0 && kludge_tflag && *argv && stat(*argv, &stbuf) < 0
245 && errno == ENOENT) {
246 vfslist = makevfslist(*argv++);
247 }
248
249 mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
250 bzero(&maxwidths, sizeof(maxwidths));
251 for (i = 0; i < mntsize; i++)
252 update_maxwidths(&maxwidths, &mntbuf[i]);
253
254 rv = 0;
255 if (!*argv) {
256 mntsize = regetmntinfo(&mntbuf, mntsize, vfslist);
257 bzero(&maxwidths, sizeof(maxwidths));
258 for (i = 0; i < mntsize; i++)
259 update_maxwidths(&maxwidths, &mntbuf[i]);
260 for (i = 0; i < mntsize; i++) {
261 if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
262 prtstat(&mntbuf[i], &maxwidths);
263 }
264 exit(rv);
265 }
266
267 for (; *argv; argv++) {
268 if (stat(*argv, &stbuf) < 0) {
269 if ((mntpt = getmntpt(*argv)) == 0) {
270 warn("%s", *argv);
271 rv = 1;
272 continue;
273 }
274 } else if (S_ISCHR(stbuf.st_mode) || S_ISBLK(stbuf.st_mode)) {
275 warnx("%s: Raw devices not supported", *argv);
276 rv = 1;
277 continue;
278 } else
279 mntpt = *argv;
280 /*
281 * Statfs does not take a `wait' flag, so we cannot
282 * implement nflag here.
283 */
284 if (statfs(mntpt, &statfsbuf) < 0) {
285 warn("%s", mntpt);
286 rv = 1;
287 continue;
288 }
289 /* Check to make sure the arguments we've been
290 * given are satisfied. Return an error if we
291 * have been asked to list a mount point that does
292 * not match the other args we've been given (-l, -t, etc.)
293 */
294 if (checkvfsname(statfsbuf.f_fstypename, vfslist)) {
295 rv++;
296 continue;
297 }
298
299 if (argc == 1) {
300 bzero(&maxwidths, sizeof(maxwidths));
301 update_maxwidths(&maxwidths, &statfsbuf);
302 }
303 prtstat(&statfsbuf, &maxwidths);
304 }
305 return (rv);
306 }
307
308 char *
309 getmntpt(char *name)
310 {
311 long mntsize, i;
312 struct statfs *mntbuf;
313
314 mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
315 for (i = 0; i < mntsize; i++) {
316 if (!strcmp(mntbuf[i].f_mntfromname, name))
317 return (mntbuf[i].f_mntonname);
318 }
319 return (0);
320 }
321
322 /*
323 * Make a pass over the filesystem info in ``mntbuf'' filtering out
324 * filesystem types not in vfslist and possibly re-stating to get
325 * current (not cached) info. Returns the new count of valid statfs bufs.
326 */
327 long
328 regetmntinfo(struct statfs **mntbufp, long mntsize, char **vfslist)
329 {
330 int i, j;
331 struct statfs *mntbuf;
332
333 if (vfslist == NULL)
334 return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
335
336 mntbuf = *mntbufp;
337 for (j = 0, i = 0; i < mntsize; i++) {
338 if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
339 continue;
340 if (!nflag)
341 (void)statfs(mntbuf[i].f_mntonname,&mntbuf[j]);
342 else if (i != j)
343 mntbuf[j] = mntbuf[i];
344 j++;
345 }
346 return (j);
347 }
348
349 /*
350 * Output in "human-readable" format. Uses 3 digits max and puts
351 * unit suffixes at the end. Makes output compact and easy to read,
352 * especially on huge disks.
353 *
354 */
355 unit_t
356 unit_adjust(double *val)
357 {
358 double abval;
359 unit_t unit;
360 unsigned int unit_sz;
361
362 abval = fabs(*val);
363
364 unit_sz = abval ? ilogb(abval) / 10 : 0;
365
366 if (unit_sz >= UNIT_MAX) {
367 unit = NONE;
368 } else {
369 unit = unitp[unit_sz];
370 *val /= (double)valp[unit_sz];
371 }
372
373 return (unit);
374 }
375
376 void
377 prthuman(struct statfs *sfsp, uint64_t used)
378 {
379 int64_t value;
380
381 value = sfsp->f_blocks;
382 value *= sfsp->f_bsize;
383 prthumanval(value);
384 value = used;
385 value *= sfsp->f_bsize;
386 prthumanval(value);
387 value = sfsp->f_bavail;
388 value *= sfsp->f_bsize;
389 prthumanval(value);
390 }
391
392 void
393 prthumanval(int64_t bytes)
394 {
395 char buf[6];
396 int flags;
397
398 flags = HN_B | HN_NOSPACE | HN_DECIMAL;
399 if (hflag == UNITS_SI)
400 flags |= HN_DIVISOR_1000;
401
402 humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
403 bytes, "", HN_AUTOSCALE, flags);
404
405 if (hflag == UNITS_SI)
406 (void)printf(" %6s", buf);
407 else
408 (void)printf("%6si", buf);
409
410 }
411
412 /*
413 * Convert statfs returned filesystem size into BLOCKSIZE units.
414 * Attempts to avoid overflow for large filesystems.
415 */
416 static intmax_t fsbtoblk(int64_t num, uint64_t fsbs, u_long bs, char *fs)
417 {
418 if (num < 0) {
419 warnx("negative filesystem block count/size from fs %s", fs);
420 return 0;
421 } else if ((fsbs != 0) && (fsbs < bs)) {
422 return (num / (intmax_t) (bs / fsbs));
423 } else {
424 return (num * (intmax_t) (fsbs / bs));
425 }
426 }
427
428 /*
429 * Print out status about a filesystem.
430 */
431 void
432 prtstat(struct statfs *sfsp, struct maxwidths *mwp)
433 {
434 static long blocksize;
435 static int headerlen, timesthrough;
436 static const char *header;
437 uint64_t used, availblks, inodes;
438 char * avail_str;
439
440 if (++timesthrough == 1) {
441 mwp->mntfrom = imax(mwp->mntfrom, (int)strlen("Filesystem"));
442 if (hflag) {
443 header = " Size";
444 mwp->total = mwp->used = mwp->avail = (int)strlen(header);
445 } else {
446 header = getbsize(&headerlen, &blocksize);
447 mwp->total = imax(mwp->total, headerlen);
448 }
449 mwp->used = imax(mwp->used, (int)strlen("Used"));
450 if (COMPAT_MODE("bin/df", "unix2003") && !hflag) {
451 avail_str = "Available";
452 } else {
453 avail_str = "Avail";
454 }
455 mwp->avail = imax(mwp->avail, (int)strlen(avail_str));
456
457 (void)printf("%-*s %*s %*s %*s Capacity", mwp->mntfrom,
458 "Filesystem", mwp->total, header, mwp->used, "Used",
459 mwp->avail, avail_str);
460 if (iflag) {
461 mwp->iused = imax(mwp->iused, (int)strlen(" iused"));
462 mwp->ifree = imax(mwp->ifree, (int)strlen("ifree"));
463 (void)printf(" %*s %*s %%iused", mwp->iused - 2,
464 "iused", mwp->ifree, "ifree");
465 }
466 (void)printf(" Mounted on\n");
467 }
468
469 (void)printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
470 if (sfsp->f_blocks > sfsp->f_bfree)
471 used = sfsp->f_blocks - sfsp->f_bfree;
472 else
473 used = 0;
474 availblks = sfsp->f_bavail + used;
475 if (hflag) {
476 prthuman(sfsp, used);
477 } else {
478 (void)printf(" %*jd %*jd %*jd", mwp->total,
479 fsbtoblk(sfsp->f_blocks, sfsp->f_bsize, blocksize, sfsp->f_mntonname),
480 mwp->used, fsbtoblk(used, sfsp->f_bsize, blocksize, sfsp->f_mntonname),
481 mwp->avail, fsbtoblk(sfsp->f_bavail, sfsp->f_bsize, blocksize, sfsp->f_mntonname));
482 }
483 if (COMPAT_MODE("bin/df", "unix2003")) {
484 /* Standard says percentage must be rounded UP to next
485 integer value, not truncated */
486 double value;
487 if (availblks == 0)
488 value = 100.0;
489 else {
490 value = (double)used / (double)availblks * 100.0;
491 if ((value-(int)value) > 0.0) value = value + 1.0;
492 }
493 (void)printf(" %5.0f%%", trunc(value));
494 } else {
495 (void)printf(" %5.0f%%",
496 availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
497 }
498 if (iflag) {
499 inodes = sfsp->f_files;
500 used = inodes - sfsp->f_ffree;
501 (void)printf(" %*llu %*lu %4.0f%% ", mwp->iused, used,
502 mwp->ifree, (unsigned long)sfsp->f_ffree, inodes == 0 ? 100.0 :
503 (double)used / (double)inodes * 100.0);
504 } else
505 (void)printf(" ");
506 (void)printf(" %s\n", sfsp->f_mntonname);
507 }
508
509 /*
510 * Update the maximum field-width information in `mwp' based on
511 * the filesystem specified by `sfsp'.
512 */
513 void
514 update_maxwidths(struct maxwidths *mwp, struct statfs *sfsp)
515 {
516 static long blocksize;
517 int dummy;
518
519 if (blocksize == 0)
520 getbsize(&dummy, &blocksize);
521
522 mwp->mntfrom = imax(mwp->mntfrom, (int)strlen(sfsp->f_mntfromname));
523 mwp->total = imax(mwp->total, longwidth(fsbtoblk(sfsp->f_blocks,
524 sfsp->f_bsize, blocksize, sfsp->f_mntonname)));
525 if (sfsp->f_blocks >= sfsp->f_bfree)
526 mwp->used = imax(mwp->used, longwidth(fsbtoblk(sfsp->f_blocks -
527 sfsp->f_bfree, sfsp->f_bsize, blocksize, sfsp->f_mntonname)));
528 mwp->avail = imax(mwp->avail, longwidth(fsbtoblk(sfsp->f_bavail,
529 sfsp->f_bsize, blocksize, sfsp->f_mntonname)));
530 mwp->iused = imax(mwp->iused, longwidth((unsigned)(sfsp->f_files - sfsp->f_ffree)));
531 mwp->ifree = imax(mwp->ifree, longwidth((unsigned)(sfsp->f_ffree)));
532 }
533
534 /* Return the width in characters of the specified long. */
535 int
536 longwidth(long long val)
537 {
538 int len;
539
540 len = 0;
541 /* Negative or zero values require one extra digit. */
542 if (val <= 0) {
543 val = -val;
544 len++;
545 }
546 while (val > 0) {
547 len++;
548 val /= 10;
549 }
550
551 return (len);
552 }
553
554 void
555 usage(void)
556 {
557
558 char *t_flag = COMPAT_MODE("bin/df", "unix2003") ? "[-t]" : "[-t type]";
559 (void)fprintf(stderr,
560 "usage: df [-b | -H | -h | -k | -m | -g | -P] [-ailn] [-T type] %s [filesystem ...]\n", t_flag);
561 exit(EX_USAGE);
562 }
563
564 char *
565 makenetvfslist(void)
566 {
567 char *str, *strptr, **listptr;
568 #ifndef __APPLE__
569 int mib[3], maxvfsconf, cnt=0, i;
570 size_t miblen;
571 struct ovfsconf *ptr;
572 #else
573 int mib[4], maxvfsconf, cnt=0, i;
574 size_t miblen;
575 struct vfsconf vfc;
576 #endif
577
578 mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_MAXTYPENUM;
579 miblen=sizeof(maxvfsconf);
580 if (sysctl(mib, (unsigned int)(sizeof(mib) / sizeof(mib[0])),
581 &maxvfsconf, &miblen, NULL, 0)) {
582 warnx("sysctl failed");
583 return (NULL);
584 }
585
586 if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
587 warnx("malloc failed");
588 return (NULL);
589 }
590
591 #ifndef __APPLE__
592 for (ptr = getvfsent(); ptr; ptr = getvfsent())
593 if (ptr->vfc_flags & VFCF_NETWORK) {
594 listptr[cnt++] = strdup(ptr->vfc_name);
595 if (listptr[cnt-1] == NULL) {
596 warnx("malloc failed");
597 return (NULL);
598 }
599 }
600 #else
601 miblen = sizeof (struct vfsconf);
602 mib[2] = VFS_CONF;
603 for (i = 0; i < maxvfsconf; i++) {
604 mib[3] = i;
605 if (sysctl(mib, 4, &vfc, &miblen, NULL, 0) == 0) {
606 if (!(vfc.vfc_flags & MNT_LOCAL)) {
607 listptr[cnt++] = strdup(vfc.vfc_name);
608 if (listptr[cnt-1] == NULL) {
609 warnx("malloc failed");
610 return (NULL);
611 }
612 }
613 }
614 }
615 #endif
616
617 if (cnt == 0 ||
618 (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
619 if (cnt > 0)
620 warnx("malloc failed");
621 free(listptr);
622 return (NULL);
623 }
624
625 *str = 'n'; *(str + 1) = 'o';
626 for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
627 strncpy(strptr, listptr[i], 32);
628 strptr += strlen(listptr[i]);
629 *strptr = ',';
630 free(listptr[i]);
631 }
632 *(--strptr) = '\0';
633
634 free(listptr);
635 return (str);
636 }