summaryrefslogtreecommitdiff
path: root/src/df.c
blob: cc126347de4b4203da8d242a7dcf2f5d207b252a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/* df - summarize free disk space
   Copyright (C) 91, 1995-2001 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

/* Written by David MacKenzie <djm@gnu.ai.mit.edu>.
   --human-readable and --megabyte options added by lm@sgi.com.
   --si and large file support added by eggert@twinsun.com.  */

#ifdef _AIX
 #pragma alloca
#endif

#include <config.h>
#if HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#include <stdio.h>
#include <sys/types.h>
#include <getopt.h>
#include <assert.h>

#include "system.h"
#include "dirname.h"
#include "error.h"
#include "fsusage.h"
#include "human.h"
#include "mountlist.h"
#include "path-concat.h"
#include "quote.h"
#include "save-cwd.h"

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "df"

#define AUTHORS \
  "Torbjorn Granlund, David MacKenzie, Larry McVoy, and Paul Eggert"

char *xgetcwd ();

/* Name this program was run with. */
char *program_name;

/* If nonzero, show inode information. */
static int inode_format;

/* If nonzero, show even filesystems with zero size or
   uninteresting types. */
static int show_all_fs;

/* If nonzero, show only local filesystems.  */
static int show_local_fs;

/* If nonzero, output data for each filesystem corresponding to a
   command line argument -- even if it's a dummy (automounter) entry.  */
static int show_listed_fs;

/* If positive, the units to use when printing sizes;
   if negative, the human-readable base.  */
static int output_block_size;

/* If nonzero, use the POSIX output format.  */
static int posix_format;

/* If nonzero, invoke the `sync' system call before getting any usage data.
   Using this option can make df very slow, especially with many or very
   busy disks.  Note that this may make a difference on some systems --
   SunOs4.1.3, for one.  It is *not* necessary on Linux.  */
static int require_sync = 0;

/* Nonzero if errors have occurred. */
static int exit_status;

/* A filesystem type to display. */

struct fs_type_list
{
  char *fs_name;
  struct fs_type_list *fs_next;
};

/* Linked list of filesystem types to display.
   If `fs_select_list' is NULL, list all types.
   This table is generated dynamically from command-line options,
   rather than hardcoding into the program what it thinks are the
   valid filesystem types; let the user specify any filesystem type
   they want to, and if there are any filesystems of that type, they
   will be shown.

   Some filesystem types:
   4.2 4.3 ufs nfs swap ignore io vm efs dbg */

static struct fs_type_list *fs_select_list;

/* Linked list of filesystem types to omit.
   If the list is empty, don't exclude any types.  */

static struct fs_type_list *fs_exclude_list;

/* Linked list of mounted filesystems. */
static struct mount_entry *mount_list;

/* If nonzero, print filesystem type as well.  */
static int print_type;

/* For long options that have no equivalent short option, use a
   non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
enum
{
  SYNC_OPTION = CHAR_MAX + 1,
  NO_SYNC_OPTION,
  BLOCK_SIZE_OPTION
};

static struct option const long_options[] =
{
  {"all", no_argument, NULL, 'a'},
  {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
  {"inodes", no_argument, NULL, 'i'},
  {"human-readable", no_argument, NULL, 'h'},
  {"si", no_argument, NULL, 'H'},
  {"kilobytes", no_argument, NULL, 'k'},
  {"local", no_argument, NULL, 'l'},
  {"megabytes", no_argument, NULL, 'm'},
  {"portability", no_argument, NULL, 'P'},
  {"print-type", no_argument, NULL, 'T'},
  {"sync", no_argument, NULL, SYNC_OPTION},
  {"no-sync", no_argument, NULL, NO_SYNC_OPTION},
  {"type", required_argument, NULL, 't'},
  {"exclude-type", required_argument, NULL, 'x'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};

static void
print_header (void)
{
  printf (_("Filesystem "));

  if (print_type)
    printf (_("   Type"));
  else
    printf ("       ");

  if (inode_format)
    printf (_("    Inodes   IUsed   IFree IUse%%"));
  else if (output_block_size < 0)
    printf (_("    Size  Used Avail Use%%"));
  else if (posix_format)
    printf (_(" %4d-blocks      Used Available Capacity"), output_block_size);
  else
    {
      char buf[LONGEST_HUMAN_READABLE + 1];
      char *p = human_readable (output_block_size, buf, 1, -1024);

      /* Replace e.g. "1.0k" by "1k".  */
      size_t plen = strlen (p);
      if (3 <= plen && strncmp (p + plen - 3, ".0", 2) == 0)
	strcpy (p + plen - 3, p + plen - 1);

      printf (_(" %4s-blocks      Used Available Use%%"), p);
    }

  printf (_(" Mounted on\n"));
}

