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