I2C (or without fancy typography, “I2C”) is an acronym for the “Inter-IC” bus, a simple bus protocol which is widely used where low data rate communications suffice. Since it’s also a licensed trademark, some vendors use another name (such as “Two-Wire Interface”, TWI) for the same bus. I2C only needs two signals (SCL for clock, SDA for data), conserving board real estate and minimizing signal quality issues. Most I2C devices use seven bit addresses, and bus speeds of up to 400 kHz; there’s a high speed extension (3.4 MHz) that’s not yet found wide use. I2C is a multi-master bus; open drain signaling is used to arbitrate between masters, as well as to handshake and to synchronize clocks from slower clients.
The Linux I2C programming interfaces support only the master side of bus interactions, not the slave side. The programming interface is structured around two kinds of driver, and two kinds of device. An I2C “Adapter Driver” abstracts the controller hardware; it binds to a physical device (perhaps a PCI device or platform_device) and exposes a struct i2c_adapter representing each I2C bus segment it manages. On each I2C bus segment will be I2C devices represented by a struct i2c_client. Those devices will be bound to a struct i2c_driver, which should follow the standard Linux driver model. (At this writing, a legacy model is more widely used.) There are functions to perform various I2C protocol operations; at this writing all such functions are usable only from task context.
The System Management Bus (SMBus) is a sibling protocol. Most SMBus systems are also I2C conformant. The electrical constraints are tighter for SMBus, and it standardizes particular protocol messages and idioms. Controllers that support I2C can also support most SMBus operations, but SMBus controllers don’t support all the protocol options that an I2C controller will. There are functions to perform various SMBus protocol operations, either using I2C primitives or by issuing SMBus commands to i2c_adapter devices which don’t support those I2C operations.
represent an I2C device driver
Definition
struct i2c_driver {
unsigned int class;
int (* attach_adapter) (struct i2c_adapter *);
int (* probe) (struct i2c_client *, const struct i2c_device_id *);
int (* remove) (struct i2c_client *);
int (* probe_new) (struct i2c_client *);
void (* shutdown) (struct i2c_client *);
void (* alert) (struct i2c_client *, enum i2c_alert_protocol protocol,unsigned int data);
int (* command) (struct i2c_client *client, unsigned int cmd, void *arg);
struct device_driver driver;
const struct i2c_device_id * id_table;
int (* detect) (struct i2c_client *, struct i2c_board_info *);
const unsigned short * address_list;
struct list_head clients;
};
Members
Description
The driver.owner field should be set to the module owner of this driver. The driver.name field should be set to the name of this driver.
For automatic device detection, both detect and address_list must be defined. class should also be set, otherwise only devices forced with module parameters will be created. The detect function must fill at least the name field of the i2c_board_info structure it is handed upon successful detection, and possibly also the flags field.
If detect is missing, the driver will still work fine for enumerated devices. Detected devices simply won’t be supported. This is expected for the many I2C/SMBus devices which can’t be detected reliably, and the ones which can always be enumerated in practice.
The i2c_client structure which is handed to the detect callback is not a real i2c_client. It is initialized just enough so that you can call i2c_smbus_read_byte_data and friends on it. Don’t do anything else with it. In particular, calling dev_dbg and friends on it is not allowed.
represent an I2C slave device
Definition
struct i2c_client {
unsigned short flags;
unsigned short addr;
char name[I2C_NAME_SIZE];
struct i2c_adapter * adapter;
struct device dev;
int irq;
struct list_head detected;
#if IS_ENABLED(CONFIG_I2C_SLAVE)
i2c_slave_cb_t slave_cb;
#endif
};
Members
Description
An i2c_client identifies a single device (i.e. chip) connected to an i2c bus. The behaviour exposed to Linux is defined by the driver managing the device.
template for device creation
Definition
struct i2c_board_info {
char type[I2C_NAME_SIZE];
unsigned short flags;
unsigned short addr;
void * platform_data;
struct dev_archdata * archdata;
struct device_node * of_node;
struct fwnode_handle * fwnode;
const struct property_entry * properties;
int irq;
};
Members
Description
I2C doesn’t actually support hardware probing, although controllers and devices may be able to use I2C_SMBUS_QUICK to tell whether or not there’s a device at a given address. Drivers commonly need more information than that, such as chip type, configuration, associated IRQ, and so on.
i2c_board_info is used to build tables of information listing I2C devices that are present. This information is used to grow the driver model tree. For mainboards this is done statically using i2c_register_board_info(); bus numbers identify adapters that aren’t yet available. For add-on boards, i2c_new_device() does this dynamically with the adapter already known.
macro used to list an i2c device and its address
Parameters
Description
This macro initializes essential fields of a struct i2c_board_info, declaring what has been provided on a particular board. Optional fields (such as associated irq, or device-specific platform_data) are provided using conventional syntax.
represent I2C transfer method
Definition
struct i2c_algorithm {
int (* master_xfer) (struct i2c_adapter *adap, struct i2c_msg *msgs,int num);
int (* smbus_xfer) (struct i2c_adapter *adap, u16 addr,unsigned short flags, char read_write,u8 command, int size, union i2c_smbus_data *data);
u32 (* functionality) (struct i2c_adapter *);
#if IS_ENABLED(CONFIG_I2C_SLAVE)
int (* reg_slave) (struct i2c_client *client);
int (* unreg_slave) (struct i2c_client *client);
#endif
};
Members
Description
The following structs are for those who like to implement new bus drivers: i2c_algorithm is the interface to a class of hardware solutions which can be addressed using the same bus algorithms - i.e. bit-banging or the PCF8584 to name two of the most common.
The return codes from the master_xfer field should indicate the type of error code that occurred during the transfer, as documented in the kernel Documentation file Documentation/i2c/fault-codes.
represent I2C locking operations
Definition
struct i2c_lock_operations {
void (* lock_bus) (struct i2c_adapter *, unsigned int flags);
int (* trylock_bus) (struct i2c_adapter *, unsigned int flags);
void (* unlock_bus) (struct i2c_adapter *, unsigned int flags);
};
Members
Description
The main operations are wrapped by i2c_lock_bus and i2c_unlock_bus.
I2C timing information
Definition
struct i2c_timings {
u32 bus_freq_hz;
u32 scl_rise_ns;
u32 scl_fall_ns;
u32 scl_int_delay_ns;
u32 sda_fall_ns;
};
Members
I2C bus recovery information
Definition
struct i2c_bus_recovery_info {
int (* recover_bus) (struct i2c_adapter *);
int (* get_scl) (struct i2c_adapter *);
void (* set_scl) (struct i2c_adapter *, int val);
int (* get_sda) (struct i2c_adapter *);
void (* prepare_recovery) (struct i2c_adapter *);
void (* unprepare_recovery) (struct i2c_adapter *);
int scl_gpio;
int sda_gpio;
};
Members
describe flaws of an i2c adapter
Definition
struct i2c_adapter_quirks {
u64 flags;
int max_num_msgs;
u16 max_write_len;
u16 max_read_len;
u16 max_comb_1st_msg_len;
u16 max_comb_2nd_msg_len;
};
Members
Description
Note about combined messages: Some I2C controllers can only send one message per transfer, plus something called combined message or write-then-read. This is (usually) a small write message followed by a read message and barely enough to access register based devices like EEPROMs. There is a flag to support this mode. It implies max_num_msg = 2 and does the length checks with max_comb_*_len because combined message mode usually has its own limitations. Because of HW implementations, some controllers can actually do write-then-anything or other variants. To support that, write-then-read has been broken out into smaller bits like write-first and read-second which can be combined as needed.
Get exclusive access to an I2C bus segment
Parameters
Try to get exclusive access to an I2C bus segment
Parameters
Return
true if the I2C bus segment is locked, false otherwise
Release exclusive access to an I2C bus segment
Parameters
Function for checking the quirk flags in an i2c adapter
Parameters
Return
true if the adapter has all the specified quirk flags, false if not
Helper macro for registering a modular I2C driver
Parameters
Description
Helper macro for I2C drivers which do not do anything special in module init/exit. This eliminates a lot of boilerplate. Each module may only use this macro once, and calling it replaces module_init() and module_exit()
Helper macro for registering a builtin I2C driver
Parameters
Description
Helper macro for I2C drivers which do not do anything special in their init. This eliminates a lot of boilerplate. Each driver may only use this macro once, and calling it replaces device_initcall().
statically declare I2C devices
Parameters
Description
Systems using the Linux I2C driver stack can declare tables of board info while they initialize. This should be done in board-specific init code near arch_initcall() time, or equivalent, before any I2C adapter driver is registered. For example, mainboard init code could define several devices, as could the init code for each daughtercard in a board stack.
The I2C devices will be created later, after the adapter for the relevant bus has been registered. After that moment, standard driver model tools are used to bind “new style” I2C drivers to the devices. The bus number for any device declared using this routine is not available for dynamic allocation.
The board info passed can safely be __initdata, but be careful of embedded pointers (for platform_data, functions, etc) since that won’t be copied.
Parameters
Description
Find the I2C bus speed by walking the ACPI namespace for all I2C slaves devices connected to this bus and use the speed of slowest device.
Returns the speed in Hz or zero
return parameter as i2c_client, or NULL
Parameters
Description
When traversing the driver model tree, perhaps using driver model iterators like device_for_each_child(), you can’t assume very much about the nodes you find. Use this function to avoid oopses caused by wrongly treating some non-I2C device as an i2c_client.
instantiate an i2c device
Parameters
Context
can sleep
Description
Create an i2c device. Binding is handled through driver model probe()/remove() methods. A driver may be bound to this device when we return from this function, or any later moment (e.g. maybe hotplugging will load the driver module). This call is not appropriate for use by mainboard initialization logic, which usually runs during an arch_initcall() long before any i2c_adapter could exist.
This returns the new i2c client, which may be saved for later use with i2c_unregister_device(); or NULL to indicate an error.
reverse effect of i2c_new_device()
Parameters
Context
can sleep
return a new i2c device bound to a dummy driver
Parameters
Context
can sleep
Description
This returns an I2C client bound to the “dummy” driver, intended for use with devices that consume multiple addresses. Examples of such chips include various EEPROMS (like 24c04 and 24c08 models).
These dummy devices have two main uses. First, most I2C and SMBus calls except i2c_transfer() need a client handle; the dummy will be that handle. And second, this prevents the specified address from being bound to a different driver.
This returns the new i2c client, which should be saved for later use with i2c_unregister_device(); or NULL to indicate an error.
Helper to get the instantiated secondary address and create the associated device
Parameters
Context
can sleep
Description
I2C clients can be composed of multiple I2C slaves bound together in a single component. The I2C client driver then binds to the master I2C slave and needs to create I2C dummy clients to communicate with all the other slaves.
This function creates and returns an I2C dummy client whose I2C address is retrieved from the platform firmware based on the given slave name. If no address is specified by the firmware default_addr is used.
On DT-based platforms the address is retrieved from the “reg” property entry cell whose “reg-names” value matches the slave name.
This returns the new i2c client, which should be saved for later use with i2c_unregister_device(); or NULL to indicate an error.
return parameter as i2c_adapter or NULL
Parameters
Description
When traversing the driver model tree, perhaps using driver model iterators like device_for_each_child(), you can’t assume very much about the nodes you find. Use this function to avoid oopses caused by wrongly treating some non-I2C device as an i2c_adapter.
Forward a Host Notify event to the correct I2C client.
Parameters
Context
can’t sleep
Description
Helper function to be called from an I2C bus driver’s interrupt handler. It will schedule the Host Notify IRQ.
declare i2c adapter, use dynamic bus number
Parameters
Context
can sleep
Description
This routine is used to declare an I2C adapter when its bus number doesn’t matter or when its bus number is specified by an dt alias. Examples of bases when the bus number doesn’t matter: I2C adapters dynamically added by USB links or PCI plugin cards.
When this returns zero, a new bus number was allocated and stored in adap->nr, and the specified adapter became available for clients. Otherwise, a negative errno value is returned.
declare i2c adapter, use static bus number
Parameters
Context
can sleep
Description
This routine is used to declare an I2C adapter when its bus number matters. For example, use it for I2C adapters from system-on-chip CPUs, or otherwise built in to the system’s mainboard, and where i2c_board_info is used to properly configure I2C devices.
If the requested bus number is set to -1, then this function will behave identically to i2c_add_adapter, and will dynamically assign a bus number.
If no devices have pre-been declared for this bus, then be sure to register the adapter before any dynamically allocated ones. Otherwise the required bus ID may not be available.
When this returns zero, the specified adapter became available for clients using the bus number provided in adap->nr. Also, the table of I2C devices pre-declared using i2c_register_board_info() is scanned, and the appropriate driver model device nodes are created. Otherwise, a negative errno value is returned.
unregister I2C adapter
Parameters
Context
can sleep
Description
This unregisters an I2C adapter which was previously registered by i2c_add_adapter or i2c_add_numbered_adapter.
get I2C related timing parameters from firmware
Parameters
Description
Scan the device for the generic I2C properties describing timing parameters for the signal and fill the given struct with the results. If a property was not found and use_defaults was true, then maximum timings are assumed which are derived from the I2C specification. If use_defaults is not used, the results will be 0, so drivers can apply their own defaults later. The latter is mainly intended for avoiding regressions of existing drivers which want to switch to this function. New drivers almost always should use the defaults.
unregister I2C driver
Parameters
Context
can sleep
increments the reference count of the i2c client structure
Parameters
Description
Each live reference to a client should be refcounted. The driver model does that automatically as part of driver binding, so that most drivers don’t need to do this explicitly: they hold a reference until they’re unbound from the device.
A pointer to the client with the incremented reference counter is returned.
release a use of the i2c client structure
Parameters
Description
Must be called when a user of a client is finished with it.
unlocked flavor of i2c_transfer
Parameters
Description
Returns negative errno, else the number of messages executed.
Adapter lock must be held when calling this function. No debug logging takes place. adap->algo->master_xfer existence isn’t checked.
execute a single or combined I2C message
Parameters
Description
Returns negative errno, else the number of messages executed.
Note that there is no requirement that each message be sent to the same slave address, although that is the most common model.
issue a single I2C message in master transmit mode
Parameters
Description
Returns negative errno, or else the number of bytes written.
issue a single I2C message in master receive mode
Parameters
Description
Returns negative errno, or else the number of bytes read.
SMBus “receive byte” protocol
Parameters
Description
This executes the SMBus “receive byte” protocol, returning negative errno else the byte received from the device.
SMBus “send byte” protocol
Parameters
Description
This executes the SMBus “send byte” protocol, returning negative errno else zero on success.
SMBus “read byte” protocol
Parameters
Description
This executes the SMBus “read byte” protocol, returning negative errno else a data byte received from the device.
SMBus “write byte” protocol
Parameters
Description
This executes the SMBus “write byte” protocol, returning negative errno else zero on success.
SMBus “read word” protocol
Parameters
Description
This executes the SMBus “read word” protocol, returning negative errno else a 16-bit unsigned “word” received from the device.
SMBus “write word” protocol
Parameters
Description
This executes the SMBus “write word” protocol, returning negative errno else zero on success.
SMBus “block read” protocol
Parameters
Description
This executes the SMBus “block read” protocol, returning negative errno else the number of data bytes in the slave’s response.
Note that using this function requires that the client’s adapter support the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers support this; its emulation through I2C messaging relies on a specific mechanism (I2C_M_RECV_LEN) which may not be implemented.
SMBus “block write” protocol
Parameters
Description
This executes the SMBus “block write” protocol, returning negative errno else zero on success.
execute SMBus protocol operations
Parameters
Description
This executes an SMBus protocol operation, and returns a negative errno code else zero on success.
read block or emulate
Parameters
Description
This executes the SMBus “block read” protocol if supported by the adapter. If block read is not supported, it emulates it using either word or byte read protocols depending on availability.
The addresses of the I2C slave device that are accessed with this function must be mapped to a linear region, so that a block read will have the same effect as a byte read. Before using this function you must double-check if the I2C slave does support exchanging a block transfer with a byte transfer.
Parameters
Description
This checks the device nodes for an I2C slave by checking the address used in the reg property. If the address match the I2C_OWN_SLAVE_ADDRESS flag this means the device is configured to act as a I2C slave and it will be listening at that address.
Returns true if an I2C own slave address is detected, otherwise returns false.