Beef up error reporting for a particular assertion to try to track down a
[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. 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  * @(#) Copyright (c) 1980, 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
39  * @(#)df.c     8.9 (Berkeley) 5/8/95
40  * $FreeBSD: src/bin/df/df.c,v 1.23.2.9 2002/07/01 00:14:24 iedowse Exp $
41  * $DragonFly: src/bin/df/df.c,v 1.6 2005/11/06 11:44:02 swildner Exp $
42  */
43
44 #include <sys/cdefs.h>
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 #include <sys/mount.h>
48 #include <sys/sysctl.h>
49 #include <vfs/ufs/ufsmount.h>
50 #include <vfs/ufs/fs.h>
51
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <fstab.h>
56 #include <math.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <sysexits.h>
61 #include <unistd.h>
62
63 #define UNITS_SI 1
64 #define UNITS_2 2
65
66 #define KILO_SZ(n) (n)
67 #define MEGA_SZ(n) ((n) * (n))
68 #define GIGA_SZ(n) ((n) * (n) * (n))
69 #define TERA_SZ(n) ((n) * (n) * (n) * (n))
70 #define PETA_SZ(n) ((n) * (n) * (n) * (n) * (n))
71
72 #define KILO_2_SZ (KILO_SZ(1024ULL))
73 #define MEGA_2_SZ (MEGA_SZ(1024ULL))
74 #define GIGA_2_SZ (GIGA_SZ(1024ULL))
75 #define TERA_2_SZ (TERA_SZ(1024ULL))
76 #define PETA_2_SZ (PETA_SZ(1024ULL))
77
78 #define KILO_SI_SZ (KILO_SZ(1000ULL))
79 #define MEGA_SI_SZ (MEGA_SZ(1000ULL))
80 #define GIGA_SI_SZ (GIGA_SZ(1000ULL))
81 #define TERA_SI_SZ (TERA_SZ(1000ULL))
82 #define PETA_SI_SZ (PETA_SZ(1000ULL))
83
84 /* Maximum widths of various fields. */
85 struct maxwidths {
86         int mntfrom;
87         int total;
88         int used;
89         int avail;
90         int iused;
91         int ifree;
92 };
93
94 unsigned long long vals_si [] = {1, KILO_SI_SZ, MEGA_SI_SZ, GIGA_SI_SZ, TERA_SI_SZ, PETA_SI_SZ};
95 unsigned long long vals_base2[] = {1, KILO_2_SZ, MEGA_2_SZ, GIGA_2_SZ, TERA_2_SZ, PETA_2_SZ};
96 unsigned long long *valp;
97
98 typedef enum { NONE, KILO, MEGA, GIGA, TERA, PETA, UNIT_MAX } unit_t;
99
100 unit_t unitp [] = { NONE, KILO, MEGA, GIGA, TERA, PETA };
101
102 int       bread(off_t, void *, int);
103 int       checkvfsname(const char *, char **);
104 char     *getmntpt(char *);
105 int       longwidth(long);
106 char     *makenetvfslist(void);
107 char    **makevfslist(char *);
108 void      prthuman(struct statfs *, long);
109 void      prthumanval(double);
110 void      prtstat(struct statfs *, struct maxwidths *);
111 long      regetmntinfo(struct statfs **, long, char **);
112 int       ufs_df(char *, struct maxwidths *);
113 unit_t    unit_adjust(double *);
114 void      update_maxwidths(struct maxwidths *, struct statfs *);
115 void      usage(void);
116
117 int     aflag = 0, hflag, iflag, nflag;
118 struct  ufs_args mdev;
119
120 static __inline int
121 imax(int a, int b)
122 {
123         return (a > b ? a : b);
124 }
125
126 int
127 main(int argc, char **argv)
128 {
129         struct stat stbuf;
130         struct statfs statfsbuf, *mntbuf;
131         struct maxwidths maxwidths;
132         const char *fstype;
133         char *mntpath, *mntpt, **vfslist;
134         long mntsize;
135         int ch, i, rv;
136
137         fstype = "ufs";
138
139         vfslist = NULL;
140         while ((ch = getopt(argc, argv, "abgHhiklmnPt:")) != -1)
141                 switch (ch) {
142                 case 'a':
143                         aflag = 1;
144                         break;
145                 case 'b':
146                                 /* FALLTHROUGH */
147                 case 'P':
148                         putenv("BLOCKSIZE=512");
149                         hflag = 0;
150                         break;
151                 case 'g':
152                         putenv("BLOCKSIZE=1g");
153                         hflag = 0;
154                         break;
155                 case 'H':
156                         hflag = UNITS_SI;
157                         valp = vals_si;
158                         break;
159                 case 'h':
160                         hflag = UNITS_2;
161                         valp = vals_base2;
162                         break;
163                 case 'i':
164                         iflag = 1;
165                         break;
166                 case 'k':
167                         putenv("BLOCKSIZE=1k");
168                         hflag = 0;
169                         break;
170                 case 'l':
171                         if (vfslist != NULL)
172                                 errx(1, "-l and -t are mutually exclusive.");
173                         vfslist = makevfslist(makenetvfslist());
174                         break;
175                 case 'm':
176                         putenv("BLOCKSIZE=1m");
177                         hflag = 0;
178                         break;
179                 case 'n':
180                         nflag = 1;
181                         break;
182                 case 't':
183                         if (vfslist != NULL)
184                                 errx(1, "only one -t option may be specified");
185                         fstype = optarg;
186                         vfslist = makevfslist(optarg);
187                         break;
188                 case '?':
189                 default:
190                         usage();
191                 }
192         argc -= optind;
193         argv += optind;
194
195         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
196         bzero(&maxwidths, sizeof(maxwidths));
197         for (i = 0; i < mntsize; i++)
198                 update_maxwidths(&maxwidths, &mntbuf[i]);
199
200         rv = 0;
201         if (!*argv) {
202                 mntsize = regetmntinfo(&mntbuf, mntsize, vfslist);
203                 bzero(&maxwidths, sizeof(maxwidths));
204                 for (i = 0; i < mntsize; i++)
205                         update_maxwidths(&maxwidths, &mntbuf[i]);
206                 for (i = 0; i < mntsize; i++) {
207                         if (aflag || (mntbuf[i].f_flags & MNT_IGNORE) == 0)
208                                 prtstat(&mntbuf[i], &maxwidths);
209                 }
210                 exit(rv);
211         }
212
213         for (; *argv; argv++) {
214                 if (stat(*argv, &stbuf) < 0) {
215                         if ((mntpt = getmntpt(*argv)) == 0) {
216                                 warn("%s", *argv);
217                                 rv = 1;
218                                 continue;
219                         }
220                 } else if (S_ISCHR(stbuf.st_mode)) {
221                         if ((mntpt = getmntpt(*argv)) == 0) {
222                                 mdev.fspec = *argv;
223                                 mntpath = strdup("/tmp/df.XXXXXX");
224                                 if (mntpath == NULL) {
225                                         warn("strdup failed");
226                                         rv = 1;
227                                         continue;
228                                 }
229                                 mntpt = mkdtemp(mntpath);
230                                 if (mntpt == NULL) {
231                                         warn("mkdtemp(\"%s\") failed", mntpath);
232                                         rv = 1;
233                                         free(mntpath);
234                                         continue;
235                                 }
236                                 if (mount(fstype, mntpt, MNT_RDONLY,
237                                     &mdev) != 0) {
238                                         rv = ufs_df(*argv, &maxwidths) || rv;
239                                         rmdir(mntpt);
240                                         free(mntpath);
241                                         continue;
242                                 } else if (statfs(mntpt, &statfsbuf) == 0) {
243                                         statfsbuf.f_mntonname[0] = '\0';
244                                         prtstat(&statfsbuf, &maxwidths);
245                                 } else {
246                                         warn("%s", *argv);
247                                         rv = 1;
248                                 }
249                                 unmount(mntpt, 0);
250                                 rmdir(mntpt);
251                                 free(mntpath);
252                                 continue;
253                         }
254                 } else
255                         mntpt = *argv;
256                 /*
257                  * Statfs does not take a `wait' flag, so we cannot
258                  * implement nflag here.
259                  */
260                 if (statfs(mntpt, &statfsbuf) < 0) {
261                         warn("%s", mntpt);
262                         rv = 1;
263                         continue;
264                 }
265                 if (argc == 1) {
266                         bzero(&maxwidths, sizeof(maxwidths));
267                         update_maxwidths(&maxwidths, &statfsbuf);
268                 }
269                 prtstat(&statfsbuf, &maxwidths);
270         }
271         return (rv);
272 }
273
274 char *
275 getmntpt(char *name)
276 {
277         long mntsize, i;
278         struct statfs *mntbuf;
279
280         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
281         for (i = 0; i < mntsize; i++) {
282                 if (!strcmp(mntbuf[i].f_mntfromname, name))
283                         return (mntbuf[i].f_mntonname);
284         }
285         return (0);
286 }
287
288 /*
289  * Make a pass over the filesystem info in ``mntbuf'' filtering out
290  * filesystem types not in vfslist and possibly re-stating to get
291  * current (not cached) info.  Returns the new count of valid statfs bufs.
292  */
293 long
294 regetmntinfo(struct statfs **mntbufp, long mntsize, char **vfslist)
295 {
296         int i, j;
297         struct statfs *mntbuf;
298
299         if (vfslist == NULL)
300                 return (nflag ? mntsize : getmntinfo(mntbufp, MNT_WAIT));
301
302         mntbuf = *mntbufp;
303         for (j = 0, i = 0; i < mntsize; i++) {
304                 if (checkvfsname(mntbuf[i].f_fstypename, vfslist))
305                         continue;
306                 if (!nflag)
307                         statfs(mntbuf[i].f_mntonname,&mntbuf[j]);
308                 else if (i != j)
309                         mntbuf[j] = mntbuf[i];
310                 j++;
311         }
312         return (j);
313 }
314
315 /*
316  * Output in "human-readable" format.  Uses 3 digits max and puts
317  * unit suffixes at the end.  Makes output compact and easy to read,
318  * especially on huge disks.
319  *
320  */
321 unit_t
322 unit_adjust(double *val)
323 {
324         double abval;
325         unit_t unit;
326         unsigned int unit_sz;
327
328         abval = fabs(*val);
329
330         unit_sz = abval ? ilogb(abval) / 10 : 0;
331
332         if (unit_sz >= UNIT_MAX) {
333                 unit = NONE;
334         } else {
335                 unit = unitp[unit_sz];
336                 *val /= (double)valp[unit_sz];
337         }
338
339         return (unit);
340 }
341
342 void
343 prthuman(struct statfs *sfsp, long used)
344 {
345
346         prthumanval((double)sfsp->f_blocks * (double)sfsp->f_bsize);
347         prthumanval((double)used * (double)sfsp->f_bsize);
348         prthumanval((double)sfsp->f_bavail * (double)sfsp->f_bsize);
349 }
350
351 void
352 prthumanval(double bytes)
353 {
354
355         unit_t unit;
356         unit = unit_adjust(&bytes);
357
358         if (bytes == 0)
359                 printf("     0B");
360         else if (bytes > 10)
361                 printf(" %5.0f%c", bytes, "BKMGTPE"[unit]);
362         else
363                 printf(" %5.1f%c", bytes, "BKMGTPE"[unit]);
364 }
365
366 /*
367  * Convert statfs returned filesystem size into BLOCKSIZE units.
368  * Attempts to avoid overflow for large filesystems.
369  */
370 #define fsbtoblk(num, fsbs, bs) \
371         (((fsbs) != 0 && (fsbs) < (bs)) ? \
372                 (num) / ((bs) / (fsbs)) : (num) * ((fsbs) / (bs)))
373
374 /*
375  * Print out status about a filesystem.
376  */
377 void
378 prtstat(struct statfs *sfsp, struct maxwidths *mwp)
379 {
380         static long blocksize;
381         static int headerlen, timesthrough;
382         static const char *header;
383         long used, availblks, inodes;
384
385         if (++timesthrough == 1) {
386                 mwp->mntfrom = imax(mwp->mntfrom, strlen("Filesystem"));
387                 if (hflag) {
388                         header = "  Size";
389                         mwp->total = mwp->used = mwp->avail = strlen(header);
390                 } else {
391                         header = getbsize(&headerlen, &blocksize);
392                         mwp->total = imax(mwp->total, headerlen);
393                 }
394                 mwp->used = imax(mwp->used, strlen("Used"));
395                 mwp->avail = imax(mwp->avail, strlen("Avail"));
396
397                 printf("%-*s %-*s %*s %*s Capacity", mwp->mntfrom,
398                     "Filesystem", mwp->total, header, mwp->used, "Used",
399                     mwp->avail, "Avail");
400                 if (iflag) {
401                         mwp->iused = imax(mwp->iused, strlen("  iused"));
402                         mwp->ifree = imax(mwp->ifree, strlen("ifree"));
403                         printf(" %*s %*s %%iused", mwp->iused - 2,
404                             "iused", mwp->ifree, "ifree");
405                 }
406                 printf("  Mounted on\n");
407         }
408         printf("%-*s", mwp->mntfrom, sfsp->f_mntfromname);
409         used = sfsp->f_blocks - sfsp->f_bfree;
410         availblks = sfsp->f_bavail + used;
411         if (hflag) {
412                 prthuman(sfsp, used);
413         } else {
414                 printf(" %*ld %*ld %*ld", mwp->total,
415                     fsbtoblk(sfsp->f_blocks, sfsp->f_bsize, blocksize),
416                     mwp->used, fsbtoblk(used, sfsp->f_bsize, blocksize),
417                     mwp->avail, fsbtoblk(sfsp->f_bavail, sfsp->f_bsize,
418                     blocksize));
419         }
420         printf(" %5.0f%%",
421             availblks == 0 ? 100.0 : (double)used / (double)availblks * 100.0);
422         if (iflag) {
423                 inodes = sfsp->f_files;
424                 used = inodes - sfsp->f_ffree;
425                 printf(" %*ld %*ld %4.0f%% ", mwp->iused, used,
426                     mwp->ifree, sfsp->f_ffree, inodes == 0 ? 100.0 :
427                     (double)used / (double)inodes * 100.0);
428         } else
429                 printf("  ");
430         printf("  %s\n", sfsp->f_mntonname);
431 }
432
433 /*
434  * Update the maximum field-width information in `mwp' based on
435  * the filesystem specified by `sfsp'.
436  */
437 void
438 update_maxwidths(struct maxwidths *mwp, struct statfs *sfsp)
439 {
440         static long blocksize;
441         int dummy;
442
443         if (blocksize == 0)
444                 getbsize(&dummy, &blocksize);
445
446         mwp->mntfrom = imax(mwp->mntfrom, strlen(sfsp->f_mntfromname));
447         mwp->total = imax(mwp->total, longwidth(fsbtoblk(sfsp->f_blocks,
448             sfsp->f_bsize, blocksize)));
449         mwp->used = imax(mwp->used, longwidth(fsbtoblk(sfsp->f_blocks -
450             sfsp->f_bfree, sfsp->f_bsize, blocksize)));
451         mwp->avail = imax(mwp->avail, longwidth(fsbtoblk(sfsp->f_bavail,
452             sfsp->f_bsize, blocksize)));
453         mwp->iused = imax(mwp->iused, longwidth(sfsp->f_files -
454             sfsp->f_ffree));
455         mwp->ifree = imax(mwp->ifree, longwidth(sfsp->f_ffree));
456 }
457
458 /* Return the width in characters of the specified long. */
459 int
460 longwidth(long val)
461 {
462         int len;
463
464         len = 0;
465         /* Negative or zero values require one extra digit. */
466         if (val <= 0) {
467                 val = -val;
468                 len++;
469         }
470         while (val > 0) {
471                 len++;
472                 val /= 10;
473         }
474
475         return (len);
476 }
477
478 /*
479  * This code constitutes the pre-system call Berkeley df code for extracting
480  * information from filesystem superblocks.
481  */
482
483 union {
484         struct fs iu_fs;
485         char dummy[SBSIZE];
486 } sb;
487 #define sblock sb.iu_fs
488
489 int     rfd;
490
491 int
492 ufs_df(char *file, struct maxwidths *mwp)
493 {
494         struct statfs statfsbuf;
495         struct statfs *sfsp;
496         const char *mntpt;
497         static int synced;
498
499         if (synced++ == 0)
500                 sync();
501
502         if ((rfd = open(file, O_RDONLY)) < 0) {
503                 warn("%s", file);
504                 return (1);
505         }
506         if (bread((off_t)SBOFF, &sblock, SBSIZE) == 0) {
507                 close(rfd);
508                 return (1);
509         }
510         sfsp = &statfsbuf;
511         sfsp->f_type = 1;
512         strcpy(sfsp->f_fstypename, "ufs");
513         sfsp->f_flags = 0;
514         sfsp->f_bsize = sblock.fs_fsize;
515         sfsp->f_iosize = sblock.fs_bsize;
516         sfsp->f_blocks = sblock.fs_dsize;
517         sfsp->f_bfree = sblock.fs_cstotal.cs_nbfree * sblock.fs_frag +
518                 sblock.fs_cstotal.cs_nffree;
519         sfsp->f_bavail = freespace(&sblock, sblock.fs_minfree);
520         sfsp->f_files =  sblock.fs_ncg * sblock.fs_ipg;
521         sfsp->f_ffree = sblock.fs_cstotal.cs_nifree;
522         sfsp->f_fsid.val[0] = 0;
523         sfsp->f_fsid.val[1] = 0;
524         if ((mntpt = getmntpt(file)) == 0)
525                 mntpt = "";
526         memmove(&sfsp->f_mntonname[0], mntpt, (size_t)MNAMELEN);
527         memmove(&sfsp->f_mntfromname[0], file, (size_t)MNAMELEN);
528         prtstat(sfsp, mwp);
529         close(rfd);
530         return (0);
531 }
532
533 int
534 bread(off_t off, void *buf, int cnt)
535 {
536         ssize_t nr;
537
538         lseek(rfd, off, SEEK_SET);
539         if ((nr = read(rfd, buf, (size_t)cnt)) != (ssize_t)cnt) {
540                 /* Probably a dismounted disk if errno == EIO. */
541                 if (errno != EIO)
542                         fprintf(stderr, "\ndf: %lld: %s\n",
543                             (long long)off, strerror(nr > 0 ? EIO : errno));
544                 return (0);
545         }
546         return (1);
547 }
548
549 void
550 usage(void)
551 {
552
553         fprintf(stderr,
554             "usage: df [-b | -H | -h | -k | -m | -P] [-ailn] [-t type] [file | filesystem ...]\n");
555         exit(EX_USAGE);
556 }
557
558 char *
559 makenetvfslist(void)
560 {
561         char *str, *strptr, **listptr;
562         int mib[3], maxvfsconf, cnt=0, i;
563         size_t miblen;
564         struct ovfsconf *ptr;
565
566         mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_MAXTYPENUM;
567         miblen=sizeof(maxvfsconf);
568         if (sysctl(mib, (unsigned int)(sizeof(mib) / sizeof(mib[0])),
569             &maxvfsconf, &miblen, NULL, 0)) {
570                 warnx("sysctl failed");
571                 return (NULL);
572         }
573
574         if ((listptr = malloc(sizeof(char*) * maxvfsconf)) == NULL) {
575                 warnx("malloc failed");
576                 return (NULL);
577         }
578
579         for (ptr = getvfsent(); ptr; ptr = getvfsent())
580                 if (ptr->vfc_flags & VFCF_NETWORK) {
581                         listptr[cnt++] = strdup(ptr->vfc_name);
582                         if (listptr[cnt-1] == NULL) {
583                                 warnx("malloc failed");
584                                 return (NULL);
585                         }
586                 }
587
588         if (cnt == 0 ||
589             (str = malloc(sizeof(char) * (32 * cnt + cnt + 2))) == NULL) {
590                 if (cnt > 0)
591                         warnx("malloc failed");
592                 free(listptr);
593                 return (NULL);
594         }
595
596         *str = 'n'; *(str + 1) = 'o';
597         for (i = 0, strptr = str + 2; i < cnt; i++, strptr++) {
598                 strncpy(strptr, listptr[i], 32);
599                 strptr += strlen(listptr[i]);
600                 *strptr = ',';
601                 free(listptr[i]);
602         }
603         *(--strptr) = NULL;
604
605         free(listptr);
606         return (str);
607 }