/* If FSTYPE is a type of filesystem that should be listed,
   return nonzero, else zero. */

static int
selected_fstype (const char *fstype)
{
  const struct fs_type_list *fsp;

  if (fs_select_list == NULL || fstype == NULL)
    return 1;
  for (fsp = fs_select_list; fsp; fsp = fsp->fs_next)
    if (STREQ (fstype, fsp->fs_name))
      return 1;
  return 0;
}

/* If FSTYPE is a type of filesystem that should be omitted,
   return nonzero, else zero. */

static int
excluded_fstype (const char *fstype)
{
  const struct fs_type_list *fsp;

  if (fs_exclude_list == NULL || fstype == NULL)
    return 0;
  for (fsp = fs_exclude_list; fsp; fsp = fsp->fs_next)
    if (STREQ (fstype, fsp->fs_name))
      return 1;
  return 0;
}

/* Like human_readable_inexact, except return "-" if the argument is -1,
   and if NEGATIVE is 1 then N represents a negative number, expressed
   in two's complement.  */
static char const *
df_readable (int negative, uintmax_t n, char *buf,
	     int from_block_size, int t_output_block_size,
	     enum human_inexact_style s)
{
  if (n == -1)
    return "-";
  else
    {
      char *p = human_readable_inexact (negative ? - n : n,
					buf + negative, from_block_size,
					t_output_block_size,
					negative ? - s : s);
      if (negative)
	*--p = '-';
      return p;
    }
}

/* Display a space listing for the disk device with absolute path DISK.
   If MOUNT_POINT is non-NULL, it is the path of the root of the
   filesystem on DISK.
   If FSTYPE is non-NULL, it is the type of the filesystem on DISK.
   If MOUNT_POINT is non-NULL, then DISK may be NULL -- certain systems may
   not be able to produce statistics in this case.
   ME_DUMMY and ME_REMOTE are the mount entry flags.  */

