fstrim.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * fstrim.c - discard the part (or whole) of mounted filesystem.
  4. *
  5. * 03 March 2012 - Malek Degachi <malek-degachi@laposte.net>
  6. * Adapted for busybox from util-linux-2.12a.
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. //config:config FSTRIM
  11. //config: bool "fstrim (4.4 kb)"
  12. //config: default y
  13. //config: help
  14. //config: Discard unused blocks on a mounted filesystem.
  15. //applet:IF_FSTRIM(APPLET_NOEXEC(fstrim, fstrim, BB_DIR_SBIN, BB_SUID_DROP, fstrim))
  16. //kbuild:lib-$(CONFIG_FSTRIM) += fstrim.o
  17. //usage:#define fstrim_trivial_usage
  18. //usage: "[OPTIONS] MOUNTPOINT"
  19. //usage:#define fstrim_full_usage "\n\n"
  20. //usage: " -o OFFSET Offset in bytes to discard from"
  21. //usage: "\n -l LEN Bytes to discard"
  22. //usage: "\n -m MIN Minimum extent length"
  23. //usage: "\n -v Print number of discarded bytes"
  24. #include "libbb.h"
  25. #include <linux/fs.h>
  26. #ifndef FITRIM
  27. struct fstrim_range {
  28. uint64_t start;
  29. uint64_t len;
  30. uint64_t minlen;
  31. };
  32. #define FITRIM _IOWR('X', 121, struct fstrim_range)
  33. #endif
  34. int fstrim_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  35. int fstrim_main(int argc UNUSED_PARAM, char **argv)
  36. {
  37. struct fstrim_range range;
  38. char *arg_o, *arg_l, *arg_m, *mp;
  39. unsigned opts;
  40. int fd;
  41. enum {
  42. OPT_o = (1 << 0),
  43. OPT_l = (1 << 1),
  44. OPT_m = (1 << 2),
  45. OPT_v = (1 << 3),
  46. };
  47. #if ENABLE_LONG_OPTS
  48. static const char fstrim_longopts[] ALIGN1 =
  49. "offset\0" Required_argument "o"
  50. "length\0" Required_argument "l"
  51. "minimum\0" Required_argument "m"
  52. "verbose\0" No_argument "v"
  53. ;
  54. #endif
  55. opts = getopt32long(argv, "^"
  56. "o:l:m:v"
  57. "\0" "=1", fstrim_longopts,
  58. &arg_o, &arg_l, &arg_m
  59. );
  60. memset(&range, 0, sizeof(range));
  61. range.len = ULLONG_MAX;
  62. if (opts & OPT_o)
  63. range.start = xatoull_sfx(arg_o, kmg_i_suffixes);
  64. if (opts & OPT_l)
  65. range.len = xatoull_sfx(arg_l, kmg_i_suffixes);
  66. if (opts & OPT_m)
  67. range.minlen = xatoull_sfx(arg_m, kmg_i_suffixes);
  68. mp = argv[optind];
  69. //Wwhy bother checking that it's a blockdev?
  70. // if (find_block_device(mp)) {
  71. fd = xopen_nonblocking(mp);
  72. /* On ENOTTY error, util-linux 2.31 says:
  73. * "fstrim: FILE: the discard operation is not supported"
  74. */
  75. xioctl(fd, FITRIM, &range);
  76. if (ENABLE_FEATURE_CLEAN_UP)
  77. close(fd);
  78. if (opts & OPT_v)
  79. printf("%s: %llu bytes trimmed\n", mp, (unsigned long long)range.len);
  80. return EXIT_SUCCESS;
  81. // }
  82. return EXIT_FAILURE;
  83. }