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