blkdiscard.c 2.3 KB

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