static void
show_dev (const char *disk, const char *mount_point, const char *fstype,
	  int me_dummy, int me_remote)
{
  struct fs_usage fsu;
  const char *stat_file;
  char buf[3][LONGEST_HUMAN_READABLE + 2];
  int width;
  int use_width;
  int input_units;
  int output_units;
  uintmax_t total;
  uintmax_t available;
  int negate_available;
  uintmax_t available_to_root;
  uintmax_t used;
  int negate_used;
  double pct = -1;

  if (me_remote && show_local_fs)
    return;

  if (me_dummy && show_all_fs == 0 && !show_listed_fs)
    return;

  if (!selected_fstype (fstype) || excluded_fstype (fstype))
    return;

  /* If MOUNT_POINT is NULL, then the filesystem is not mounted, and this
     program reports on the filesystem that the special file is on.
     It would be better to report on the unmounted filesystem,
     but statfs doesn't do that on most systems.  */
  stat_file = mount_point ? mount_point : disk;

  if (get_fs_usage (stat_file, disk, &fsu))
    {
      error (0, errno, "%s", quote (stat_file));
      exit_status = 1;
      return;
    }

  if (fsu.fsu_blocks == 0 && !show_all_fs && !show_listed_fs)
    return;

  if (! disk)
    disk = "-";			/* unknown */
  if (! fstype)
    fstype = "-";		/* unknown */

  /* df.c reserved 5 positions for fstype,
     but that does not suffice for type iso9660 */
  if (print_type)
    {
      int disk_name_len = (int) strlen (disk);
      int fstype_len = (int) strlen (fstype);
      if (disk_name_len + fstype_len + 2 < 20)
	printf ("%s%*s  ", disk, 18 - disk_name_len, fstype);
      else if (!posix_format)
	printf ("%s\n%18s  ", disk, fstype);
      else
	printf ("%s %s", disk, fstype);
    }
  else
    {
      if ((int) strlen (disk) > 20 && !posix_format)
	printf ("%s\n%20s", disk, "");
      else
	printf ("%-20s", disk);
    }

  if (inode_format)
    {
      width = 7;
      use_width = 5;
      input_units = 1;
      output_units = output_block_size < 0 ? output_block_size : 1;
      total = fsu.fsu_files;
      available = fsu.fsu_ffree;
      negate_available = 0;
      available_to_root = available;
    }
  else
    {
      width = output_block_size < 0 ? 5 : 9;
      use_width = posix_format ? 8 : 4;
      input_units = fsu.fsu_blocksize;
      output_units = output_block_size;
      total = fsu.fsu_blocks;
      available = fsu.fsu_bavail;
      negate_available = fsu.fsu_bavail_top_bit_set;
      available_to_root = fsu.fsu_bfree;
    }

  used = -1;
  negate_used = 0;
  if (total != -1 && available_to_root != -1)
    {
      used = total - available_to_root;
      if (total < available_to_root)
	{
	  negate_used = 1;
	  used = - used;
	}
    }

  printf (" %*s %*s %*s ",
	  width, df_readable (0, total,
			      buf[0], input_units, output_units,
			      (posix_format
			       ? human_ceiling
			       : human_round_to_even)),
	  width, df_readable (negate_used, used,
			      buf[1], input_units, output_units,
			      human_ceiling),
	  width, df_readable (negate_available, available,
			      buf[2], input_units, output_units,
			      posix_format ? human_ceiling : human_floor));

  if (used == -1 || available == -1)
    ;
  else if (!negate_used
	   && used <= TYPE_MAXIMUM (uintmax_t) / 100
	   && used + available != 0
	   && (used + available < used) == negate_available)
    {
      uintmax_t u100 = used * 100;
      uintmax_t nonroot_total = used + available;
      pct = u100 / nonroot_total + (u100 % nonroot_total != 0);
    }
  else
    {
      /* The calculation cannot be done easily with integer
	 arithmetic.  Fall back on floating point.  This can suffer
	 from minor rounding errors, but doing it exactly requires
	 multiple precision arithmetic, and it's not worth the
	 aggravation.  */
      double u = negate_used ? - (double) - used : used;
      double a = negate_available ? - (double) - available : available;
      double nonroot_total = u + a;
      if (nonroot_total)
	{
	  double ipct;
	  pct = u * 100 / nonroot_total;
	  ipct = (long) pct;

	  /* Like `pct = ceil (dpct);', but avoid ceil so that
	     the math library needn't be linked.  */
	  if (ipct - 1 < pct && pct <= ipct + 1)
	    pct = ipct + (ipct < pct);
	}
    }

  if (0 <= pct)
    printf ("%*.0f%%", use_width - 1, pct);
  else
    printf ("%*s", use_width, "- ");

  if (mount_point)
    {
#ifdef HIDE_AUTOMOUNT_PREFIX
      /* Don't print the first directory name in MOUNT_POINT if it's an
	 artifact of an automounter.  This is a bit too aggressive to be
	 the default.  */
      if (strncmp ("/auto/", mount_point, 6) == 0)
	mount_point += 5;
      else if (strncmp ("/tmp_mnt/", mount_point, 9) == 0)
	mount_point += 8;
#endif
      printf (" %s", mount_point);
    }
  putchar ('\n');
}

/* Identify the directory, if any, that device
   DISK is mounted on, and show its disk usage.  */

static void
show_disk (const char *disk)
{
  struct mount_entry *me;

  for (me = mount_list; me; me = me->me_next)
    if (STREQ (disk, me->me_devname))
      {
	show_dev (me->me_devname, me->me_mountdir, me->me_type,
		  me->me_dummy, me->me_remote);
	return;
      }
  /* No filesystem is mounted on DISK. */
  show_dev (disk, (char *) NULL, (char *) NULL, 0, 0);
}

/* Return the root mountpoint of the filesystem on which FILE exists, in
   malloced storage.  FILE_STAT should be the result of stating FILE.  */
static char *
find_mount_point (const char *file, const struct stat *file_stat)
{
  struct saved_cwd cwd;
  struct stat last_stat;
  char *mp = 0;			/* The malloced mount point path.  */

  if (save_cwd (&cwd))
    return NULL;

  if (S_ISDIR (file_stat->st_mode))
    /* FILE is a directory, so just chdir there directly.  */
    {
      last_stat = *file_stat;
      if (chdir (file) < 0)
	return NULL;
    }
  else
    /* FILE is some other kind of file, we need to use its directory.  */
    {
      char *dir = dir_name (file);
      int rv = chdir (dir);
      free (dir);

      if (rv < 0)
	return NULL;

      if (stat (".", &last_stat) < 0)
	goto done;
    }

  /* Now walk up FILE's parents until we find another filesystem or /,
     chdiring as we go.  LAST_STAT holds stat information for the last place
     we visited.  */
  for (;;)
    {
      struct stat st;
      if (stat ("..", &st) < 0)
	goto done;
      if (st.st_dev != last_stat.st_dev || st.st_ino == last_stat.st_ino)
	/* cwd is the mount point.  */
	break;
      if (chdir ("..") < 0)
	goto done;
      last_stat = st;
    }

  /* Finally reached a mount point, see what it's called.  */
  mp = xgetcwd ();

done:
  /* Restore the original cwd.  */
  {
    int save_errno = errno;
    if (restore_cwd (&cwd, 0, mp))
      exit (1);			/* We're scrod.  */
    free_cwd (&cwd);
    errno = save_errno;
  }

  return mp;
}

