xref: /aosp_15_r20/external/toybox/toys/other/blkdiscard.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* blkdiscard - discard device sectors
2  *
3  * Copyright 2020 Patrick Oppenlander <[email protected]>
4  *
5  * See http://man7.org/linux/man-pages/man8/blkdiscard.8.html
6  *
7  * The -v and -p options are not supported.
8  * Size parsing does not match util-linux where MB, GB, TB are multiples of
9  * 1000 and MiB, TiB, GiB are multipes of 1024.
10 
11 USE_BLKDISCARD(NEWTOY(blkdiscard, "<1>1f(force)l(length)#<0o(offset)#<0s(secure)z(zeroout)[!sz]", TOYFLAG_BIN))
12 
13 config BLKDISCARD
14   bool "blkdiscard"
15   default y
16   help
17     usage: blkdiscard [-szf] [-o OFFSET] [-l LENGTH] DEVICE
18 
19     Discard device sectors (permanetly deleting data). Free space can improve
20     flash performance and lifetime by wear leveling and collating data.
21     (Some filesystem/driver combinations can do this automatically.)
22 
23     -o	Start at OFFSET (--offset, default 0)
24     -l	LENGTH to discard (--length, default all)
25     -s	Overwrite discarded data (--secure)
26     -z	Zero-fill rather than discard (--zeroout)
27     -f	Disable check for mounted filesystem (--force)
28 
29     OFFSET and LENGTH must be aligned to the device sector size. Default
30     without -o/-l discards the entire device. (You have been warned.)
31 */
32 
33 #define FOR_blkdiscard
34 #include "toys.h"
35 
36 #include <linux/fs.h>
37 
GLOBALS(long o,l;)38 GLOBALS(
39   long o, l;
40 )
41 
42 void blkdiscard_main(void)
43 {
44   int fd = xopen(*toys.optargs, O_WRONLY|O_EXCL*!FLAG(f));
45   unsigned long long ol[2] = {TT.o, TT.l};
46 
47   // TODO: argument size capped to 2 gigs on 32-bit, even with "-l 8g"
48   if (!FLAG(l)) {
49     xioctl(fd, BLKGETSIZE64, ol+1);
50     ol[1] -= ol[0];
51   }
52   xioctl(fd, FLAG(s) ? BLKSECDISCARD : FLAG(z) ? BLKZEROOUT : BLKDISCARD, ol);
53   close(fd);
54 }
55