declare functions local to df module as static
[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 total;
67         int used;
68         int avail;
69         int iused;
70         int ifree;
71 };
72
73 /* vfslist.c */
74 char    **makevfslist(char *);
75 int       checkvfsname(const char *, char **);
76
77 static int       bread(off_t, void *, int);
78 static char     *getmntpt(char *);
79 static int       quadwidth(int64_t);
80 static char     *makenetvfslist(void);
81 static void      prthuman(struct statvfs *, int64_t);
82 static void      prthumanval(int64_t);
83 static void      prtstat(struct statfs *, struct statvfs *, struct maxwidths *);
84 static long      regetmntinfo(struct statfs **, struct statvfs **, long, char **);
85 static int       ufs_df(char *, struct maxwidths *);
86 static void      update_maxwidths(struct maxwidths *, struct statfs *, struct statvfs *);
87 static void      usage(void);
88
89 int     aflag = 0, hflag, iflag, nflag;
90 struct  ufs_args mdev;
91
92 static __inline int
93 imax(int a, int b)
94 {
95         return (a > b ? a : b);
96 }
97
98 static __inline int64_t
99 qmax(int64_t a, int64_t b)
100 {
101         return (a > b ? a : b);
102 }
103
104 int
105 main(int argc, char **argv)
106 {
107         struct stat stbuf;
108         struct statfs statfsbuf, *mntbuf;
109         struct statvfs statvfsbuf, *mntvbuf;
110         struct maxwidths maxwidths;
111         const char *fstype;
112         char *mntpath, *mntpt, **vfslist;
113         long mntsize;
114         int ch, i, rv;
115
116         fstype = "ufs";
117
118         vfslist = NULL;
119         while ((ch = getopt(argc, argv, "abgHhiklmnPt:")) != -1)
120                 switch (ch) {
121                 case 'a':
122                         aflag = 1;
123                         break;
124                 case 'b':
125                                 /* FALLTHROUGH */
126                 case 'P':
127                         if (setenv("BLOCKSIZE", "512", 1) != 0)
128                                 warn("setenv: cannot set BLOCKSIZE=512");
129                         hflag = 0;
130                         break;
131                 case 'g':
132                         if (setenv("BLOCKSIZE", "1g", 1) != 0)
133                                 warn("setenv: cannot set BLOCKSIZE=1g");
134                         hflag = 0;
135                         break;
136                 case 'H':
137                         hflag = UNITS_SI;
138                         break;
139                 case 'h':
140                         hflag = UNITS_2;
141                         break;
142                 case 'i':
143                         iflag = 1;
144                         break;
145                 case 'k':
146                         if (setenv("BLOCKSIZE", "1k", 1) != 0)
147                                 warn("setenv: cannot set BLOCKSIZE=1k");
148                         hflag = 0;
149                         break;
150                 case 'l':
151                         if (vfslist != NULL)
152                                 errx(1, "-l and -t are mutually exclusive.");
153                         vfslist = makevfslist(makenetvfslist());
154                         break;
155                 case 'm':
156                         if (setenv("BLOCKSIZE", "1m", 1) != 0)
157                                 warn("setenv: cannot set BLOCKSIZE=1m");
158                         hflag = 0;
159                         break;
160                 case 'n':
161                         nflag = 1;
162                         break;
163                 case 't':
164                         if (vfslist != NULL)
165                                 errx(1, "only one -t option may be specified");
166                         fstype = optarg;
167                         vfslist = makevfslist(optarg);
168                         break;
169                 case '?':
170                 default:
171                         usage();
172                 }
173         argc -= optind;
174         argv += optind;
175
176         mntsize = getmntvinfo(&mntbuf, &mntvbuf, MNT_NOWAIT);
177         bzero(&maxwidths, sizeof(maxwidths));
178         for (i = 0; i < mntsize; i++)
179                 update_maxwidths(&maxwidths, &mntbuf[i], &mntvbuf[i]);
180
181         rv = 0;
182         if (!*argv) {
183                 mntsize = regetmntinfo(&mntbuf, &mntvbuf, mntsize, vfslist);
184                 bzero(&maxwidths, sizeof(maxwidths));
185                 for (i = 0; i < mntsize; i++)
186                         update_maxwidths(&maxwidths, &mntbuf[i], &mntvbuf[i]);
187                 for (i = 0; i < mntsize; i++) {
188                         if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
189                                 prtstat(&mntbuf[i], &mntvbuf[i], &maxwidths);
190                 }
191                 exit(rv);
192         }
193
194         for (; *argv; argv++) {
195                 if (stat(*argv, &stbuf) < 0) {
196                         if ((mntpt = getmntpt(*argv)) == NULL) {
197                                 warn("%s", *argv);
198                                 rv = 1;
199                                 continue;
200                         }
201                 } else if (S_ISCHR(stbuf.st_mode)) {
202                         if ((mntpt = getmntpt(*argv)) == NULL) {
203                                 mdev.fspec = *argv;
204                                 mntpath = strdup("/tmp/df.XXXXXX");
205                                 if (mntpath == NULL) {
206                                         warn("strdup failed");
207                                         rv = 1;
208                                         continue;
209                                 }
210                                 mntpt = mkdtemp(mntpath);
211                                 if (mntpt == NULL) {
212                                         warn("mkdtemp(\"%s\") failed", mntpath);
213                                         rv = 1;
214                                         free(mntpath);
215                                         continue;
216                                 }
217                                 if (mount(fstype, mntpt, MNT_RDONLY,
218                                     &mdev) != 0) {
219                                         rv = ufs_df(*argv, &maxwidths) || rv;
220                                         rmdir(mntpt);
221                                         free(mntpath);
222                                         continue;
223                                 } else if (statfs(mntpt, &statfsbuf) == 0 &&
224                                            statvfs(mntpt, &statvfsbuf) == 0) {
225                                         statfsbuf.f_mntonname[0] = '\0';
226                                         prtstat(&statfsbuf, &statvfsbuf, &maxwidths);
227                                 } else {
228                                         warn("%s", *argv);
229                                         rv = 1;
230                                 }
231                                 unmount(mntpt, 0);
232                                 rmdir(mntpt);
233                                 free(mntpath);
234                                 continue;
235                         }
236                 } else
237                         mntpt = *argv;
238                 /*
239                  * Statfs does not take a `wait' flag, so we cannot
240                  * implement nflag here.
241                  */
242                 if (statfs(mntpt, &statfsbuf) < 0) {
243                         warn("%s", mntpt);
244                         rv = 1;
245                         continue;
246                 }
247                 if (statvfs(mntpt, &statvfsbuf) < 0) {
248                         warn("%s", mntpt);
249                         rv = 1;
250                         continue;
251                 }
252                 /*
253                  * Check to make sure the arguments we've been given are
254                  * satisfied. Return an error if we have been asked to
255                  * list a mount point that does not match the other args
256                  * we've been given (-l, -t, etc.).
257                  */
258                 if (checkvfsname(statfsbuf.f_fstypename, vfslist)) {
259                         rv = 1;
260                         continue;
261                 }
262
263                 if (argc == 1) {
264                         bzero(&maxwidths, sizeof(maxwidths));
265                         update_maxwidths(&maxwidths, &statfsbuf, &statvfsbuf);
266                 }
267                 prtstat(&statfsbuf, &statvfsbuf, &maxwidths);
268         }
269         return (rv);
270 }
271
272 static char *
273 getmntpt(char *name)
274 {
275         long mntsize, i;
276         struct statfs *mntbuf;
277         struct statvfs *mntvbuf;
278
279         mntsize = getmntvinfo(&mntbuf, &mntvbuf, MNT_NOWAIT);
280         for (i = 0; i < mntsize; i++) {
281                 if (!strcmp(mntbuf[i].f_mntfromname, name))
282                         return (mntbuf[i].f_mntonname);
283         }
284         return (0);
285 }
286
287 /*
288  * Make a pass over the filesystem info in ``mntbuf'' filtering out
289  * filesystem types not in vfslist and possibly re-stating to get
290  * current (not cached) info.  Returns the new count of valid statfs bufs.
291  */
292 static long
293 regetmntinfo(struct statfs **mntbufp, struct statvfs **mntvbufp, long mntsize, char **vfslist)
294 {
295         int i, j;
296         struct statfs *mntbuf;
297         struct statvfs *mntvbuf;
298
299         if (vfslist == NULL)
300                 return (nflag ? mntsize : getmntvinfo(mntbufp, mntvbufp, MNT_WAIT));
301
302         mntbuf = *mntbufp;
303         mntvbuf = *mntvbufp;
304         for (j = 0, i = 0; i < mntsize; i++) {
305                 if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
306                         continue;
307                 if (!nflag) {
308                         statfs(mntbuf[i].f_mntonname,&mntbuf[j]);
309                         statvfs(mntbuf[i].f_mntonname,&mntvbuf[j]);
310                 } else if (i != j) {
311                         mntbuf[j] = mntbuf[i];
312                         mntvbuf[j] = mntvbuf[i];
313                 }
314                 j++;
315         }
316         return (j);
317 }
318
319 static void
320 prthuman(struct statvfs *vsfsp, int64_t used)
321 {
322         prthumanval(vsfsp->f_blocks * vsfsp->f_bsize);
323         prthumanval(used * vsfsp->f_bsize);
324         prthumanval(vsfsp->f_bavail * vsfsp->f_bsize);
325 }
326
327 static void
328 prthumanval(int64_t bytes)
329 {
330         char buf[6];
331         int flags;
332
333         flags = HN_B | HN_NOSPACE | HN_DECIMAL;
334         if (hflag == UNITS_SI)
335                 flags |= HN_DIVISOR_1000;
336
337         humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
338             bytes, "", HN_AUTOSCALE, flags);
339
340         printf(" %6s", buf);
341 }
342
343 /*
344  * Convert statfs returned filesystem size into BLOCKSIZE units.
345  * Attempts to avoid overflow for large filesystems.
346  */
347 static intmax_t
348 fsbtoblk(int64_t num, uint64_t bsize, u_long reqbsize)
349 {
350         if (bsize != 0 && bsize < reqbsize)
351                 return (num / (intmax_t)(reqbsize / bsize));
352         else
353                 return (num * (intmax_t)(bsize / reqbsize));
354 }
355
356 /*
357  * Print out status about a filesystem.
358  */
359 static void
360 prtstat(struct statfs *sfsp, struct statvfs *vsfsp, struct maxwidths *mwp)
361 {
362         static long blocksize;
363         static int headerlen, timesthrough;
364         static const char *header;
365         int64_t used, availblks, inodes;
366
367         if (++timesthrough == 1) {
368                 mwp->mntfrom = imax(mwp->mntfrom, strlen("Filesystem"));
369                 if (hflag) {
370                         header = "  Size";
371                         mwp->total = mwp->used = mwp->avail = strlen(header);
372                 } else {
373                         header = getbsize(&headerlen, &blocksize);
374                         mwp->total = imax(mwp->total, headerlen);
375                 }
376                 mwp->used = imax(mwp->used, strlen("Used"));
377                 mwp->avail = imax(mwp->avail, strlen("Avail"));
378
379                 printf("%-*s %-*s %*s %*s Capacity", mwp->mntfrom,
380                     "Filesystem", mwp->total, header, mwp->used, "Used",
381                     mwp->avail, "Avail");
382                 if (iflag) {
383                         mwp->iused = imax(mwp->iused, strlen("  iused"));
384                         mwp->ifree = imax(mwp->ifree, strlen("ifree"));
385                         printf(" %*s %*s %%iused", mwp->iused - 2,
386                             "iused", mwp->ifree, "ifree");
387                 }
388                 printf("  Mounted on\n");
389         }
390         printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
391         used = vsfsp->f_blocks - vsfsp->f_bfree;
392         availblks = vsfsp->f_bavail + used;
393         if (hflag) {
394                 prthuman(vsfsp, used);
395         } else {
396                 printf(" %*jd %*jd %*jd", mwp->total,
397                     fsbtoblk(vsfsp->f_blocks, vsfsp->f_bsize, blocksize),
398                     mwp->used, fsbtoblk(used, vsfsp->f_bsize, blocksize),
399                     mwp->avail, fsbtoblk(vsfsp->f_bavail, vsfsp->f_bsize,
400                     blocksize));
401         }
402         printf(" %5.0f%%",
403             availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
404         if (iflag) {
405                 inodes = vsfsp->f_files;
406                 used = inodes - vsfsp->f_ffree;
407                 printf(" %*jd %*jd %4.0f%% ", mwp->iused, (intmax_t)used,
408                     mwp->ifree, (intmax_t)vsfsp->f_ffree, inodes == 0 ? 100.0 :
409                     (double)used / (double)inodes * 100.0);
410         } else
411                 printf("  ");
412         printf("  %s\n", sfsp->f_mntonname);
413 }
414
415 /*
416  * Update the maximum field-width information in `mwp' based on
417  * the filesystem specified by `sfsp'.
418  */
419 static void
420 update_maxwidths(struct maxwidths *mwp, struct statfs *sfsp, struct statvfs *vsfsp)
421 {
422         static long blocksize;
423         int dummy;
424
425         if (blocksize == 0)
426                 getbsize(&dummy, &blocksize);
427
428         mwp->mntfrom = imax(mwp->mntfrom, strlen(sfsp->f_mntfromname));
429         mwp->total = imax(mwp->total, quadwidth(fsbtoblk(vsfsp->f_blocks,
430             vsfsp->f_bsize, blocksize)));
431         mwp->used = imax(mwp->used, quadwidth(fsbtoblk(vsfsp->f_blocks -
432             vsfsp->f_bfree, vsfsp->f_bsize, blocksize)));
433         mwp->avail = imax(mwp->avail, quadwidth(fsbtoblk(vsfsp->f_bavail,
434             vsfsp->f_bsize, blocksize)));
435         mwp->iused = imax(mwp->iused, quadwidth(vsfsp->f_files -
436             vsfsp->f_ffree));
437         mwp->ifree = imax(mwp->ifree, quadwidth(vsfsp->f_ffree));
438 }
439
440 /* Return the width in characters of the specified long. */
441 static int
442 quadwidth(int64_t val)
443 {
444         int len;
445
446         len = 0;
447         /* Negative or zero values require one extra digit. */
448         if (val <= 0) {
449                 val = -val;
450                 len++;
451         }
452         while (val > 0) {
453                 len++;
454                 val /= 10;
455         }
456         return (len);
457 }
458
459 /*
460  * This code constitutes the pre-system call Berkeley df code for extracting
461  * information from filesystem superblocks.
462  */
463
464 union {
465         struct fs iu_fs;
466         char dummy[SBSIZE];
467 } sb;
468 #define sblock sb.iu_fs
469
470 int     rfd;
471
472 static int
473 ufs_df(char *file, struct maxwidths *mwp)
474 {
475         struct statfs statfsbuf;
476         struct statvfs statvfsbuf;
477         struct statfs *sfsp;
478         struct statvfs *vsfsp;
479         const char *mntpt;
480         static int synced;
481
482         if (synced++ == 0)
483                 sync();
484
485         if ((rfd = open(file, O_RDONLY)) < 0) {
486                 warn("%s", file);
487                 return (1);
488         }
489         if (bread((off_t)SBOFF, &sblock, SBSIZE) == 0) {
490                 close(rfd);
491                 return (1);
492         }
493         sfsp = &statfsbuf;
494         vsfsp = &statvfsbuf;
495         sfsp->f_type = 1;
496         strcpy(sfsp->f_fstypename, "ufs");
497         sfsp->f_flags = 0;
498         sfsp->f_bsize = vsfsp->f_bsize = sblock.fs_fsize;
499         sfsp->f_iosize = vsfsp->f_frsize = sblock.fs_bsize;
500         sfsp->f_blocks = vsfsp->f_blocks = sblock.fs_dsize;
501         sfsp->f_bfree = vsfsp->f_bfree =
502                 sblock.fs_cstotal.cs_nbfree * sblock.fs_frag +
503                 sblock.fs_cstotal.cs_nffree;
504         sfsp->f_bavail = vsfsp->f_bavail = freespace(&sblock, sblock.fs_minfree);
505         sfsp->f_files = vsfsp->f_files = sblock.fs_ncg * sblock.fs_ipg;
506         sfsp->f_ffree = vsfsp->f_ffree = sblock.fs_cstotal.cs_nifree;
507         sfsp->f_fsid.val[0] = 0;
508         sfsp->f_fsid.val[1] = 0;
509         if ((mntpt = getmntpt(file)) == NULL)
510                 mntpt = "";
511         memmove(&sfsp->f_mntonname[0], mntpt, (size_t)MNAMELEN);
512         memmove(&sfsp->f_mntfromname[0], file, (size_t)MNAMELEN);
513         prtstat(sfsp, vsfsp, mwp);
514         close(rfd);
515         return (0);
516 }
517
518 static int
519 bread(off_t off, void *buf, int cnt)
520 {
521         ssize_t nr;
522
523         lseek(rfd, off, SEEK_SET);
524         if ((nr = read(rfd, buf, (size_t)cnt)) != (ssize_t)cnt) {
525                 /* Probably a dismounted disk if errno == EIO. */
526                 if (errno != EIO)
527                         fprintf(stderr, "\ndf: %lld: %s\n",
528                             (long long)off, strerror(nr > 0 ? EIO : errno));
529                 return (0);
530         }
531         return (1);
532 }
533
534 static void
535 usage(void)
536 {
537
538         fprintf(stderr,
539             "usage: df [-b | -H | -h | -k | -m | -P] [-ailn] [-t type] [file | filesystem ...]\n");
540         exit(EX_USAGE);
541 }
542
543 static char *
544 makenetvfslist(void)
545 {
546         char *str, *strptr, **listptr;
547         int mib[3], maxvfsconf, cnt=0, i;
548         size_t miblen;
549         struct ovfsconf *ptr;
550
551         mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_MAXTYPENUM;
552         miblen=sizeof(maxvfsconf);
553         if (sysctl(mib, (unsigned int)(sizeof(mib) / sizeof(mib[0])),
554             &maxvfsconf, &miblen, NULL, 0)) {
555                 warnx("sysctl failed");
556                 return (NULL);
557         }
558
559         if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
560                 warnx("malloc failed");
561                 return (NULL);
562         }
563
564         for (ptr = getvfsent(); ptr; ptr = getvfsent())
565                 if (ptr->vfc_flags & VFCF_NETWORK) {
566                         listptr[cnt++] = strdup(ptr->vfc_name);
567                         if (listptr[cnt-1] == NULL) {
568                                 warnx("malloc failed");
569                                 return (NULL);
570                         }
571                 }
572
573         if (cnt == 0 ||
574             (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
575                 if (cnt > 0)
576                         warnx("malloc failed");
577                 free(listptr);
578                 return (NULL);
579         }
580
581         *str = 'n'; *(str + 1) = 'o';
582         for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
583                 strncpy(strptr, listptr[i], 32);
584                 strptr += strlen(listptr[i]);
585                 *strptr = ',';
586                 free(listptr[i]);
587         }
588         *(--strptr) = '\0';
589
590         free(listptr);
591         return (str);
592 }