file_cmds-202.2.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 const char *fstype;
148 char *mntpt, **vfslist;
149 long mntsize;
150 int ch, i, rv, tflag = 0, kludge_tflag = 0;
151 int kflag = 0;
152 const char *options = "abgHhiklmnPt:T:";
153 if (COMPAT_MODE("bin/df", "unix2003")) {
154 /* Unix2003 requires -t be "include total capacity". which df
155 already does, but it conflicts with the old -t so we need to
156 *not* expect a string after -t (we provide -T in both cases
157 to cover the old use of -t) */
158 options = "abgHhiklmnPtT:";
159 }
160
161 fstype = "hfs";
162
163 vfslist = NULL;
164 while ((ch = getopt(argc, argv, options)) != -1)
165 switch (ch) {
166 case 'a':
167 aflag = 1;
168 break;
169 case 'b':
170 /* FALLTHROUGH */
171 case 'P':
172 if (COMPAT_MODE("bin/df", "unix2003")) {
173 if (!kflag) {
174 /* -k overrides -P */
175 putenv("BLOCKSIZE=512");
176 }
177 } else {
178 putenv("BLOCKSIZE=512");
179 }
180 hflag = 0;
181 break;
182 case 'g':
183 putenv("BLOCKSIZE=1g");
184 hflag = 0;
185 break;
186 case 'H':
187 hflag = UNITS_SI;
188 valp = vals_si;
189 break;
190 case 'h':
191 hflag = UNITS_2;
192 valp = vals_base2;
193 break;
194 case 'i':
195 iflag = 1;
196 break;
197 case 'k':
198 if (COMPAT_MODE("bin/df", "unix2003")) {
199 putenv("BLOCKSIZE=1024");
200 } else {
201 putenv("BLOCKSIZE=1k");
202 }
203 kflag = 1;
204 hflag = 0;
205 break;
206 case 'l':
207 if (tflag)
208 errx(1, "-l and -T are mutually exclusive.");
209 if (vfslist != NULL)
210 break;
211 vfslist = makevfslist(makenetvfslist());
212 break;
213 case 'm':
214 putenv("BLOCKSIZE=1m");
215 hflag = 0;
216 break;
217 case 'n':
218 nflag = 1;
219 break;
220 case 't':
221 /* Unix2003 uses -t for something we do by default */
222 if (COMPAT_MODE("bin/df", "unix2003")) {
223 kludge_tflag = 1;
224 break;
225 }
226 case 'T':
227 if (vfslist != NULL) {
228 if (tflag)
229 errx(1, "only one -%c option may be specified", ch);
230 else
231 errx(1, "-l and -%c are mutually exclusive.", ch);
232 }
233 tflag++;
234 fstype = optarg;
235 vfslist = makevfslist(optarg);
236 break;
237 case '?':
238 default:
239 usage();
240 }
241 argc -= optind;
242 argv += optind;
243
244 /* If we are in unix2003 mode, have seen a -t but no -T and the first
245 non switch arg isn't a file, let's pretend they used -T on it.
246 This makes the Lexmark printer installer happy (PR-3918471) */
247 if (tflag == 0 && kludge_tflag && *argv && stat(*argv, &stbuf) < 0
248 && errno == ENOENT) {
249 tflag = 1;
250 fstype = *argv++;
251 vfslist = makevfslist(fstype);
252 }
253
254 mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
255 bzero(&maxwidths, sizeof(maxwidths));
256 for (i = 0; i < mntsize; i++)
257 update_maxwidths(&maxwidths, &mntbuf[i]);
258
259 rv = 0;
260 if (!*argv) {
261 mntsize = regetmntinfo(&mntbuf, mntsize, vfslist);
262 bzero(&maxwidths, sizeof(maxwidths));
263 for (i = 0; i < mntsize; i++)
264 update_maxwidths(&maxwidths, &mntbuf[i]);
265 for (i = 0; i < mntsize; i++) {
266 if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
267 prtstat(&mntbuf[i], &maxwidths);
268 }
269 exit(rv);
270 }
271
272 for (; *argv; argv++) {
273 if (stat(*argv, &stbuf) < 0) {
274 if ((mntpt = getmntpt(*argv)) == 0) {
275 warn("%s", *argv);
276 rv = 1;
277 continue;
278 }
279 } else if (S_ISCHR(stbuf.st_mode) || S_ISBLK(stbuf.st_mode)) {
280 warnx("%s: Raw devices not supported", *argv);
281 rv = 1;
282 continue;
283 } else
284 mntpt = *argv;
285 /*
286 * Statfs does not take a `wait' flag, so we cannot
287 * implement nflag here.
288 */
289 if (statfs(mntpt, &statfsbuf) < 0) {
290 warn("%s", mntpt);
291 rv = 1;
292 continue;
293 }
294 /* Check to make sure the arguments we've been
295 * given are satisfied. Return an error if we
296 * have been asked to list a mount point that does
297 * not match the other args we've been given (-l, -t, etc.)
298 */
299 if (checkvfsname(statfsbuf.f_fstypename, vfslist)) {
300 rv++;
301 continue;
302 }
303
304 if (argc == 1) {
305 bzero(&maxwidths, sizeof(maxwidths));
306 update_maxwidths(&maxwidths, &statfsbuf);
307 }
308 prtstat(&statfsbuf, &maxwidths);
309 }
310 return (rv);
311 }
312
313 char *
314 getmntpt(char *name)
315 {
316 long mntsize, i;
317 struct statfs *mntbuf;
318
319 mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
320 for (i = 0; i < mntsize; i++) {
321 if (!strcmp(mntbuf[i].f_mntfromname, name))
322 return (mntbuf[i].f_mntonname);
323 }
324 return (0);
325 }
326
327 /*
328 * Make a pass over the filesystem info in ``mntbuf'' filtering out
329 * filesystem types not in vfslist and possibly re-stating to get
330 * current (not cached) info. Returns the new count of valid statfs bufs.
331 */
332 long
333 regetmntinfo(struct statfs **mntbufp, long mntsize, char **vfslist)
334 {
335 int i, j;
336 struct statfs *mntbuf;
337
338 if (vfslist == NULL)
339 return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
340
341 mntbuf = *mntbufp;
342 for (j = 0, i = 0; i < mntsize; i++) {
343 if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
344 continue;
345 if (!nflag)
346 (void)statfs(mntbuf[i].f_mntonname,&mntbuf[j]);
347 else if (i != j)
348 mntbuf[j] = mntbuf[i];
349 j++;
350 }
351 return (j);
352 }
353
354 /*
355 * Output in "human-readable" format. Uses 3 digits max and puts
356 * unit suffixes at the end. Makes output compact and easy to read,
357 * especially on huge disks.
358 *
359 */
360 unit_t
361 unit_adjust(double *val)
362 {
363 double abval;
364 unit_t unit;
365 unsigned int unit_sz;
366
367 abval = fabs(*val);
368
369 unit_sz = abval ? ilogb(abval) / 10 : 0;
370
371 if (unit_sz >= UNIT_MAX) {
372 unit = NONE;
373 } else {
374 unit = unitp[unit_sz];
375 *val /= (double)valp[unit_sz];
376 }
377
378 return (unit);
379 }
380
381 void
382 prthuman(struct statfs *sfsp, uint64_t used)
383 {
384 int64_t value;
385
386 value = sfsp->f_blocks;
387 value *= sfsp->f_bsize;
388 prthumanval(value);
389 value = used;
390 value *= sfsp->f_bsize;
391 prthumanval(value);
392 value = sfsp->f_bavail;
393 value *= sfsp->f_bsize;
394 prthumanval(value);
395 }
396
397 void
398 prthumanval(int64_t bytes)
399 {
400 char buf[6];
401 int flags;
402
403 flags = HN_B | HN_NOSPACE | HN_DECIMAL;
404 if (hflag == UNITS_SI)
405 flags |= HN_DIVISOR_1000;
406
407 humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
408 bytes, "", HN_AUTOSCALE, flags);
409
410 if (hflag == UNITS_SI)
411 (void)printf(" %6s", buf);
412 else
413 (void)printf("%6si", buf);
414
415 }
416
417 /*
418 * Convert statfs returned filesystem size into BLOCKSIZE units.
419 * Attempts to avoid overflow for large filesystems.
420 */
421 static intmax_t fsbtoblk(int64_t num, uint64_t fsbs, u_long bs, char *fs)
422 {
423 if (num < 0) {
424 warnx("negative filesystem block count/size from fs %s", fs);
425 return 0;
426 } else if ((fsbs != 0) && (fsbs < bs)) {
427 return (num / (intmax_t) (bs / fsbs));
428 } else {
429 return (num * (intmax_t) (fsbs / bs));
430 }
431 }
432
433 /*
434 * Print out status about a filesystem.
435 */
436 void
437 prtstat(struct statfs *sfsp, struct maxwidths *mwp)
438 {
439 static long blocksize;
440 static int headerlen, timesthrough;
441 static const char *header;
442 uint64_t used, availblks, inodes;
443 char * avail_str;
444
445 if (++timesthrough == 1) {
446 mwp->mntfrom = imax(mwp->mntfrom, strlen("Filesystem"));
447 if (hflag) {
448 header = " Size";
449 mwp->total = mwp->used = mwp->avail = strlen(header);
450 } else {
451 header = getbsize(&headerlen, &blocksize);
452 mwp->total = imax(mwp->total, headerlen);
453 }
454 mwp->used = imax(mwp->used, strlen("Used"));
455 if (COMPAT_MODE("bin/df", "unix2003") && !hflag) {
456 avail_str = "Available";
457 } else {
458 avail_str = "Avail";
459 }
460 mwp->avail = imax(mwp->avail, strlen(avail_str));
461
462 (void)printf("%-*s %*s %*s %*s Capacity", mwp->mntfrom,
463 "Filesystem", mwp->total, header, mwp->used, "Used",
464 mwp->avail, avail_str);
465 if (iflag) {
466 mwp->iused = imax(mwp->iused, strlen(" iused"));
467 mwp->ifree = imax(mwp->ifree, strlen("ifree"));
468 (void)printf(" %*s %*s %%iused", mwp->iused - 2,
469 "iused", mwp->ifree, "ifree");
470 }
471 (void)printf(" Mounted on\n");
472 }
473
474 (void)printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
475 if (sfsp->f_blocks > sfsp->f_bfree)
476 used = sfsp->f_blocks - sfsp->f_bfree;
477 else
478 used = 0;
479 availblks = sfsp->f_bavail + used;
480 if (hflag) {
481 prthuman(sfsp, used);
482 } else {
483 (void)printf(" %*jd %*jd %*jd", mwp->total,
484 fsbtoblk(sfsp->f_blocks, sfsp->f_bsize, blocksize, sfsp->f_mntonname),
485 mwp->used, fsbtoblk(used, sfsp->f_bsize, blocksize, sfsp->f_mntonname),
486 mwp->avail, fsbtoblk(sfsp->f_bavail, sfsp->f_bsize, blocksize, sfsp->f_mntonname));
487 }
488 if (COMPAT_MODE("bin/df", "unix2003")) {
489 /* Standard says percentage must be rounded UP to next
490 integer value, not truncated */
491 double value;
492 if (availblks == 0)
493 value = 100.0;
494 else {
495 value = (double)used / (double)availblks * 100.0;
496 if ((value-(int)value) > 0.0) value = value + 1.0;
497 }
498 (void)printf(" %5.0f%%", trunc(value));
499 } else {
500 (void)printf(" %5.0f%%",
501 availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
502 }
503 if (iflag) {
504 inodes = sfsp->f_files;
505 used = inodes - sfsp->f_ffree;
506 (void)printf(" %*llu %*lu %4.0f%% ", mwp->iused, used,
507 mwp->ifree, (unsigned long)sfsp->f_ffree, inodes == 0 ? 100.0 :
508 (double)used / (double)inodes * 100.0);
509 } else
510 (void)printf(" ");
511 (void)printf(" %s\n", sfsp->f_mntonname);
512 }
513
514 /*
515 * Update the maximum field-width information in `mwp' based on
516 * the filesystem specified by `sfsp'.
517 */
518 void
519 update_maxwidths(struct maxwidths *mwp, struct statfs *sfsp)
520 {
521 static long blocksize;
522 int dummy;
523
524 if (blocksize == 0)
525 getbsize(&dummy, &blocksize);
526
527 mwp->mntfrom = imax(mwp->mntfrom, strlen(sfsp->f_mntfromname));
528 mwp->total = imax(mwp->total, longwidth(fsbtoblk(sfsp->f_blocks,
529 sfsp->f_bsize, blocksize, sfsp->f_mntonname)));
530 if (sfsp->f_blocks >= sfsp->f_bfree)
531 mwp->used = imax(mwp->used, longwidth(fsbtoblk(sfsp->f_blocks -
532 sfsp->f_bfree, sfsp->f_bsize, blocksize, sfsp->f_mntonname)));
533 mwp->avail = imax(mwp->avail, longwidth(fsbtoblk(sfsp->f_bavail,
534 sfsp->f_bsize, blocksize, sfsp->f_mntonname)));
535 mwp->iused = imax(mwp->iused, longwidth((unsigned)(sfsp->f_files - sfsp->f_ffree)));
536 mwp->ifree = imax(mwp->ifree, longwidth((unsigned)(sfsp->f_ffree)));
537 }
538
539 /* Return the width in characters of the specified long. */
540 int
541 longwidth(long long val)
542 {
543 int len;
544
545 len = 0;
546 /* Negative or zero values require one extra digit. */
547 if (val <= 0) {
548 val = -val;
549 len++;
550 }
551 while (val > 0) {
552 len++;
553 val /= 10;
554 }
555
556 return (len);
557 }
558
559 void
560 usage(void)
561 {
562
563 char *t_flag = COMPAT_MODE("bin/df", "unix2003") ? "[-t]" : "[-t type]";
564 (void)fprintf(stderr,
565 "usage: df [-b | -H | -h | -k | -m | -g | -P] [-ailn] [-T type] %s [filesystem ...]\n", t_flag);
566 exit(EX_USAGE);
567 }
568
569 char *
570 makenetvfslist(void)
571 {
572 char *str, *strptr, **listptr;
573 #ifndef __APPLE__
574 int mib[3], maxvfsconf, cnt=0, i;
575 size_t miblen;
576 struct ovfsconf *ptr;
577 #else
578 int mib[4], maxvfsconf, cnt=0, i;
579 size_t miblen;
580 struct vfsconf vfc;
581 #endif
582
583 mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_MAXTYPENUM;
584 miblen=sizeof(maxvfsconf);
585 if (sysctl(mib, (unsigned int)(sizeof(mib) / sizeof(mib[0])),
586 &maxvfsconf, &miblen, NULL, 0)) {
587 warnx("sysctl failed");
588 return (NULL);
589 }
590
591 if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
592 warnx("malloc failed");
593 return (NULL);
594 }
595
596 #ifndef __APPLE__
597 for (ptr = getvfsent(); ptr; ptr = getvfsent())
598 if (ptr->vfc_flags & VFCF_NETWORK) {
599 listptr[cnt++] = strdup(ptr->vfc_name);
600 if (listptr[cnt-1] == NULL) {
601 warnx("malloc failed");
602 return (NULL);
603 }
604 }
605 #else
606 miblen = sizeof (struct vfsconf);
607 mib[2] = VFS_CONF;
608 for (i = 0; i < maxvfsconf; i++) {
609 mib[3] = i;
610 if (sysctl(mib, 4, &vfc, &miblen, NULL, 0) == 0) {
611 if (!(vfc.vfc_flags & MNT_LOCAL)) {
612 listptr[cnt++] = strdup(vfc.vfc_name);
613 if (listptr[cnt-1] == NULL) {
614 warnx("malloc failed");
615 return (NULL);
616 }
617 }
618 }
619 }
620 #endif
621
622 if (cnt == 0 ||
623 (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
624 if (cnt > 0)
625 warnx("malloc failed");
626 free(listptr);
627 return (NULL);
628 }
629
630 *str = 'n'; *(str + 1) = 'o';
631 for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
632 strncpy(strptr, listptr[i], 32);
633 strptr += strlen(listptr[i]);
634 *strptr = ',';
635 free(listptr[i]);
636 }
637 *(--strptr) = '\0';
638
639 free(listptr);
640 return (str);
641 }