1 /* blockdev.c -show/set blockdev information.
2  *
3  * Copyright 2014 Sameer Prakash Pradhan <sameer.p.pradhan@gmail.com>
4  *
5  * No Standard.
6 
7 USE_BLOCKDEV(NEWTOY(blockdev, "<1>1(setro)(setrw)(getro)(getss)(getbsz)(setbsz)#<0(getsz)(getsize)(getsize64)(flushbufs)(rereadpt)",TOYFLAG_USR|TOYFLAG_BIN))
8 
9 config BLOCKDEV
10   bool "blockdev"
11   default y
12   help
13     usage: blockdev --OPTION... BLOCKDEV...
14 
15     Call ioctl(s) on each listed block device
16 
17     OPTIONs:
18     --setro		Set read only
19     --setrw		Set read write
20     --getro		Get read only
21     --getss		Get sector size
22     --getbsz	Get block size
23     --setbsz	BYTES	Set block size
24     --getsz		Get device size in 512-byte sectors
25     --getsize	Get device size in sectors (deprecated)
26     --getsize64	Get device size in bytes
27     --flushbufs	Flush buffers
28     --rereadpt	Reread partition table
29 */
30 
31 #define FOR_blockdev
32 #include "toys.h"
33 #include <linux/fs.h>
34 
GLOBALS(long bsz;)35 GLOBALS(
36   long bsz;
37 )
38 
39 void blockdev_main(void)
40 {
41   int cmds[] = {BLKRRPART, BLKFLSBUF, BLKGETSIZE64, BLKGETSIZE, BLKGETSIZE64,
42                 BLKBSZSET, BLKBSZGET, BLKSSZGET, BLKROGET, BLKROSET, BLKROSET};
43   char **ss;
44   long long val = 0;
45 
46   if (!toys.optflags) help_exit("need --option");
47 
48   for (ss = toys.optargs;  *ss; ss++) {
49     int fd = xopen(*ss, O_RDONLY), i;
50 
51     // Command line order discarded so perform multiple operations in flag order
52     for (i = 0; i < 32; i++) {
53       long flag = toys.optflags & (1<<i);
54 
55       if (!flag) continue;
56 
57       if (flag & FLAG_setbsz) val = TT.bsz;
58       else val = !!(flag & FLAG_setro);
59 
60       xioctl(fd, cmds[i], &val);
61 
62       flag &= FLAG_setbsz|FLAG_setro|FLAG_flushbufs|FLAG_rereadpt|FLAG_setrw;
63       if (!flag) printf("%lld\n", (toys.optflags & FLAG_getsz) ? val >> 9: val);
64     }
65     xclose(fd);
66   }
67 }
68