1# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# Description:
6#
7# Python version of include/asm-generic/ioctl.h
8
9
10import struct
11
12
13# ioctl command encoding: 32 bits total, command in lower 16 bits,
14# size of the parameter structure in the lower 14 bits of the
15# upper 16 bits.
16# Encoding the size of the parameter structure in the ioctl request
17# is useful for catching programs compiled with old versions
18# and to avoid overwriting user space outside the user buffer area.
19# The highest 2 bits are reserved for indicating the ``access mode''.
20# NOTE: This limits the max parameter size to 16kB -1 !
21
22_IOC_NRBITS    = 8
23_IOC_TYPEBITS  = 8
24_IOC_SIZEBITS  = 14
25_IOC_DIRBITS   = 2
26
27_IOC_NRMASK    = ((1 << _IOC_NRBITS) - 1)
28_IOC_TYPEMASK  = ((1 << _IOC_TYPEBITS) - 1)
29_IOC_SIZEMASK  = ((1 << _IOC_SIZEBITS) - 1)
30_IOC_DIRMASK   = ((1 << _IOC_DIRBITS) - 1)
31
32_IOC_NRSHIFT   = 0
33_IOC_TYPESHIFT = (_IOC_NRSHIFT + _IOC_NRBITS)
34_IOC_SIZESHIFT = (_IOC_TYPESHIFT + _IOC_TYPEBITS)
35_IOC_DIRSHIFT  = (_IOC_SIZESHIFT + _IOC_SIZEBITS)
36
37IOC_NONE      = 0
38IOC_WRITE     = 1
39IOC_READ      = 2
40
41# Return the byte size of a python struct format string
42def sizeof(t):
43    return struct.calcsize(t)
44
45def IOC(d, t, nr, size):
46    return ((d << _IOC_DIRSHIFT) | (ord(t) << _IOC_TYPESHIFT) |
47            (nr << _IOC_NRSHIFT) | (size << _IOC_SIZESHIFT))
48
49# used to create numbers
50def IO(t, nr, t_format):
51    return IOC(IOC_NONE, t, nr, 0)
52
53def IOW(t, nr, t_format):
54    return IOC(IOC_WRITE, t, nr, sizeof(t_format))
55
56def IOR(t, nr, t_format):
57    return IOC(IOC_READ, t, nr, sizeof(t_format))
58
59def IOWR(t, nr, t_format):
60    return IOC(IOC_READ|_IOC_WRITE, t, nr, sizeof(t_format))
61
62# used to decode ioctl numbers..
63def IOC_DIR(nr):
64    return ((nr >> _IOC_DIRSHIFT) & _IOC_DIRMASK)
65
66def IOC_TYPE(nr):
67    return ((nr >> _IOC_TYPESHIFT) & _IOC_TYPEMASK)
68
69def IOC_NR(nr):
70    return ((nr >> _IOC_NRSHIFT) & _IOC_NRMASK)
71
72def IOC_SIZE(nr):
73    return ((nr >> _IOC_SIZESHIFT) & _IOC_SIZEMASK)
74
75# ...and for the drivers/sound files...
76IOC_IN          = (IOC_WRITE << _IOC_DIRSHIFT)
77IOC_OUT         = (IOC_READ << _IOC_DIRSHIFT)
78IOC_INOUT       = ((IOC_WRITE | IOC_READ) << _IOC_DIRSHIFT)
79IOCSIZE_MASK    = (_IOC_SIZEMASK << _IOC_SIZESHIFT)
80IOCSIZE_SHIFT   = (_IOC_SIZESHIFT)
81
82