Back to home page

OSCL-LXR

 
 

    


0001 ============================================
0002 Implementing I2C device drivers in userspace
0003 ============================================
0004 
0005 Usually, I2C devices are controlled by a kernel driver. But it is also
0006 possible to access all devices on an adapter from userspace, through
0007 the /dev interface. You need to load module i2c-dev for this.
0008 
0009 Each registered I2C adapter gets a number, counting from 0. You can
0010 examine /sys/class/i2c-dev/ to see what number corresponds to which adapter.
0011 Alternatively, you can run "i2cdetect -l" to obtain a formatted list of all
0012 I2C adapters present on your system at a given time. i2cdetect is part of
0013 the i2c-tools package.
0014 
0015 I2C device files are character device files with major device number 89
0016 and a minor device number corresponding to the number assigned as
0017 explained above. They should be called "i2c-%d" (i2c-0, i2c-1, ...,
0018 i2c-10, ...). All 256 minor device numbers are reserved for I2C.
0019 
0020 
0021 C example
0022 =========
0023 
0024 So let's say you want to access an I2C adapter from a C program.
0025 First, you need to include these two headers::
0026 
0027   #include <linux/i2c-dev.h>
0028   #include <i2c/smbus.h>
0029 
0030 Now, you have to decide which adapter you want to access. You should
0031 inspect /sys/class/i2c-dev/ or run "i2cdetect -l" to decide this.
0032 Adapter numbers are assigned somewhat dynamically, so you can not
0033 assume much about them. They can even change from one boot to the next.
0034 
0035 Next thing, open the device file, as follows::
0036 
0037   int file;
0038   int adapter_nr = 2; /* probably dynamically determined */
0039   char filename[20];
0040 
0041   snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
0042   file = open(filename, O_RDWR);
0043   if (file < 0) {
0044     /* ERROR HANDLING; you can check errno to see what went wrong */
0045     exit(1);
0046   }
0047 
0048 When you have opened the device, you must specify with what device
0049 address you want to communicate::
0050 
0051   int addr = 0x40; /* The I2C address */
0052 
0053   if (ioctl(file, I2C_SLAVE, addr) < 0) {
0054     /* ERROR HANDLING; you can check errno to see what went wrong */
0055     exit(1);
0056   }
0057 
0058 Well, you are all set up now. You can now use SMBus commands or plain
0059 I2C to communicate with your device. SMBus commands are preferred if
0060 the device supports them. Both are illustrated below::
0061 
0062   __u8 reg = 0x10; /* Device register to access */
0063   __s32 res;
0064   char buf[10];
0065 
0066   /* Using SMBus commands */
0067   res = i2c_smbus_read_word_data(file, reg);
0068   if (res < 0) {
0069     /* ERROR HANDLING: I2C transaction failed */
0070   } else {
0071     /* res contains the read word */
0072   }
0073 
0074   /*
0075    * Using I2C Write, equivalent of
0076    * i2c_smbus_write_word_data(file, reg, 0x6543)
0077    */
0078   buf[0] = reg;
0079   buf[1] = 0x43;
0080   buf[2] = 0x65;
0081   if (write(file, buf, 3) != 3) {
0082     /* ERROR HANDLING: I2C transaction failed */
0083   }
0084 
0085   /* Using I2C Read, equivalent of i2c_smbus_read_byte(file) */
0086   if (read(file, buf, 1) != 1) {
0087     /* ERROR HANDLING: I2C transaction failed */
0088   } else {
0089     /* buf[0] contains the read byte */
0090   }
0091 
0092 Note that only a subset of the I2C and SMBus protocols can be achieved by
0093 the means of read() and write() calls. In particular, so-called combined
0094 transactions (mixing read and write messages in the same transaction)
0095 aren't supported. For this reason, this interface is almost never used by
0096 user-space programs.
0097 
0098 IMPORTANT: because of the use of inline functions, you *have* to use
0099 '-O' or some variation when you compile your program!
0100 
0101 
0102 Full interface description
0103 ==========================
0104 
0105 The following IOCTLs are defined:
0106 
0107 ``ioctl(file, I2C_SLAVE, long addr)``
0108   Change slave address. The address is passed in the 7 lower bits of the
0109   argument (except for 10 bit addresses, passed in the 10 lower bits in this
0110   case).
0111 
0112 ``ioctl(file, I2C_TENBIT, long select)``
0113   Selects ten bit addresses if select not equals 0, selects normal 7 bit
0114   addresses if select equals 0. Default 0.  This request is only valid
0115   if the adapter has I2C_FUNC_10BIT_ADDR.
0116 
0117 ``ioctl(file, I2C_PEC, long select)``
0118   Selects SMBus PEC (packet error checking) generation and verification
0119   if select not equals 0, disables if select equals 0. Default 0.
0120   Used only for SMBus transactions.  This request only has an effect if the
0121   the adapter has I2C_FUNC_SMBUS_PEC; it is still safe if not, it just
0122   doesn't have any effect.
0123 
0124 ``ioctl(file, I2C_FUNCS, unsigned long *funcs)``
0125   Gets the adapter functionality and puts it in ``*funcs``.
0126 
0127 ``ioctl(file, I2C_RDWR, struct i2c_rdwr_ioctl_data *msgset)``
0128   Do combined read/write transaction without stop in between.
0129   Only valid if the adapter has I2C_FUNC_I2C.  The argument is
0130   a pointer to a::
0131 
0132     struct i2c_rdwr_ioctl_data {
0133       struct i2c_msg *msgs;  /* ptr to array of simple messages */
0134       int nmsgs;             /* number of messages to exchange */
0135     }
0136 
0137   The msgs[] themselves contain further pointers into data buffers.
0138   The function will write or read data to or from that buffers depending
0139   on whether the I2C_M_RD flag is set in a particular message or not.
0140   The slave address and whether to use ten bit address mode has to be
0141   set in each message, overriding the values set with the above ioctl's.
0142 
0143 ``ioctl(file, I2C_SMBUS, struct i2c_smbus_ioctl_data *args)``
0144   If possible, use the provided ``i2c_smbus_*`` methods described below instead
0145   of issuing direct ioctls.
0146 
0147 You can do plain I2C transactions by using read(2) and write(2) calls.
0148 You do not need to pass the address byte; instead, set it through
0149 ioctl I2C_SLAVE before you try to access the device.
0150 
0151 You can do SMBus level transactions (see documentation file smbus-protocol.rst
0152 for details) through the following functions::
0153 
0154   __s32 i2c_smbus_write_quick(int file, __u8 value);
0155   __s32 i2c_smbus_read_byte(int file);
0156   __s32 i2c_smbus_write_byte(int file, __u8 value);
0157   __s32 i2c_smbus_read_byte_data(int file, __u8 command);
0158   __s32 i2c_smbus_write_byte_data(int file, __u8 command, __u8 value);
0159   __s32 i2c_smbus_read_word_data(int file, __u8 command);
0160   __s32 i2c_smbus_write_word_data(int file, __u8 command, __u16 value);
0161   __s32 i2c_smbus_process_call(int file, __u8 command, __u16 value);
0162   __s32 i2c_smbus_block_process_call(int file, __u8 command, __u8 length,
0163                                      __u8 *values);
0164   __s32 i2c_smbus_read_block_data(int file, __u8 command, __u8 *values);
0165   __s32 i2c_smbus_write_block_data(int file, __u8 command, __u8 length,
0166                                    __u8 *values);
0167 
0168 All these transactions return -1 on failure; you can read errno to see
0169 what happened. The 'write' transactions return 0 on success; the
0170 'read' transactions return the read value, except for read_block, which
0171 returns the number of values read. The block buffers need not be longer
0172 than 32 bytes.
0173 
0174 The above functions are made available by linking against the libi2c library,
0175 which is provided by the i2c-tools project.  See:
0176 https://git.kernel.org/pub/scm/utils/i2c-tools/i2c-tools.git/.
0177 
0178 
0179 Implementation details
0180 ======================
0181 
0182 For the interested, here's the code flow which happens inside the kernel
0183 when you use the /dev interface to I2C:
0184 
0185 1) Your program opens /dev/i2c-N and calls ioctl() on it, as described in
0186    section "C example" above.
0187 
0188 2) These open() and ioctl() calls are handled by the i2c-dev kernel
0189    driver: see i2c-dev.c:i2cdev_open() and i2c-dev.c:i2cdev_ioctl(),
0190    respectively. You can think of i2c-dev as a generic I2C chip driver
0191    that can be programmed from user-space.
0192 
0193 3) Some ioctl() calls are for administrative tasks and are handled by
0194    i2c-dev directly. Examples include I2C_SLAVE (set the address of the
0195    device you want to access) and I2C_PEC (enable or disable SMBus error
0196    checking on future transactions.)
0197 
0198 4) Other ioctl() calls are converted to in-kernel function calls by
0199    i2c-dev. Examples include I2C_FUNCS, which queries the I2C adapter
0200    functionality using i2c.h:i2c_get_functionality(), and I2C_SMBUS, which
0201    performs an SMBus transaction using i2c-core-smbus.c:i2c_smbus_xfer().
0202 
0203    The i2c-dev driver is responsible for checking all the parameters that
0204    come from user-space for validity. After this point, there is no
0205    difference between these calls that came from user-space through i2c-dev
0206    and calls that would have been performed by kernel I2C chip drivers
0207    directly. This means that I2C bus drivers don't need to implement
0208    anything special to support access from user-space.
0209 
0210 5) These i2c.h functions are wrappers to the actual implementation of
0211    your I2C bus driver. Each adapter must declare callback functions
0212    implementing these standard calls. i2c.h:i2c_get_functionality() calls
0213    i2c_adapter.algo->functionality(), while
0214    i2c-core-smbus.c:i2c_smbus_xfer() calls either
0215    adapter.algo->smbus_xfer() if it is implemented, or if not,
0216    i2c-core-smbus.c:i2c_smbus_xfer_emulated() which in turn calls
0217    i2c_adapter.algo->master_xfer().
0218 
0219 After your I2C bus driver has processed these requests, execution runs
0220 up the call chain, with almost no processing done, except by i2c-dev to
0221 package the returned data, if any, in suitable format for the ioctl.