/* Figure out which device file or directory POINT is mounted on
   and show its disk usage.
   STATP is the results of `stat' on POINT.  */
static void
show_point (const char *point, const struct stat *statp)
{
  struct stat disk_stats;
  struct mount_entry *me;
  struct mount_entry *matching_dummy = NULL;
  char *needs_freeing = NULL;

  /* If POINT is an absolute path name, see if we can find the
     mount point without performing any extra stat calls at all.  */
  if (*point == '/')
    {
      for (me = mount_list; me; me = me->me_next)
	{
	  if (STREQ (me->me_mountdir, point) && !STREQ (me->me_type, "lofs"))
	    {
	      /* Prefer non-dummy entries.  */
	      if (! me->me_dummy)
		goto show_me;
	      matching_dummy = me;
	    }
	}

      if (matching_dummy)
	goto show_matching_dummy;
    }

  /* Ideally, the following mess of #if'd code would be in a separate
     file, and there'd be a single function call here.  FIXME, someday.  */

#if HAVE_REALPATH || HAVE_RESOLVEPATH || HAVE_CANONICALIZE_FILE_NAME
  /* Calculate the real absolute path for POINT, and use that to find
     the mount point.  This avoids statting unavailable mount points,
     which can hang df.  */
  {
    char const *abspoint = point;
    char *resolved;
    ssize_t resolved_len;
    struct mount_entry *best_match = NULL;

# if HAVE_CANONICALIZE_FILE_NAME
    resolved = canonicalize_file_name (abspoint);
    resolved_len = resolved ? strlen (resolved) : -1;
# else
#  if HAVE_RESOLVEPATH
    /* All known hosts with resolvepath (e.g. Solaris 7) don't turn
       relative names into absolute ones, so prepend the working
       directory if the path is not absolute.  */

    if (*point != '/')
      {
	static char const *wd;

	if (! wd)
	  {
	    struct stat pwd_stats;
	    struct stat dot_stats;

	    /* Use PWD if it is correct; this is usually cheaper than
               xgetcwd.  */
	    wd = getenv ("PWD");
	    if (! (wd
		   && stat (wd, &pwd_stats) == 0
		   && stat (".", &dot_stats) == 0
		   && SAME_INODE (pwd_stats, dot_stats)))
	      wd = xgetcwd ();
	  }

	if (wd)
	  {
	    needs_freeing = path_concat (wd, point, NULL);
	    if (needs_freeing)
	      abspoint = needs_freeing;
	  }
      }
#  endif

#  if HAVE_RESOLVEPATH
    {
      size_t resolved_size = strlen (abspoint);
      while (1)
	{
	  resolved_size = 2 * resolved_size + 1;
	  resolved = xmalloc (resolved_size);
	  resolved_len = resolvepath (abspoint, resolved, resolved_size);
	  if (resolved_len < resolved_size)
	    break;
	  free (resolved);
	}
    }
#  else
    /* Use realpath only as a last resort.
       It provides a very poor interface.  */
    resolved = xmalloc (PATH_MAX + 1);
    resolved = (char *) realpath (abspoint, resolved);
    resolved_len = resolved ? strlen (resolved) : -1;
#  endif
# endif

    if (1 <= resolved_len && resolved[0] == '/')
      {
	size_t best_match_len = 0;

	for (me = mount_list; me; me = me->me_next)
	  if (! me->me_dummy)
	    {
	      size_t len = strlen (me->me_mountdir);
	      if (best_match_len < len && len <= resolved_len
		  && (len == 1 /* root file system */
		      || ((len == resolved_len || resolved[len] == '/')
			  && strncmp (me->me_mountdir, resolved, len) == 0)))
		{
		  best_match = me;
		  best_match_len = len;
		}
	    }
      }

    if (resolved)
      free (resolved);

    if (best_match && !STREQ (best_match->me_type, "lofs")
	&& stat (best_match->me_mountdir, &disk_stats) == 0
	&& disk_stats.st_dev == statp->st_dev)
      {
	me = best_match;
	goto show_me;
      }
  }
#endif

  for (me = mount_list; me; me = me->me_next)
    {
      if (me->me_dev == (dev_t) -1)
	{
	  if (stat (me->me_mountdir, &disk_stats) == 0)
	    me->me_dev = disk_stats.st_dev;
	  else
	    {
	      error (0, errno, "%s", quote (me->me_mountdir));
	      exit_status = 1;
	      /* So we won't try and fail repeatedly. */
	      me->me_dev = (dev_t) -2;
	    }
	}

      if (statp->st_dev == me->me_dev)
	{
	  /* Skip bogus mtab entries.  */
	  if (stat (me->me_mountdir, &disk_stats) != 0
	      || disk_stats.st_dev != me->me_dev)
	    {
	      me->me_dev = (dev_t) -2;
	      continue;
	    }

	  /* Prefer non-dummy entries.  */
	  if (! me->me_dummy)
	    goto show_me;
	  matching_dummy = me;
	}
    }

  if (matching_dummy)
    goto show_matching_dummy;

  /* We couldn't find the mount entry corresponding to POINT.  Go ahead and
     print as much info as we can; methods that require the device to be
     present will fail at a later point.  */
  {
    /* Find the actual mount point.  */
    char *mp = find_mount_point (point, statp);
    if (mp)
      {
	show_dev (0, mp, 0, 0, 0);
	free (mp);
      }
    else
      error (0, errno, "%s", quote (point));
  }

  goto free_then_return;

 show_matching_dummy:
  me = matching_dummy;
 show_me:
  show_dev (me->me_devname, me->me_mountdir, me->me_type, me->me_dummy,
	    me->me_remote);
 free_then_return:
  if (needs_freeing)
    free (needs_freeing);
}

