PageRenderTime 659ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/coreutils-8.17/src/df.c

#
C | 1141 lines | 819 code | 159 blank | 163 comment | 206 complexity | 5fa05c936421e99fe09e13d53e60ae27 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.0
  1. /* df - summarize free disk space
  2. Copyright (C) 1991-2012 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /* Written by David MacKenzie <djm@gnu.ai.mit.edu>.
  14. --human-readable and --megabyte options added by lm@sgi.com.
  15. --si and large file support added by eggert@twinsun.com. */
  16. #include <config.h>
  17. #include <stdio.h>
  18. #include <sys/types.h>
  19. #include <getopt.h>
  20. #include <assert.h>
  21. #include "system.h"
  22. #include "canonicalize.h"
  23. #include "error.h"
  24. #include "fsusage.h"
  25. #include "human.h"
  26. #include "mbsalign.h"
  27. #include "mbswidth.h"
  28. #include "mountlist.h"
  29. #include "quote.h"
  30. #include "find-mount-point.h"
  31. /* The official name of this program (e.g., no 'g' prefix). */
  32. #define PROGRAM_NAME "df"
  33. #define AUTHORS \
  34. proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
  35. proper_name ("David MacKenzie"), \
  36. proper_name ("Paul Eggert")
  37. /* If true, show inode information. */
  38. static bool inode_format;
  39. /* If true, show even file systems with zero size or
  40. uninteresting types. */
  41. static bool show_all_fs;
  42. /* If true, show only local file systems. */
  43. static bool show_local_fs;
  44. /* If true, output data for each file system corresponding to a
  45. command line argument -- even if it's a dummy (automounter) entry. */
  46. static bool show_listed_fs;
  47. /* Human-readable options for output. */
  48. static int human_output_opts;
  49. /* The units to use when printing sizes. */
  50. static uintmax_t output_block_size;
  51. /* If true, use the POSIX output format. */
  52. static bool posix_format;
  53. /* True if a file system has been processed for output. */
  54. static bool file_systems_processed;
  55. /* If true, invoke the 'sync' system call before getting any usage data.
  56. Using this option can make df very slow, especially with many or very
  57. busy disks. Note that this may make a difference on some systems --
  58. SunOS 4.1.3, for one. It is *not* necessary on GNU/Linux. */
  59. static bool require_sync;
  60. /* Desired exit status. */
  61. static int exit_status;
  62. /* A file system type to display. */
  63. struct fs_type_list
  64. {
  65. char *fs_name;
  66. struct fs_type_list *fs_next;
  67. };
  68. /* Linked list of file system types to display.
  69. If 'fs_select_list' is NULL, list all types.
  70. This table is generated dynamically from command-line options,
  71. rather than hardcoding into the program what it thinks are the
  72. valid file system types; let the user specify any file system type
  73. they want to, and if there are any file systems of that type, they
  74. will be shown.
  75. Some file system types:
  76. 4.2 4.3 ufs nfs swap ignore io vm efs dbg */
  77. static struct fs_type_list *fs_select_list;
  78. /* Linked list of file system types to omit.
  79. If the list is empty, don't exclude any types. */
  80. static struct fs_type_list *fs_exclude_list;
  81. /* Linked list of mounted file systems. */
  82. static struct mount_entry *mount_list;
  83. /* If true, print file system type as well. */
  84. static bool print_type;
  85. /* If true, print a grand total at the end. */
  86. static bool print_grand_total;
  87. /* If true, show statistics for a file instead of mount point. */
  88. static bool direct_statfs;
  89. /* Grand total data. */
  90. static struct fs_usage grand_fsu;
  91. /* Display modes. */
  92. enum { DEFAULT_MODE, INODES_MODE, HUMAN_MODE, POSIX_MODE, NMODES };
  93. static int header_mode = DEFAULT_MODE;
  94. /* Displayable fields. */
  95. enum
  96. {
  97. DEV_FIELD, /* file system */
  98. TYPE_FIELD, /* FS type */
  99. TOTAL_FIELD, /* blocks or inodes */
  100. USED_FIELD, /* ditto */
  101. FREE_FIELD, /* ditto */
  102. PCENT_FIELD, /* percent used */
  103. MNT_FIELD, /* mount point */
  104. NFIELDS
  105. };
  106. /* Header strings for the above fields in each mode.
  107. NULL means to use the header for the default mode. */
  108. static const char *headers[NFIELDS][NMODES] = {
  109. /* DEFAULT_MODE INODES_MODE HUMAN_MODE POSIX_MODE */
  110. { N_("Filesystem"), NULL, NULL, NULL },
  111. { N_("Type"), NULL, NULL, NULL },
  112. { N_("blocks"), N_("Inodes"), N_("Size"), NULL },
  113. { N_("Used"), N_("IUsed"), NULL, NULL },
  114. { N_("Available"), N_("IFree"), N_("Avail"), NULL },
  115. { N_("Use%"), N_("IUse%"), NULL, N_("Capacity") },
  116. { N_("Mounted on"), NULL, NULL, NULL }
  117. };
  118. /* Alignments for the 3 textual and 4 numeric fields. */
  119. static mbs_align_t alignments[NFIELDS] = {
  120. MBS_ALIGN_LEFT, MBS_ALIGN_LEFT,
  121. MBS_ALIGN_RIGHT, MBS_ALIGN_RIGHT, MBS_ALIGN_RIGHT, MBS_ALIGN_RIGHT,
  122. MBS_ALIGN_LEFT
  123. };
  124. /* Auto adjusted (up) widths used to align columns. */
  125. static size_t widths[NFIELDS] = { 14, 4, 5, 5, 5, 4, 0 };
  126. /* Storage for pointers for each string (cell of table). */
  127. static char ***table;
  128. /* The current number of processed rows (including header). */
  129. static size_t nrows;
  130. /* For long options that have no equivalent short option, use a
  131. non-character as a pseudo short option, starting with CHAR_MAX + 1. */
  132. enum
  133. {
  134. NO_SYNC_OPTION = CHAR_MAX + 1,
  135. SYNC_OPTION,
  136. DIRECT_OPTION
  137. };
  138. static struct option const long_options[] =
  139. {
  140. {"all", no_argument, NULL, 'a'},
  141. {"block-size", required_argument, NULL, 'B'},
  142. {"direct", no_argument, NULL, DIRECT_OPTION},
  143. {"inodes", no_argument, NULL, 'i'},
  144. {"human-readable", no_argument, NULL, 'h'},
  145. {"si", no_argument, NULL, 'H'},
  146. {"local", no_argument, NULL, 'l'},
  147. {"megabytes", no_argument, NULL, 'm'}, /* obsolescent */
  148. {"portability", no_argument, NULL, 'P'},
  149. {"print-type", no_argument, NULL, 'T'},
  150. {"sync", no_argument, NULL, SYNC_OPTION},
  151. {"no-sync", no_argument, NULL, NO_SYNC_OPTION},
  152. {"total", no_argument, NULL, 'c'},
  153. {"type", required_argument, NULL, 't'},
  154. {"exclude-type", required_argument, NULL, 'x'},
  155. {GETOPT_HELP_OPTION_DECL},
  156. {GETOPT_VERSION_OPTION_DECL},
  157. {NULL, 0, NULL, 0}
  158. };
  159. /* Dynamically allocate a row of pointers in TABLE, which
  160. can then be accessed with standard 2D array notation. */
  161. static void
  162. alloc_table_row (void)
  163. {
  164. nrows++;
  165. table = xnrealloc (table, nrows, sizeof (char *));
  166. table[nrows-1] = xnmalloc (NFIELDS, sizeof (char *));
  167. }
  168. /* Output each cell in the table, accounting for the
  169. alignment and max width of each column. */
  170. static void
  171. print_table (void)
  172. {
  173. size_t field, row;
  174. for (row = 0; row < nrows; row ++)
  175. {
  176. for (field = 0; field < NFIELDS; field++)
  177. {
  178. size_t width = widths[field];
  179. char *cell = table[row][field];
  180. if (!cell) /* Missing type column, or mount point etc. */
  181. continue;
  182. /* Note the DEV_FIELD used to be displayed on it's own line
  183. if (!posix_format && mbswidth (cell) > 20), but that
  184. functionality is probably more problematic than helpful. */
  185. if (field != 0)
  186. putchar (' ');
  187. if (field == MNT_FIELD) /* The last one. */
  188. fputs (cell, stdout);
  189. else
  190. {
  191. cell = ambsalign (cell, &width, alignments[field], 0);
  192. /* When ambsalign fails, output unaligned data. */
  193. fputs (cell ? cell : table[row][field], stdout);
  194. free (cell);
  195. }
  196. IF_LINT (free (table[row][field]));
  197. }
  198. putchar ('\n');
  199. IF_LINT (free (table[row]));
  200. }
  201. IF_LINT (free (table));
  202. }
  203. /* Obtain the appropriate header entries. */
  204. static void
  205. get_header (void)
  206. {
  207. size_t field;
  208. alloc_table_row ();
  209. for (field = 0; field < NFIELDS; field++)
  210. {
  211. if (field == TYPE_FIELD && !print_type)
  212. {
  213. table[nrows-1][field] = NULL;
  214. continue;
  215. }
  216. char *cell = NULL;
  217. char const *header = (field == MNT_FIELD && direct_statfs)?
  218. _("File") :
  219. _(headers[field][header_mode]);
  220. if (!header)
  221. header = _(headers[field][DEFAULT_MODE]);
  222. if (header_mode == DEFAULT_MODE && field == TOTAL_FIELD)
  223. {
  224. char buf[LONGEST_HUMAN_READABLE + 1];
  225. int opts = (human_suppress_point_zero
  226. | human_autoscale | human_SI
  227. | (human_output_opts
  228. & (human_group_digits | human_base_1024 | human_B)));
  229. /* Prefer the base that makes the human-readable value more exact,
  230. if there is a difference. */
  231. uintmax_t q1000 = output_block_size;
  232. uintmax_t q1024 = output_block_size;
  233. bool divisible_by_1000;
  234. bool divisible_by_1024;
  235. do
  236. {
  237. divisible_by_1000 = q1000 % 1000 == 0; q1000 /= 1000;
  238. divisible_by_1024 = q1024 % 1024 == 0; q1024 /= 1024;
  239. }
  240. while (divisible_by_1000 & divisible_by_1024);
  241. if (divisible_by_1000 < divisible_by_1024)
  242. opts |= human_base_1024;
  243. if (divisible_by_1024 < divisible_by_1000)
  244. opts &= ~human_base_1024;
  245. if (! (opts & human_base_1024))
  246. opts |= human_B;
  247. char *num = human_readable (output_block_size, buf, opts, 1, 1);
  248. if (asprintf (&cell, "%s-%s", num, header) == -1)
  249. cell = NULL;
  250. }
  251. else if (header_mode == POSIX_MODE && field == TOTAL_FIELD)
  252. {
  253. char buf[INT_BUFSIZE_BOUND (uintmax_t)];
  254. char *num = umaxtostr (output_block_size, buf);
  255. if (asprintf (&cell, "%s-%s", num, header) == -1)
  256. cell = NULL;
  257. }
  258. else
  259. cell = strdup (header);
  260. if (!cell)
  261. xalloc_die ();
  262. table[nrows-1][field] = cell;
  263. widths[field] = MAX (widths[field], mbswidth (cell, 0));
  264. }
  265. }
  266. /* Is FSTYPE a type of file system that should be listed? */
  267. static bool _GL_ATTRIBUTE_PURE
  268. selected_fstype (const char *fstype)
  269. {
  270. const struct fs_type_list *fsp;
  271. if (fs_select_list == NULL || fstype == NULL)
  272. return true;
  273. for (fsp = fs_select_list; fsp; fsp = fsp->fs_next)
  274. if (STREQ (fstype, fsp->fs_name))
  275. return true;
  276. return false;
  277. }
  278. /* Is FSTYPE a type of file system that should be omitted? */
  279. static bool _GL_ATTRIBUTE_PURE
  280. excluded_fstype (const char *fstype)
  281. {
  282. const struct fs_type_list *fsp;
  283. if (fs_exclude_list == NULL || fstype == NULL)
  284. return false;
  285. for (fsp = fs_exclude_list; fsp; fsp = fsp->fs_next)
  286. if (STREQ (fstype, fsp->fs_name))
  287. return true;
  288. return false;
  289. }
  290. /* Return true if N is a known integer value. On many file systems,
  291. UINTMAX_MAX represents an unknown value; on AIX, UINTMAX_MAX - 1
  292. represents unknown. Use a rule that works on AIX file systems, and
  293. that almost-always works on other types. */
  294. static bool
  295. known_value (uintmax_t n)
  296. {
  297. return n < UINTMAX_MAX - 1;
  298. }
  299. /* Like human_readable (N, BUF, human_output_opts, INPUT_UNITS, OUTPUT_UNITS),
  300. except:
  301. - If NEGATIVE, then N represents a negative number,
  302. expressed in two's complement.
  303. - Otherwise, return "-" if N is unknown. */
  304. static char const *
  305. df_readable (bool negative, uintmax_t n, char *buf,
  306. uintmax_t input_units, uintmax_t output_units)
  307. {
  308. if (! known_value (n) && !negative)
  309. return "-";
  310. else
  311. {
  312. char *p = human_readable (negative ? -n : n, buf + negative,
  313. human_output_opts, input_units, output_units);
  314. if (negative)
  315. *--p = '-';
  316. return p;
  317. }
  318. }
  319. /* Logical equivalence */
  320. #define LOG_EQ(a, b) (!(a) == !(b))
  321. /* Add integral value while using uintmax_t for value part and separate
  322. negation flag. It adds value of SRC and SRC_NEG to DEST and DEST_NEG.
  323. The result will be in DEST and DEST_NEG. See df_readable to understand
  324. how the negation flag is used. */
  325. static void
  326. add_uint_with_neg_flag (uintmax_t *dest, bool *dest_neg,
  327. uintmax_t src, bool src_neg)
  328. {
  329. if (LOG_EQ (*dest_neg, src_neg))
  330. {
  331. *dest += src;
  332. return;
  333. }
  334. if (*dest_neg)
  335. *dest = -*dest;
  336. if (src_neg)
  337. src = -src;
  338. if (src < *dest)
  339. *dest -= src;
  340. else
  341. {
  342. *dest = src - *dest;
  343. *dest_neg = src_neg;
  344. }
  345. if (*dest_neg)
  346. *dest = -*dest;
  347. }
  348. /* Return true if S ends in a string that may be a 36-byte UUID,
  349. i.e., of the form HHHHHHHH-HHHH-HHHH-HHHH-HHHHHHHHHHHH, where
  350. each H is an upper or lower case hexadecimal digit. */
  351. static bool _GL_ATTRIBUTE_PURE
  352. has_uuid_suffix (char const *s)
  353. {
  354. size_t len = strlen (s);
  355. return (36 < len
  356. && strspn (s + len - 36, "-0123456789abcdefABCDEF") == 36);
  357. }
  358. /* Obtain a space listing for the disk device with absolute file name DISK.
  359. If MOUNT_POINT is non-NULL, it is the name of the root of the
  360. file system on DISK.
  361. If STAT_FILE is non-null, it is the name of a file within the file
  362. system that the user originally asked for; this provides better
  363. diagnostics, and sometimes it provides better results on networked
  364. file systems that give different free-space results depending on
  365. where in the file system you probe.
  366. If FSTYPE is non-NULL, it is the type of the file system on DISK.
  367. If MOUNT_POINT is non-NULL, then DISK may be NULL -- certain systems may
  368. not be able to produce statistics in this case.
  369. ME_DUMMY and ME_REMOTE are the mount entry flags.
  370. Caller must set PROCESS_ALL to true when iterating over all entries, as
  371. when df is invoked with no non-option argument. See below for details. */
  372. static void
  373. get_dev (char const *disk, char const *mount_point,
  374. char const *stat_file, char const *fstype,
  375. bool me_dummy, bool me_remote,
  376. const struct fs_usage *force_fsu,
  377. bool process_all)
  378. {
  379. struct fs_usage fsu;
  380. char buf[LONGEST_HUMAN_READABLE + 2];
  381. uintmax_t input_units;
  382. uintmax_t output_units;
  383. uintmax_t total;
  384. uintmax_t available;
  385. bool negate_available;
  386. uintmax_t available_to_root;
  387. uintmax_t used;
  388. bool negate_used;
  389. double pct = -1;
  390. char* cell;
  391. size_t field;
  392. if (me_remote && show_local_fs)
  393. return;
  394. if (me_dummy && !show_all_fs && !show_listed_fs)
  395. return;
  396. if (!selected_fstype (fstype) || excluded_fstype (fstype))
  397. return;
  398. /* If MOUNT_POINT is NULL, then the file system is not mounted, and this
  399. program reports on the file system that the special file is on.
  400. It would be better to report on the unmounted file system,
  401. but statfs doesn't do that on most systems. */
  402. if (!stat_file)
  403. stat_file = mount_point ? mount_point : disk;
  404. if (force_fsu)
  405. fsu = *force_fsu;
  406. else if (get_fs_usage (stat_file, disk, &fsu))
  407. {
  408. error (0, errno, "%s", quote (stat_file));
  409. exit_status = EXIT_FAILURE;
  410. return;
  411. }
  412. if (fsu.fsu_blocks == 0 && !show_all_fs && !show_listed_fs)
  413. return;
  414. if (! file_systems_processed)
  415. {
  416. file_systems_processed = true;
  417. get_header ();
  418. }
  419. alloc_table_row ();
  420. if (! disk)
  421. disk = "-"; /* unknown */
  422. char *dev_name = xstrdup (disk);
  423. char *resolved_dev;
  424. /* On some systems, dev_name is a long-named symlink like
  425. /dev/disk/by-uuid/828fc648-9f30-43d8-a0b1-f7196a2edb66 pointing to a
  426. much shorter and more useful name like /dev/sda1. It may also look
  427. like /dev/mapper/luks-828fc648-9f30-43d8-a0b1-f7196a2edb66 and point to
  428. /dev/dm-0. When process_all is true and dev_name is a symlink whose
  429. name ends with a UUID use the resolved name instead. */
  430. if (process_all
  431. && has_uuid_suffix (dev_name)
  432. && (resolved_dev = canonicalize_filename_mode (dev_name, CAN_EXISTING)))
  433. {
  434. free (dev_name);
  435. dev_name = resolved_dev;
  436. }
  437. if (! fstype)
  438. fstype = "-"; /* unknown */
  439. if (inode_format)
  440. {
  441. input_units = output_units = 1;
  442. total = fsu.fsu_files;
  443. available = fsu.fsu_ffree;
  444. negate_available = false;
  445. available_to_root = available;
  446. if (known_value (total))
  447. grand_fsu.fsu_files += total;
  448. if (known_value (available))
  449. grand_fsu.fsu_ffree += available;
  450. }
  451. else
  452. {
  453. input_units = fsu.fsu_blocksize;
  454. output_units = output_block_size;
  455. total = fsu.fsu_blocks;
  456. available = fsu.fsu_bavail;
  457. negate_available = (fsu.fsu_bavail_top_bit_set
  458. && known_value (available));
  459. available_to_root = fsu.fsu_bfree;
  460. if (known_value (total))
  461. grand_fsu.fsu_blocks += input_units * total;
  462. if (known_value (available_to_root))
  463. grand_fsu.fsu_bfree += input_units * available_to_root;
  464. if (known_value (available))
  465. add_uint_with_neg_flag (&grand_fsu.fsu_bavail,
  466. &grand_fsu.fsu_bavail_top_bit_set,
  467. input_units * available, negate_available);
  468. }
  469. used = UINTMAX_MAX;
  470. negate_used = false;
  471. if (known_value (total) && known_value (available_to_root))
  472. {
  473. used = total - available_to_root;
  474. negate_used = (total < available_to_root);
  475. }
  476. for (field = 0; field < NFIELDS; field++)
  477. {
  478. switch (field)
  479. {
  480. case DEV_FIELD:
  481. cell = dev_name;
  482. break;
  483. case TYPE_FIELD:
  484. cell = print_type ? xstrdup (fstype) : NULL;
  485. break;
  486. case TOTAL_FIELD:
  487. cell = xstrdup (df_readable (false, total, buf,
  488. input_units, output_units));
  489. break;
  490. case USED_FIELD:
  491. cell = xstrdup (df_readable (negate_used, used, buf,
  492. input_units, output_units));
  493. break;
  494. case FREE_FIELD:
  495. cell = xstrdup (df_readable (negate_available, available, buf,
  496. input_units, output_units));
  497. break;
  498. case PCENT_FIELD:
  499. if (! known_value (used) || ! known_value (available))
  500. ;
  501. else if (!negate_used
  502. && used <= TYPE_MAXIMUM (uintmax_t) / 100
  503. && used + available != 0
  504. && (used + available < used) == negate_available)
  505. {
  506. uintmax_t u100 = used * 100;
  507. uintmax_t nonroot_total = used + available;
  508. pct = u100 / nonroot_total + (u100 % nonroot_total != 0);
  509. }
  510. else
  511. {
  512. /* The calculation cannot be done easily with integer
  513. arithmetic. Fall back on floating point. This can suffer
  514. from minor rounding errors, but doing it exactly requires
  515. multiple precision arithmetic, and it's not worth the
  516. aggravation. */
  517. double u = negate_used ? - (double) - used : used;
  518. double a = negate_available ? - (double) - available : available;
  519. double nonroot_total = u + a;
  520. if (nonroot_total)
  521. {
  522. long int lipct = pct = u * 100 / nonroot_total;
  523. double ipct = lipct;
  524. /* Like 'pct = ceil (dpct);', but avoid ceil so that
  525. the math library needn't be linked. */
  526. if (ipct - 1 < pct && pct <= ipct + 1)
  527. pct = ipct + (ipct < pct);
  528. }
  529. }
  530. if (0 <= pct)
  531. {
  532. if (asprintf (&cell, "%.0f%%", pct) == -1)
  533. cell = NULL;
  534. }
  535. else
  536. cell = strdup ("-");
  537. if (!cell)
  538. xalloc_die ();
  539. break;
  540. case MNT_FIELD:
  541. if (mount_point)
  542. {
  543. #ifdef HIDE_AUTOMOUNT_PREFIX
  544. /* Don't print the first directory name in MOUNT_POINT if it's an
  545. artifact of an automounter. This is a bit too aggressive to be
  546. the default. */
  547. if (STRNCMP_LIT (mount_point, "/auto/") == 0)
  548. mount_point += 5;
  549. else if (STRNCMP_LIT (mount_point, "/tmp_mnt/") == 0)
  550. mount_point += 8;
  551. #endif
  552. cell = xstrdup (mount_point);
  553. }
  554. else
  555. cell = NULL;
  556. break;
  557. default:
  558. assert (!"unhandled field");
  559. }
  560. if (cell)
  561. widths[field] = MAX (widths[field], mbswidth (cell, 0));
  562. table[nrows-1][field] = cell;
  563. }
  564. }
  565. /* If DISK corresponds to a mount point, show its usage
  566. and return true. Otherwise, return false. */
  567. static bool
  568. get_disk (char const *disk)
  569. {
  570. struct mount_entry const *me;
  571. struct mount_entry const *best_match = NULL;
  572. for (me = mount_list; me; me = me->me_next)
  573. if (STREQ (disk, me->me_devname))
  574. best_match = me;
  575. if (best_match)
  576. {
  577. get_dev (best_match->me_devname, best_match->me_mountdir, NULL,
  578. best_match->me_type, best_match->me_dummy,
  579. best_match->me_remote, NULL, false);
  580. return true;
  581. }
  582. return false;
  583. }
  584. /* Figure out which device file or directory POINT is mounted on
  585. and show its disk usage.
  586. STATP must be the result of 'stat (POINT, STATP)'. */
  587. static void
  588. get_point (const char *point, const struct stat *statp)
  589. {
  590. struct stat disk_stats;
  591. struct mount_entry *me;
  592. struct mount_entry const *best_match = NULL;
  593. /* Calculate the real absolute file name for POINT, and use that to find
  594. the mount point. This avoids statting unavailable mount points,
  595. which can hang df. */
  596. char *resolved = canonicalize_file_name (point);
  597. if (resolved && resolved[0] == '/')
  598. {
  599. size_t resolved_len = strlen (resolved);
  600. size_t best_match_len = 0;
  601. for (me = mount_list; me; me = me->me_next)
  602. if (!STREQ (me->me_type, "lofs")
  603. && (!best_match || best_match->me_dummy || !me->me_dummy))
  604. {
  605. size_t len = strlen (me->me_mountdir);
  606. if (best_match_len <= len && len <= resolved_len
  607. && (len == 1 /* root file system */
  608. || ((len == resolved_len || resolved[len] == '/')
  609. && STREQ_LEN (me->me_mountdir, resolved, len))))
  610. {
  611. best_match = me;
  612. best_match_len = len;
  613. }
  614. }
  615. }
  616. free (resolved);
  617. if (best_match
  618. && (stat (best_match->me_mountdir, &disk_stats) != 0
  619. || disk_stats.st_dev != statp->st_dev))
  620. best_match = NULL;
  621. if (! best_match)
  622. for (me = mount_list; me; me = me->me_next)
  623. {
  624. if (me->me_dev == (dev_t) -1)
  625. {
  626. if (stat (me->me_mountdir, &disk_stats) == 0)
  627. me->me_dev = disk_stats.st_dev;
  628. else
  629. {
  630. /* Report only I/O errors. Other errors might be
  631. caused by shadowed mount points, which means POINT
  632. can't possibly be on this file system. */
  633. if (errno == EIO)
  634. {
  635. error (0, errno, "%s", quote (me->me_mountdir));
  636. exit_status = EXIT_FAILURE;
  637. }
  638. /* So we won't try and fail repeatedly. */
  639. me->me_dev = (dev_t) -2;
  640. }
  641. }
  642. if (statp->st_dev == me->me_dev
  643. && !STREQ (me->me_type, "lofs")
  644. && (!best_match || best_match->me_dummy || !me->me_dummy))
  645. {
  646. /* Skip bogus mtab entries. */
  647. if (stat (me->me_mountdir, &disk_stats) != 0
  648. || disk_stats.st_dev != me->me_dev)
  649. me->me_dev = (dev_t) -2;
  650. else
  651. best_match = me;
  652. }
  653. }
  654. if (best_match)
  655. get_dev (best_match->me_devname, best_match->me_mountdir, point,
  656. best_match->me_type, best_match->me_dummy, best_match->me_remote,
  657. NULL, false);
  658. else
  659. {
  660. /* We couldn't find the mount entry corresponding to POINT. Go ahead and
  661. print as much info as we can; methods that require the device to be
  662. present will fail at a later point. */
  663. /* Find the actual mount point. */
  664. char *mp = find_mount_point (point, statp);
  665. if (mp)
  666. {
  667. get_dev (NULL, mp, NULL, NULL, false, false, NULL, false);
  668. free (mp);
  669. }
  670. }
  671. }
  672. /* Determine what kind of node NAME is and show the disk usage
  673. for it. STATP is the results of 'stat' on NAME. */
  674. static void
  675. get_entry (char const *name, struct stat const *statp)
  676. {
  677. if (direct_statfs)
  678. {
  679. char *resolved = canonicalize_file_name (name);
  680. if (resolved)
  681. {
  682. get_dev (NULL, resolved, NULL, NULL, false, false, NULL, false);
  683. free (resolved);
  684. return;
  685. }
  686. }
  687. if ((S_ISBLK (statp->st_mode) || S_ISCHR (statp->st_mode))
  688. && get_disk (name))
  689. return;
  690. get_point (name, statp);
  691. }
  692. /* Show all mounted file systems, except perhaps those that are of
  693. an unselected type or are empty. */
  694. static void
  695. get_all_entries (void)
  696. {
  697. struct mount_entry *me;
  698. for (me = mount_list; me; me = me->me_next)
  699. get_dev (me->me_devname, me->me_mountdir, NULL, me->me_type,
  700. me->me_dummy, me->me_remote, NULL, true);
  701. }
  702. /* Add FSTYPE to the list of file system types to display. */
  703. static void
  704. add_fs_type (const char *fstype)
  705. {
  706. struct fs_type_list *fsp;
  707. fsp = xmalloc (sizeof *fsp);
  708. fsp->fs_name = (char *) fstype;
  709. fsp->fs_next = fs_select_list;
  710. fs_select_list = fsp;
  711. }
  712. /* Add FSTYPE to the list of file system types to be omitted. */
  713. static void
  714. add_excluded_fs_type (const char *fstype)
  715. {
  716. struct fs_type_list *fsp;
  717. fsp = xmalloc (sizeof *fsp);
  718. fsp->fs_name = (char *) fstype;
  719. fsp->fs_next = fs_exclude_list;
  720. fs_exclude_list = fsp;
  721. }
  722. void
  723. usage (int status)
  724. {
  725. if (status != EXIT_SUCCESS)
  726. emit_try_help ();
  727. else
  728. {
  729. printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
  730. fputs (_("\
  731. Show information about the file system on which each FILE resides,\n\
  732. or all file systems by default.\n\
  733. \n\
  734. "), stdout);
  735. fputs (_("\
  736. Mandatory arguments to long options are mandatory for short options too.\n\
  737. "), stdout);
  738. fputs (_("\
  739. -a, --all include dummy file systems\n\
  740. -B, --block-size=SIZE scale sizes by SIZE before printing them. E.g.,\n\
  741. '-BM' prints sizes in units of 1,048,576 bytes.\n\
  742. See SIZE format below.\n\
  743. --direct show statistics for a file instead of mount point\n\
  744. --total produce a grand total\n\
  745. -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\
  746. \n\
  747. -H, --si likewise, but use powers of 1000 not 1024\n\
  748. "), stdout);
  749. fputs (_("\
  750. -i, --inodes list inode information instead of block usage\n\
  751. -k like --block-size=1K\n\
  752. -l, --local limit listing to local file systems\n\
  753. --no-sync do not invoke sync before getting usage info (default)\
  754. \n\
  755. "), stdout);
  756. fputs (_("\
  757. -P, --portability use the POSIX output format\n\
  758. --sync invoke sync before getting usage info\n\
  759. -t, --type=TYPE limit listing to file systems of type TYPE\n\
  760. -T, --print-type print file system type\n\
  761. -x, --exclude-type=TYPE limit listing to file systems not of type TYPE\n\
  762. -v (ignored)\n\
  763. "), stdout);
  764. fputs (HELP_OPTION_DESCRIPTION, stdout);
  765. fputs (VERSION_OPTION_DESCRIPTION, stdout);
  766. emit_blocksize_note ("DF");
  767. emit_size_note ();
  768. emit_ancillary_info ();
  769. }
  770. exit (status);
  771. }
  772. int
  773. main (int argc, char **argv)
  774. {
  775. struct stat *stats IF_LINT ( = 0);
  776. initialize_main (&argc, &argv);
  777. set_program_name (argv[0]);
  778. setlocale (LC_ALL, "");
  779. bindtextdomain (PACKAGE, LOCALEDIR);
  780. textdomain (PACKAGE);
  781. atexit (close_stdout);
  782. fs_select_list = NULL;
  783. fs_exclude_list = NULL;
  784. inode_format = false;
  785. show_all_fs = false;
  786. show_listed_fs = false;
  787. human_output_opts = -1;
  788. print_type = false;
  789. file_systems_processed = false;
  790. posix_format = false;
  791. exit_status = EXIT_SUCCESS;
  792. print_grand_total = false;
  793. grand_fsu.fsu_blocksize = 1;
  794. while (true)
  795. {
  796. int oi = -1;
  797. int c = getopt_long (argc, argv, "aB:iF:hHklmPTt:vx:", long_options,
  798. &oi);
  799. if (c == -1)
  800. break;
  801. switch (c)
  802. {
  803. case 'a':
  804. show_all_fs = true;
  805. break;
  806. case 'B':
  807. {
  808. enum strtol_error e = human_options (optarg, &human_output_opts,
  809. &output_block_size);
  810. if (e != LONGINT_OK)
  811. xstrtol_fatal (e, oi, c, long_options, optarg);
  812. }
  813. break;
  814. case DIRECT_OPTION:
  815. direct_statfs = true;
  816. break;
  817. case 'i':
  818. inode_format = true;
  819. break;
  820. case 'h':
  821. human_output_opts = human_autoscale | human_SI | human_base_1024;
  822. output_block_size = 1;
  823. break;
  824. case 'H':
  825. human_output_opts = human_autoscale | human_SI;
  826. output_block_size = 1;
  827. break;
  828. case 'k':
  829. human_output_opts = 0;
  830. output_block_size = 1024;
  831. break;
  832. case 'l':
  833. show_local_fs = true;
  834. break;
  835. case 'm': /* obsolescent */
  836. human_output_opts = 0;
  837. output_block_size = 1024 * 1024;
  838. break;
  839. case 'T':
  840. print_type = true;
  841. break;
  842. case 'P':
  843. posix_format = true;
  844. break;
  845. case SYNC_OPTION:
  846. require_sync = true;
  847. break;
  848. case NO_SYNC_OPTION:
  849. require_sync = false;
  850. break;
  851. case 'F':
  852. /* Accept -F as a synonym for -t for compatibility with Solaris. */
  853. case 't':
  854. add_fs_type (optarg);
  855. break;
  856. case 'v': /* For SysV compatibility. */
  857. /* ignore */
  858. break;
  859. case 'x':
  860. add_excluded_fs_type (optarg);
  861. break;
  862. case 'c':
  863. print_grand_total = true;
  864. break;
  865. case_GETOPT_HELP_CHAR;
  866. case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
  867. default:
  868. usage (EXIT_FAILURE);
  869. }
  870. }
  871. if (direct_statfs && show_local_fs)
  872. {
  873. error (0, 0, _("options --direct and --local (-l) are mutually "
  874. "exclusive"));
  875. usage (EXIT_FAILURE);
  876. }
  877. if (human_output_opts == -1)
  878. {
  879. if (posix_format)
  880. {
  881. human_output_opts = 0;
  882. output_block_size = (getenv ("POSIXLY_CORRECT") ? 512 : 1024);
  883. }
  884. else
  885. human_options (getenv ("DF_BLOCK_SIZE"),
  886. &human_output_opts, &output_block_size);
  887. }
  888. if (inode_format)
  889. header_mode = INODES_MODE;
  890. else if (human_output_opts & human_autoscale)
  891. header_mode = HUMAN_MODE;
  892. else if (posix_format)
  893. header_mode = POSIX_MODE;
  894. /* Fail if the same file system type was both selected and excluded. */
  895. {
  896. bool match = false;
  897. struct fs_type_list *fs_incl;
  898. for (fs_incl = fs_select_list; fs_incl; fs_incl = fs_incl->fs_next)
  899. {
  900. struct fs_type_list *fs_excl;
  901. for (fs_excl = fs_exclude_list; fs_excl; fs_excl = fs_excl->fs_next)
  902. {
  903. if (STREQ (fs_incl->fs_name, fs_excl->fs_name))
  904. {
  905. error (0, 0,
  906. _("file system type %s both selected and excluded"),
  907. quote (fs_incl->fs_name));
  908. match = true;
  909. break;
  910. }
  911. }
  912. }
  913. if (match)
  914. exit (EXIT_FAILURE);
  915. }
  916. if (optind < argc)
  917. {
  918. int i;
  919. /* Open each of the given entries to make sure any corresponding
  920. partition is automounted. This must be done before reading the
  921. file system table. */
  922. stats = xnmalloc (argc - optind, sizeof *stats);
  923. for (i = optind; i < argc; ++i)
  924. {
  925. /* Prefer to open with O_NOCTTY and use fstat, but fall back
  926. on using "stat", in case the file is unreadable. */
  927. int fd = open (argv[i], O_RDONLY | O_NOCTTY);
  928. if ((fd < 0 || fstat (fd, &stats[i - optind]))
  929. && stat (argv[i], &stats[i - optind]))
  930. {
  931. error (0, errno, "%s", quote (argv[i]));
  932. exit_status = EXIT_FAILURE;
  933. argv[i] = NULL;
  934. }
  935. if (0 <= fd)
  936. close (fd);
  937. }
  938. }
  939. mount_list =
  940. read_file_system_list ((fs_select_list != NULL
  941. || fs_exclude_list != NULL
  942. || print_type
  943. || show_local_fs));
  944. if (mount_list == NULL)
  945. {
  946. /* Couldn't read the table of mounted file systems.
  947. Fail if df was invoked with no file name arguments;
  948. Otherwise, merely give a warning and proceed. */
  949. int status = (optind < argc ? 0 : EXIT_FAILURE);
  950. const char *warning = (optind < argc ? _("Warning: ") : "");
  951. error (status, errno, "%s%s", warning,
  952. _("cannot read table of mounted file systems"));
  953. }
  954. if (require_sync)
  955. sync ();
  956. if (optind < argc)
  957. {
  958. int i;
  959. /* Display explicitly requested empty file systems. */
  960. show_listed_fs = true;
  961. for (i = optind; i < argc; ++i)
  962. if (argv[i])
  963. get_entry (argv[i], &stats[i - optind]);
  964. }
  965. else
  966. get_all_entries ();
  967. if (print_grand_total)
  968. {
  969. if (inode_format)
  970. grand_fsu.fsu_blocks = 1;
  971. get_dev ("total", NULL, NULL, NULL, false, false, &grand_fsu, false);
  972. }
  973. print_table ();
  974. if (! file_systems_processed)
  975. error (EXIT_FAILURE, 0, _("no file systems processed"));
  976. exit (exit_status);
  977. }