1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30#include "libbb.h"
31#include <linux/fs.h>
32
33#ifndef BLKDISCARD
34#define BLKDISCARD 0x1277
35#endif
36#ifndef BLKSECDISCARD
37#define BLKSECDISCARD 0x127d
38#endif
39
40int blkdiscard_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
41int blkdiscard_main(int argc UNUSED_PARAM, char **argv)
42{
43 unsigned opts;
44 const char *offset_str = "0";
45 const char *length_str;
46 uint64_t offset;
47 uint64_t length;
48 uint64_t range[2];
49 int fd;
50
51 enum {
52 OPT_OFFSET = (1 << 0),
53 OPT_LENGTH = (1 << 1),
54 OPT_SECURE = (1 << 2),
55 };
56
57 opts = getopt32(argv, "^" "o:l:s" "\0" "=1", &offset_str, &length_str);
58 argv += optind;
59
60 fd = xopen(argv[0], O_RDWR|O_EXCL);
61
62
63
64
65
66 offset = xatoull_sfx(offset_str, kMG_suffixes);
67
68 if (opts & OPT_LENGTH)
69 length = xatoull_sfx(length_str, kMG_suffixes);
70 else {
71 xioctl(fd, BLKGETSIZE64, &length);
72 length -= offset;
73 }
74
75 range[0] = offset;
76 range[1] = length;
77 ioctl_or_perror_and_die(fd,
78 (opts & OPT_SECURE) ? BLKSECDISCARD : BLKDISCARD,
79 &range,
80 "%s: %s failed",
81 argv[0],
82 (opts & OPT_SECURE) ? "BLKSECDISCARD" : "BLKDISCARD"
83 );
84
85 if (ENABLE_FEATURE_CLEAN_UP)
86 close(fd);
87
88 return EXIT_SUCCESS;
89}
90