blkdiscard.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Mini blkdiscard implementation for busybox
  3. *
  4. * Copyright (C) 2015 by Ari Sundholm <ari@tuxera.com> and Tuxera Inc.
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. //config:config BLKDISCARD
  9. //config: bool "blkdiscard (4.3 kb)"
  10. //config: default y
  11. //config: help
  12. //config: blkdiscard discards sectors on a given device.
  13. //applet:IF_BLKDISCARD(APPLET_NOEXEC(blkdiscard, blkdiscard, BB_DIR_USR_BIN, BB_SUID_DROP, blkdiscard))
  14. //kbuild:lib-$(CONFIG_BLKDISCARD) += blkdiscard.o
  15. //usage:#define blkdiscard_trivial_usage
  16. //usage: "[-o OFS] [-l LEN] [-s] DEVICE"
  17. //usage:#define blkdiscard_full_usage "\n\n"
  18. //usage: "Discard sectors on DEVICE\n"
  19. //usage: "\n -o OFS Byte offset into device"
  20. //usage: "\n -l LEN Number of bytes to discard"
  21. //usage: "\n -s Perform a secure discard"
  22. //usage:
  23. //usage:#define blkdiscard_example_usage
  24. //usage: "$ blkdiscard -o 0 -l 1G /dev/sdb"
  25. #include "libbb.h"
  26. #include <linux/fs.h>
  27. #ifndef BLKDISCARD
  28. #define BLKDISCARD 0x1277
  29. #endif
  30. #ifndef BLKSECDISCARD
  31. #define BLKSECDISCARD 0x127d
  32. #endif
  33. int blkdiscard_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  34. int blkdiscard_main(int argc UNUSED_PARAM, char **argv)
  35. {
  36. unsigned opts;
  37. const char *offset_str = "0";
  38. const char *length_str;
  39. uint64_t offset; /* Leaving these two variables out does not */
  40. uint64_t length; /* shrink code size and hampers readability. */
  41. uint64_t range[2];
  42. int fd;
  43. enum {
  44. OPT_OFFSET = (1 << 0),
  45. OPT_LENGTH = (1 << 1),
  46. OPT_SECURE = (1 << 2),
  47. };
  48. opts = getopt32(argv, "^" "o:l:s" "\0" "=1", &offset_str, &length_str);
  49. argv += optind;
  50. fd = xopen(argv[0], O_RDWR|O_EXCL);
  51. //Why bother, BLK[SEC]DISCARD will fail on non-blockdevs anyway?
  52. // xfstat(fd, &st);
  53. // if (!S_ISBLK(st.st_mode))
  54. // bb_error_msg_and_die("%s: not a block device", argv[0]);
  55. offset = xatoull_sfx(offset_str, kMG_suffixes);
  56. if (opts & OPT_LENGTH)
  57. length = xatoull_sfx(length_str, kMG_suffixes);
  58. else {
  59. xioctl(fd, BLKGETSIZE64, &length);
  60. length -= offset;
  61. }
  62. range[0] = offset;
  63. range[1] = length;
  64. ioctl_or_perror_and_die(fd,
  65. (opts & OPT_SECURE) ? BLKSECDISCARD : BLKDISCARD,
  66. &range,
  67. "%s: %s failed",
  68. argv[0],
  69. (opts & OPT_SECURE) ? "BLKSECDISCARD" : "BLKDISCARD"
  70. );
  71. if (ENABLE_FEATURE_CLEAN_UP)
  72. close(fd);
  73. return EXIT_SUCCESS;
  74. }