/* Determine what kind of node PATH is and show the disk usage
   for it.  STATP is the results of `stat' on PATH.  */

static void
show_entry (const char *path, const struct stat *statp)
{
  if (S_ISBLK (statp->st_mode) || S_ISCHR (statp->st_mode))
    show_disk (path);
  else
    show_point (path, statp);
}

/* Show all mounted filesystems, except perhaps those that are of
   an unselected type or are empty. */

static void
show_all_entries (void)
{
  struct mount_entry *me;

  for (me = mount_list; me; me = me->me_next)
    show_dev (me->me_devname, me->me_mountdir, me->me_type,
	      me->me_dummy, me->me_remote);
}

/* Add FSTYPE to the list of filesystem types to display. */

static void
add_fs_type (const char *fstype)
{
  struct fs_type_list *fsp;

  fsp = (struct fs_type_list *) xmalloc (sizeof (struct fs_type_list));
  fsp->fs_name = (char *) fstype;
  fsp->fs_next = fs_select_list;
  fs_select_list = fsp;
}

/* Add FSTYPE to the list of filesystem types to be omitted. */

static void
add_excluded_fs_type (const char *fstype)
{
  struct fs_type_list *fsp;

  fsp = (struct fs_type_list *) xmalloc (sizeof (struct fs_type_list));
  fsp->fs_name = (char *) fstype;
  fsp->fs_next = fs_exclude_list;
  fs_exclude_list = fsp;
}

void
usage (int status)
{
  if (status != 0)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
	     program_name);
  else
    {
      printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
      fputs (_("\
Show information about the filesystem on which each FILE resides,\n\
or all filesystems by default.\n\
\n\
"), stdout);
      fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
      fputs (_("\
  -a, --all             include filesystems having 0 blocks\n\
      --block-size=SIZE use SIZE-byte blocks\n\
  -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)\n\
  -H, --si              likewise, but use powers of 1000 not 1024\n\
"), stdout);
      fputs (_("\
  -i, --inodes          list inode information instead of block usage\n\
  -k, --kilobytes       like --block-size=1024\n\
  -l, --local           limit listing to local filesystems\n\
  -m, --megabytes       like --block-size=1048576\n\
      --no-sync         do not invoke sync before getting usage info (default)\n\
"), stdout);
      fputs (_("\
  -P, --portability     use the POSIX output format\n\
      --sync            invoke sync before getting usage info\n\
  -t, --type=TYPE       limit listing to filesystems of type TYPE\n\
  -T, --print-type      print filesystem type\n\
  -x, --exclude-type=TYPE   limit listing to filesystems not of type TYPE\n\
  -v                    (ignored)\n\
"), stdout);
      fputs (_("\
      --help            display this help and exit\n\
      --version         output version information and exit\n\
"), stdout);
      puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
    }
  exit (status);
}

