Merge branch 'vendor/FILE'
[dragonfly.git] / bin / 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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * @(#) Copyright (c) 1980, 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
35  * @(#)df.c     8.9 (Berkeley) 5/8/95
36  * $FreeBSD: src/bin/df/df.c,v 1.23.2.9 2002/07/01 00:14:24 iedowse Exp $
37  */
38
39 #include <sys/param.h>
40 #include <sys/stat.h>
41 #include <sys/mount.h>
42 #include <sys/sysctl.h>
43 #include <sys/statvfs.h>
44
45 #include <vfs/ufs/dinode.h>
46 #include <vfs/ufs/fs.h>
47 #include <vfs/ufs/ufsmount.h>
48
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <fstab.h>
53 #include <libutil.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <sysexits.h>
58 #include <unistd.h>
59
60 #define UNITS_SI 1
61 #define UNITS_2 2
62
63 /* Maximum widths of various fields. */
64 struct maxwidths {
65         int mntfrom;
66         int fstype;
67         int total;
68         int used;
69         int avail;
70         int iused;
71         int ifree;
72 };
73
74 /* vfslist.c */
75 char    **makevfslist(char *);
76 int       checkvfsname(const char *, char **);
77
78 static int       bread(off_t, void *, int);
79 static char     *getmntpt(char *);
80 static int       quadwidth(int64_t);
81 static char     *makenetvfslist(void);
82 static void      prthuman(struct statvfs *, int64_t);
83 static void      prthumanval(int64_t);
84 static void      prtstat(struct statfs *, struct statvfs *, struct maxwidths *);
85 static long      regetmntinfo(struct statfs **, struct statvfs **, long, char **);
86 static int       ufs_df(char *, struct maxwidths *);
87 static void      update_maxwidths(struct maxwidths *, struct statfs *, struct statvfs *);
88 static void      usage(void);
89
90 int     aflag = 0, hflag, iflag, nflag, Tflag;
91 struct  ufs_args mdev;
92
93 static __inline int
94 imax(int a, int b)
95 {
96         return (a > b ? a : b);
97 }
98
99 static __inline int64_t
100 qmax(int64_t a, int64_t b)
101 {
102         return (a > b ? a : b);
103 }
104
105 int
106 main(int argc, char **argv)
107 {
108         struct stat stbuf;
109         struct statfs statfsbuf, *mntbuf;
110         struct statvfs statvfsbuf, *mntvbuf;
111         struct maxwidths maxwidths;
112         const char *fstype;
113         char *mntpath, *mntpt, **vfslist;
114         long mntsize;
115         int ch, i, rv;
116
117         fstype = "ufs";
118
119         vfslist = NULL;
120         while ((ch = getopt(argc, argv, "abgHhiklmnPt:T")) != -1)
121                 switch (ch) {
122                 case 'a':
123                         aflag = 1;
124                         break;
125                 case 'b':
126                                 /* FALLTHROUGH */
127                 case 'P':
128                         if (setenv("BLOCKSIZE", "512", 1) != 0)
129                                 warn("setenv: cannot set BLOCKSIZE=512");
130                         hflag = 0;
131                         break;
132                 case 'g':
133                         if (setenv("BLOCKSIZE", "1g", 1) != 0)
134                                 warn("setenv: cannot set BLOCKSIZE=1g");
135                         hflag = 0;
136                         break;
137                 case 'H':
138                         hflag = UNITS_SI;
139                         break;
140                 case 'h':
141                         hflag = UNITS_2;
142                         break;
143                 case 'i':
144                         iflag = 1;
145                         break;
146                 case 'k':
147                         if (setenv("BLOCKSIZE", "1k", 1) != 0)
148                                 warn("setenv: cannot set BLOCKSIZE=1k");
149                         hflag = 0;
150                         break;
151                 case 'l':
152                         if (vfslist != NULL)
153                                 errx(1, "-l and -t are mutually exclusive.");
154                         vfslist = makevfslist(makenetvfslist());
155                         break;
156                 case 'm':
157                         if (setenv("BLOCKSIZE", "1m", 1) != 0)
158                                 warn("setenv: cannot set BLOCKSIZE=1m");
159                         hflag = 0;
160                         break;
161                 case 'n':
162                         nflag = 1;
163                         break;
164                 case 't':
165                         if (vfslist != NULL)
166                                 errx(1, "only one -t option may be specified");
167                         fstype = optarg;
168                         vfslist = makevfslist(optarg);
169                         break;
170                 case 'T':
171                         Tflag = 1;
172                         break;
173                 case '?':
174                 default:
175                         usage();
176                 }
177         argc -= optind;
178         argv += optind;
179
180         mntsize = getmntvinfo(&mntbuf, &mntvbuf, MNT_NOWAIT);
181         bzero(&maxwidths, sizeof(maxwidths));
182         for (i = 0; i < mntsize; i++)
183                 update_maxwidths(&maxwidths, &mntbuf[i], &mntvbuf[i]);
184
185         rv = 0;
186         if (!*argv) {
187                 mntsize = regetmntinfo(&mntbuf, &mntvbuf, mntsize, vfslist);
188                 bzero(&maxwidths, sizeof(maxwidths));
189                 for (i = 0; i < mntsize; i++)
190                         update_maxwidths(&maxwidths, &mntbuf[i], &mntvbuf[i]);
191                 for (i = 0; i < mntsize; i++) {
192                         if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
193                                 prtstat(&mntbuf[i], &mntvbuf[i], &maxwidths);
194                 }
195                 exit(rv);
196         }
197
198         for (; *argv; argv++) {
199                 if (stat(*argv, &stbuf) < 0) {
200                         if ((mntpt = getmntpt(*argv)) == NULL) {
201                                 warn("%s", *argv);
202                                 rv = 1;
203                                 continue;
204                         }
205                 } else if (S_ISCHR(stbuf.st_mode)) {
206                         if ((mntpt = getmntpt(*argv)) == NULL) {
207                                 mdev.fspec = *argv;
208                                 mntpath = strdup("/tmp/df.XXXXXX");
209                                 if (mntpath == NULL) {
210                                         warn("strdup failed");
211                                         rv = 1;
212                                         continue;
213                                 }
214                                 mntpt = mkdtemp(mntpath);
215                                 if (mntpt == NULL) {
216                                         warn("mkdtemp(\"%s\") failed", mntpath);
217                                         rv = 1;
218                                         free(mntpath);
219                                         continue;
220                                 }
221                                 if (mount(fstype, mntpt, MNT_RDONLY,
222                                     &mdev) != 0) {
223                                         rv = ufs_df(*argv, &maxwidths) || rv;
224                                         rmdir(mntpt);
225                                         free(mntpath);
226                                         continue;
227                                 } else if (statfs(mntpt, &statfsbuf) == 0 &&
228                                            statvfs(mntpt, &statvfsbuf) == 0) {
229                                         statfsbuf.f_mntonname[0] = '\0';
230                                         prtstat(&statfsbuf, &statvfsbuf, &maxwidths);
231                                 } else {
232                                         warn("%s", *argv);
233                                         rv = 1;
234                                 }
235                                 unmount(mntpt, 0);
236                                 rmdir(mntpt);
237                                 free(mntpath);
238                                 continue;
239                         }
240                 } else
241                         mntpt = *argv;
242                 /*
243                  * Statfs does not take a `wait' flag, so we cannot
244                  * implement nflag here.
245                  */
246                 if (statfs(mntpt, &statfsbuf) < 0) {
247                         warn("%s", mntpt);
248                         rv = 1;
249                         continue;
250                 }
251                 if (statvfs(mntpt, &statvfsbuf) < 0) {
252                         warn("%s", mntpt);
253                         rv = 1;
254                         continue;
255                 }
256                 /*
257                  * Check to make sure the arguments we've been given are
258                  * satisfied. Return an error if we have been asked to
259                  * list a mount point that does not match the other args
260                  * we've been given (-l, -t, etc.).
261                  */
262                 if (checkvfsname(statfsbuf.f_fstypename, vfslist)) {
263                         rv = 1;
264                         continue;
265                 }
266
267                 if (argc == 1) {
268                         bzero(&maxwidths, sizeof(maxwidths));
269                         update_maxwidths(&maxwidths, &statfsbuf, &statvfsbuf);
270                 }
271                 prtstat(&statfsbuf, &statvfsbuf, &maxwidths);
272         }
273         return (rv);
274 }
275
276 static char *
277 getmntpt(char *name)
278 {
279         long mntsize, i;
280         struct statfs *mntbuf;
281         struct statvfs *mntvbuf;
282
283         mntsize = getmntvinfo(&mntbuf, &mntvbuf, MNT_NOWAIT);
284         for (i = 0; i < mntsize; i++) {
285                 if (!strcmp(mntbuf[i].f_mntfromname, name))
286                         return (mntbuf[i].f_mntonname);
287         }
288         return (0);
289 }
290
291 /*
292  * Make a pass over the filesystem info in ``mntbuf'' filtering out
293  * filesystem types not in vfslist and possibly re-stating to get
294  * current (not cached) info.  Returns the new count of valid statfs bufs.
295  */
296 static long
297 regetmntinfo(struct statfs **mntbufp, struct statvfs **mntvbufp, long mntsize, char **vfslist)
298 {
299         int i, j;
300         struct statfs *mntbuf;
301         struct statvfs *mntvbuf;
302
303         if (vfslist == NULL)
304                 return (nflag ? mntsize : getmntvinfo(mntbufp, mntvbufp, MNT_WAIT));
305
306         mntbuf = *mntbufp;
307         mntvbuf = *mntvbufp;
308         for (j = 0, i = 0; i < mntsize; i++) {
309                 if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
310                         continue;
311                 if (!nflag) {
312                         statfs(mntbuf[i].f_mntonname,&mntbuf[j]);
313                         statvfs(mntbuf[i].f_mntonname,&mntvbuf[j]);
314                 } else if (i != j) {
315                         mntbuf[j] = mntbuf[i];
316                         mntvbuf[j] = mntvbuf[i];
317                 }
318                 j++;
319         }
320         return (j);
321 }
322
323 static void
324 prthuman(struct statvfs *vsfsp, int64_t used)
325 {
326         prthumanval(vsfsp->f_blocks * vsfsp->f_bsize);
327         prthumanval(used * vsfsp->f_bsize);
328         prthumanval(vsfsp->f_bavail * vsfsp->f_bsize);
329 }
330
331 static void
332 prthumanval(int64_t bytes)
333 {
334         char buf[6];
335         int flags;
336
337         flags = HN_B | HN_NOSPACE | HN_DECIMAL;
338         if (hflag == UNITS_SI)
339                 flags |= HN_DIVISOR_1000;
340
341         humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
342             bytes, "", HN_AUTOSCALE, flags);
343
344         printf(" %6s", buf);
345 }
346
347 /*
348  * Print an inode count in "human-readable" format.
349  */
350 static void
351 prthumanvalinode(int64_t bytes)
352 {
353         char buf[6];
354         int flags;
355
356         flags = HN_NOSPACE | HN_DECIMAL | HN_DIVISOR_1000;
357
358         humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
359             bytes, "", HN_AUTOSCALE, flags);
360
361         printf(" %5s", buf);
362 }
363
364 /*
365  * Convert statfs returned filesystem size into BLOCKSIZE units.
366  * Attempts to avoid overflow for large filesystems.
367  */
368 static intmax_t
369 fsbtoblk(int64_t num, uint64_t bsize, u_long reqbsize)
370 {
371         if (bsize != 0 && bsize < reqbsize)
372                 return (num / (intmax_t)(reqbsize / bsize));
373         else
374                 return (num * (intmax_t)(bsize / reqbsize));
375 }
376
377 /*
378  * Print out status about a filesystem.
379  */
380 static void
381 prtstat(struct statfs *sfsp, struct statvfs *vsfsp, struct maxwidths *mwp)
382 {
383         static long blocksize;
384         static int headerlen, timesthrough;
385         static const char *header;
386         int64_t used, availblks, inodes;
387
388         if (++timesthrough == 1) {
389                 mwp->mntfrom = imax(mwp->mntfrom, strlen("Filesystem"));
390                 mwp->fstype = imax(mwp->fstype, strlen("Type"));
391                 if (hflag) {
392                         header = "  Size";
393                         mwp->total = mwp->used = mwp->avail = strlen(header);
394                 } else {
395                         header = getbsize(&headerlen, &blocksize);
396                         mwp->total = imax(mwp->total, headerlen);
397                 }
398                 mwp->used = imax(mwp->used, strlen("Used"));
399                 mwp->avail = imax(mwp->avail, strlen("Avail"));
400
401                 printf("%-*s", mwp->mntfrom, "Filesystem");
402                 if (Tflag)
403                         printf("  %-*s", mwp->fstype, "Type");
404                 printf(" %-*s %*s %*s Capacity", mwp->total, header, mwp->used,
405                     "Used", mwp->avail, "Avail");
406                 if (iflag) {
407                         mwp->iused = imax(mwp->iused, strlen("  iused"));
408                         mwp->ifree = imax(mwp->ifree, strlen("ifree"));
409                         printf(" %*s %*s %%iused", mwp->iused - 2,
410                             "iused", mwp->ifree, "ifree");
411                 }
412                 printf("  Mounted on\n");
413         }
414         printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
415         if (Tflag)
416                 printf("  %-*s", mwp->fstype, sfsp->f_fstypename);
417         used = vsfsp->f_blocks - vsfsp->f_bfree;
418         availblks = vsfsp->f_bavail + used;
419         if (hflag) {
420                 prthuman(vsfsp, used);
421         } else {
422                 printf(" %*jd %*jd %*jd", mwp->total,
423                     fsbtoblk(vsfsp->f_blocks, vsfsp->f_bsize, blocksize),
424                     mwp->used, fsbtoblk(used, vsfsp->f_bsize, blocksize),
425                     mwp->avail, fsbtoblk(vsfsp->f_bavail, vsfsp->f_bsize,
426                     blocksize));
427         }
428         printf(" %5.0f%%",
429             availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
430         if (iflag) {
431                 inodes = vsfsp->f_files;
432                 used = inodes - vsfsp->f_ffree;
433                 if (hflag) {
434                         printf("  ");
435                         prthumanvalinode(used);
436                         prthumanvalinode(vsfsp->f_ffree);
437                 } else {
438                         printf(" %*jd %*jd", mwp->iused, (intmax_t)used,
439                             mwp->ifree, (intmax_t)vsfsp->f_ffree);
440                 }
441                 printf(" %4.0f%% ", inodes == 0 ? 100.0 :
442                     (double)used / (double)inodes * 100.0);
443         } else
444                 printf("  ");
445         printf("  %s\n", sfsp->f_mntonname);
446 }
447
448 /*
449  * Update the maximum field-width information in `mwp' based on
450  * the filesystem specified by `sfsp'.
451  */
452 static void
453 update_maxwidths(struct maxwidths *mwp, struct statfs *sfsp, struct statvfs *vsfsp)
454 {
455         static long blocksize;
456         int dummy;
457
458         if (blocksize == 0)
459                 getbsize(&dummy, &blocksize);
460
461         mwp->mntfrom = imax(mwp->mntfrom, strlen(sfsp->f_mntfromname));
462         mwp->fstype = imax(mwp->fstype, strlen(sfsp->f_fstypename));
463         mwp->total = imax(mwp->total, quadwidth(fsbtoblk(vsfsp->f_blocks,
464             vsfsp->f_bsize, blocksize)));
465         mwp->used = imax(mwp->used, quadwidth(fsbtoblk(vsfsp->f_blocks -
466             vsfsp->f_bfree, vsfsp->f_bsize, blocksize)));
467         mwp->avail = imax(mwp->avail, quadwidth(fsbtoblk(vsfsp->f_bavail,
468             vsfsp->f_bsize, blocksize)));
469         mwp->iused = imax(mwp->iused, quadwidth(vsfsp->f_files -
470             vsfsp->f_ffree));
471         mwp->ifree = imax(mwp->ifree, quadwidth(vsfsp->f_ffree));
472 }
473
474 /* Return the width in characters of the specified long. */
475 static int
476 quadwidth(int64_t val)
477 {
478         int len;
479
480         len = 0;
481         /* Negative or zero values require one extra digit. */
482         if (val <= 0) {
483                 val = -val;
484                 len++;
485         }
486         while (val > 0) {
487                 len++;
488                 val /= 10;
489         }
490         return (len);
491 }
492
493 /*
494  * This code constitutes the pre-system call Berkeley df code for extracting
495  * information from filesystem superblocks.
496  */
497
498 union {
499         struct fs iu_fs;
500         char dummy[SBSIZE];
501 } sb;
502 #define sblock sb.iu_fs
503
504 int     rfd;
505
506 static int
507 ufs_df(char *file, struct maxwidths *mwp)
508 {
509         struct statfs statfsbuf;
510         struct statvfs statvfsbuf;
511         struct statfs *sfsp;
512         struct statvfs *vsfsp;
513         const char *mntpt;
514         static int synced;
515
516         if (synced++ == 0)
517                 sync();
518
519         if ((rfd = open(file, O_RDONLY)) < 0) {
520                 warn("%s", file);
521                 return (1);
522         }
523         if (bread((off_t)SBOFF, &sblock, SBSIZE) == 0) {
524                 close(rfd);
525                 return (1);
526         }
527         sfsp = &statfsbuf;
528         vsfsp = &statvfsbuf;
529         sfsp->f_type = 1;
530         strcpy(sfsp->f_fstypename, "ufs");
531         sfsp->f_flags = 0;
532         sfsp->f_bsize = vsfsp->f_bsize = sblock.fs_fsize;
533         sfsp->f_iosize = vsfsp->f_frsize = sblock.fs_bsize;
534         sfsp->f_blocks = vsfsp->f_blocks = sblock.fs_dsize;
535         sfsp->f_bfree = vsfsp->f_bfree =
536                 sblock.fs_cstotal.cs_nbfree * sblock.fs_frag +
537                 sblock.fs_cstotal.cs_nffree;
538         sfsp->f_bavail = vsfsp->f_bavail = freespace(&sblock, sblock.fs_minfree);
539         sfsp->f_files = vsfsp->f_files = sblock.fs_ncg * sblock.fs_ipg;
540         sfsp->f_ffree = vsfsp->f_ffree = sblock.fs_cstotal.cs_nifree;
541         sfsp->f_fsid.val[0] = 0;
542         sfsp->f_fsid.val[1] = 0;
543         if ((mntpt = getmntpt(file)) == NULL)
544                 mntpt = "";
545         memmove(&sfsp->f_mntonname[0], mntpt, (size_t)MNAMELEN);
546         memmove(&sfsp->f_mntfromname[0], file, (size_t)MNAMELEN);
547         prtstat(sfsp, vsfsp, mwp);
548         close(rfd);
549         return (0);
550 }
551
552 static int
553 bread(off_t off, void *buf, int cnt)
554 {
555         ssize_t nr;
556
557         lseek(rfd, off, SEEK_SET);
558         if ((nr = read(rfd, buf, (size_t)cnt)) != (ssize_t)cnt) {
559                 /* Probably a dismounted disk if errno == EIO. */
560                 if (errno != EIO)
561                         fprintf(stderr, "\ndf: %lld: %s\n",
562                             (long long)off, strerror(nr > 0 ? EIO : errno));
563                 return (0);
564         }
565         return (1);
566 }
567
568 static void
569 usage(void)
570 {
571
572         fprintf(stderr,
573             "usage: df [-b | -H | -h | -k | -m | -P] [-ailnT] [-t type] [file | filesystem ...]\n");
574         exit(EX_USAGE);
575 }
576
577 static char *
578 makenetvfslist(void)
579 {
580         char *str, *strptr, **listptr;
581         int mib[3], maxvfsconf, cnt=0, i;
582         size_t miblen;
583         struct ovfsconf *ptr;
584
585         mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_MAXTYPENUM;
586         miblen=sizeof(maxvfsconf);
587         if (sysctl(mib, (unsigned int)(sizeof(mib) / sizeof(mib[0])),
588             &maxvfsconf, &miblen, NULL, 0)) {
589                 warnx("sysctl failed");
590                 return (NULL);
591         }
592
593         if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
594                 warnx("malloc failed");
595                 return (NULL);
596         }
597
598         for (ptr = getvfsent(); ptr; ptr = getvfsent())
599                 if (ptr->vfc_flags & VFCF_NETWORK) {
600                         listptr[cnt++] = strdup(ptr->vfc_name);
601                         if (listptr[cnt-1] == NULL) {
602                                 warnx("malloc failed");
603                                 free(listptr);
604                                 return (NULL);
605                         }
606                 }
607
608         if (cnt == 0 ||
609             (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
610                 if (cnt > 0)
611                         warnx("malloc failed");
612                 free(listptr);
613                 return (NULL);
614         }
615
616         *str = 'n'; *(str + 1) = 'o';
617         for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
618                 strncpy(strptr, listptr[i], 32);
619                 strptr += strlen(listptr[i]);
620                 *strptr = ',';
621                 free(listptr[i]);
622         }
623         *(--strptr) = '\0';
624
625         free(listptr);
626         return (str);
627 }