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)(getra)(setra)#<0(flushbufs)(rereadpt)",TOYFLAG_SBIN))
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     --setro		Set read only
18     --setrw		Set read write
19     --getro		Get read only
20     --getss		Get sector size
21     --getbsz	Get block size
22     --setbsz BYTES	Set block size
23     --getsz		Get device size in 512-byte sectors
24     --getsize	Get device size in sectors (deprecated)
25     --getsize64	Get device size in bytes
26     --getra		Get readahead in 512-byte sectors
27     --setra SECTORS	Set readahead
28     --flushbufs	Flush buffers
29     --rereadpt	Reread partition table
30 */
31 
32 #define FOR_blockdev
33 #include "toys.h"
34 #include <linux/fs.h>
35 
GLOBALS(long setbsz,setra;)36 GLOBALS(
37   long setbsz, setra;
38 )
39 
40 void blockdev_main(void)
41 {
42   int cmds[] = {BLKRRPART, BLKFLSBUF, BLKRASET, BLKRAGET, BLKGETSIZE64, BLKGETSIZE, BLKGETSIZE64,
43                 BLKBSZSET, BLKBSZGET, BLKSSZGET, BLKROGET, BLKROSET, BLKROSET};
44   char **ss;
45   long long val = 0;
46 
47   if (!toys.optflags) help_exit("need --option");
48 
49   for (ss = toys.optargs;  *ss; ss++) {
50     int fd = xopenro(*ss), i;
51 
52     // Command line order discarded so perform multiple operations in flag order
53     for (i = 0; i < 32; i++) {
54       long flag = toys.optflags & (1<<i);
55 
56       if (!flag) continue;
57 
58       if (flag & FLAG_setbsz) val = TT.setbsz;
59       else val = !!(flag & FLAG_setro);
60 
61       if (flag & FLAG_setra) val = TT.setra;
62 
63       xioctl(fd, cmds[i], &val);
64 
65       flag &= FLAG_setbsz|FLAG_setro|FLAG_flushbufs|FLAG_rereadpt|FLAG_setrw|FLAG_setbsz;
66       if (!flag) printf("%lld\n", (toys.optflags & FLAG_getsz) ? val >> 9: val);
67     }
68     xclose(fd);
69   }
70 }
71