int
main (int argc, char **argv)
{
  int c;
  struct stat *stats IF_LINT (= 0);
  int n_valid_args = 0;

  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  fs_select_list = NULL;
  fs_exclude_list = NULL;
  inode_format = 0;
  show_all_fs = 0;
  show_listed_fs = 0;

  human_block_size (getenv ("DF_BLOCK_SIZE"), 0, &output_block_size);

  print_type = 0;
  posix_format = 0;
  exit_status = 0;

  while ((c = getopt_long (argc, argv, "aiF:hHklmPTt:vx:", long_options, NULL))
	 != -1)
    {
      switch (c)
	{
	case 0:			/* Long option. */
	  break;
	case 'a':
	  show_all_fs = 1;
	  break;
	case 'i':
	  inode_format = 1;
	  break;
	case 'h':
	  output_block_size = -1024;
	  break;
	case 'H':
	  output_block_size = -1000;
	  break;
	case 'k':
	  output_block_size = 1024;
	  break;
	case 'l':
	  show_local_fs = 1;
	  break;
	case 'm':
	  output_block_size = 1024 * 1024;
	  break;
	case 'T':
	  print_type = 1;
	  break;
	case 'P':
	  posix_format = 1;
	  break;
	case SYNC_OPTION:
	  require_sync = 1;
	  break;
	case NO_SYNC_OPTION:
	  require_sync = 0;
	  break;

	case BLOCK_SIZE_OPTION:
	  human_block_size (optarg, 1, &output_block_size);
	  break;

	case 'F':
	  /* Accept -F as a synonym for -t for compatibility with Solaris.  */
	case 't':
	  add_fs_type (optarg);
	  break;

	case 'v':		/* For SysV compatibility. */
	  /* ignore */
	  break;
	case 'x':
	  add_excluded_fs_type (optarg);
	  break;

	case_GETOPT_HELP_CHAR;
	case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);

	default:
	  usage (1);
	}
    }

  /* Fail if the same file system type was both selected and excluded.  */
  {
    int match = 0;
    struct fs_type_list *fs_incl;
    for (fs_incl = fs_select_list; fs_incl; fs_incl = fs_incl->fs_next)
      {
	struct fs_type_list *fs_excl;
	for (fs_excl = fs_exclude_list; fs_excl; fs_excl = fs_excl->fs_next)
	  {
	    if (STREQ (fs_incl->fs_name, fs_excl->fs_name))
	      {
		error (0, 0,
		       _("file system type %s both selected and excluded"),
		       quote (fs_incl->fs_name));
		match = 1;
		break;
	      }
	  }
      }
    if (match)
      exit (1);
  }

  {
    int i;

    /* stat all the given entries to make sure they get automounted,
       if necessary, before reading the filesystem table.  */
    stats = (struct stat *)
      xmalloc ((argc - optind) * sizeof (struct stat));
    for (i = optind; i < argc; ++i)
      {
	if (stat (argv[i], &stats[i - optind]))
	  {
	    error (0, errno, "%s", quote (argv[i]));
	    exit_status = 1;
	    argv[i] = NULL;
	  }
	else
	  {
	    ++n_valid_args;
	  }
      }
  }

  mount_list =
    read_filesystem_list ((fs_select_list != NULL
			   || fs_exclude_list != NULL
			   || print_type
			   || show_local_fs));

  if (mount_list == NULL)
    {
      /* Couldn't read the table of mounted filesystems.
	 Fail if df was invoked with no file name arguments;
	 Otherwise, merely give a warning and proceed.  */
      const char *warning = (optind == argc ? "" : _("Warning: "));
      int status = (optind == argc ? 1 : 0);
      error (status, errno,
	     _("%scannot read table of mounted filesystems"), warning);
    }

  if (require_sync)
    sync ();

  if (optind == argc)
    {
      print_header ();
      show_all_entries ();
    }
  else
    {
      int i;

      /* Display explicitly requested empty filesystems. */
      show_listed_fs = 1;

      if (n_valid_args > 0)
	print_header ();

      for (i = optind; i < argc; ++i)
	if (argv[i])
	  show_entry (argv[i], &stats[i - optind]);
    }

  exit (exit_status);
}