3
0

blkdiscard.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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"
  10. //config: default y
  11. //config: help
  12. //config: blkdiscard discards sectors on a given device.
  13. //kbuild:lib-$(CONFIG_BLKDISCARD) += blkdiscard.o
  14. //applet:IF_BLKDISCARD(APPLET(blkdiscard, BB_DIR_USR_BIN, BB_SUID_DROP))
  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. int blkdiscard_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  28. int blkdiscard_main(int argc UNUSED_PARAM, char **argv)
  29. {
  30. unsigned opts;
  31. const char *offset_str = "0";
  32. const char *length_str;
  33. uint64_t offset; /* Leaving these two variables out does not */
  34. uint64_t length; /* shrink code size and hampers readability. */
  35. uint64_t range[2];
  36. // struct stat st;
  37. int fd;
  38. enum {
  39. OPT_OFFSET = (1 << 0),
  40. OPT_LENGTH = (1 << 1),
  41. OPT_SECURE = (1 << 2),
  42. };
  43. opt_complementary = "=1";
  44. opts = getopt32(argv, "o:l:s", &offset_str, &length_str);
  45. argv += optind;
  46. fd = xopen(argv[0], O_RDWR|O_EXCL);
  47. //Why bother, BLK[SEC]DISCARD will fail on non-blockdevs anyway?
  48. // xfstat(fd, &st);
  49. // if (!S_ISBLK(st.st_mode))
  50. // bb_error_msg_and_die("%s: not a block device", argv[0]);
  51. offset = xatoull_sfx(offset_str, kMG_suffixes);
  52. if (opts & OPT_LENGTH)
  53. length = xatoull_sfx(length_str, kMG_suffixes);
  54. else {
  55. xioctl(fd, BLKGETSIZE64, &length);
  56. length -= offset;
  57. }
  58. range[0] = offset;
  59. range[1] = length;
  60. ioctl_or_perror_and_die(fd,
  61. (opts & OPT_SECURE) ? BLKSECDISCARD : BLKDISCARD,
  62. &range,
  63. "%s: %s failed",
  64. argv[0],
  65. (opts & OPT_SECURE) ? "BLKSECDISCARD" : "BLKDISCARD"
  66. );
  67. if (ENABLE_FEATURE_CLEAN_UP)
  68. close(fd);
  69. return EXIT_SUCCESS;
  70. }