Build an ioctl number
Pack and unpack the direction, type, number and size of an ioctl command. An easy embedded C problem (Linux drivers and kernel modules), run and graded in…
easy · Linux drivers and kernel modules · linux · drivers · bits
Linux ioctl commands are 32-bit numbers built by the _IO, _IOR, _IOW and _IOWR macros:
| Bits | Field |
|---|---|
| 0-7 | nr: the command number |
| 8-15 | type: the driver's "magic" character |
| 16-29 | size: of the argument structure (14 bits) |
| 30-31 | dir: 0 none, 1 write (user to kernel), 2 read (kernel to user), 3 both |
Write ioc(dir, type, nr, size) to build a command, and ioc_decode(cmd, d) to split one into its fields.
Starter code
uint32_t ioc(unsigned dir, unsigned type, unsigned nr, unsigned size) {
return (dir << 24) | (type << 16) | (nr << 8) | size;
}
void ioc_decode(uint32_t cmd, ioc_t *d) {
d->dir = cmd >> 24; d->type = (cmd >> 16) & 0xFF; d->nr = (cmd >> 8) & 0xFF; d->size = cmd & 0xFF;
}Example tests
Building commands
show(ioc(IOC_READ, 'k', 1, 4));
show(ioc(IOC_NONE, 'k', 2, 0));Expected output:
0x80046B01: read, type 'k', nr 1, size 4
0x00006B02: none, type 'k', nr 2, size 0Learn it first
- Linux drivers and kernel modules · Modules, character devices, platform drivers and probe.