【Linux 内核源码分析】I2C子系统分析 整体框架介绍

内核版本:v4.14

构成

在Linux的I2C架构如图:
【Linux 内核源码分析】I2C子系统分析 整体框架介绍_第1张图片
内核空间部分可以分为:i2c设备驱动、i2c核心以及i2c总线驱动。

  • i2c核心:框架的实现;提供i2c总线驱动和设备驱动的注册、注销方法;i2c通信方法(algorithm)上层的,与具体适配器无关的代码以及探测设备、检测设备地址的上层代码等。这一部分的工作由内核开发者完成。
  • i2c总线驱动:具体控制器的实现;i2c总线驱动是对i2c硬件体系结构中适配器端的实现,说白了,就是怎么操作i2c模块工作。适配器可由CPU控制,甚至直接集成到cpu里面( algorithm driver
    adapter driver)
  • i2c设备:对i2c硬件体系结构中设备端的实现,比如说板上的EEPROM设备等。设备一般挂接在cpu控制的i2c适配器上,通过i2c适配器与cpu交换数据。( chip drivers, 包括多种类型,如RTC, EEPROM, I/O expander, hardware monitoring, sound, video等)

名词解释:

  • i2c-adapter(适配器):指的是CPU实际的I2C控制器(例如I2C0,I2C1);
  • i2c-device(设备):指的是I2C总线上的从设备(例如某片EEPROM,某个触摸屏);
  • i2c algorithm(算法、实现方法):这里指的是对i2c设备一套对应的通信方法。

分层的好处:

  • 让工程师们各司其职,只关心自己应该实现的部分
  • 不需要为每一个i2c控制器编写所有从设备的控制代码,只需要分别完成n个控制器的控制接口,m个从设备的访问实现,即可实现任意的控制器访问任意的从设备(假设硬件连接支持)

原型

以下原型均定义在include/linux/i2c.h中,随着内核版本的不同有差异,但差异不大。

以下原型均定义在include/linux/i2c.h中,随着内核版本的不同有差异,但差异不大。

i2c 设备驱动

i2c_driver:代表一个i2c设备驱动;

i2c 设备驱动要使用i2c_driver 和i2c_client数据结构并填充i2c_driver中的成员函数

/**
 * struct i2c_driver - represent an I2C device driver
 * @class: What kind of i2c device we instantiate (for detect)
 * @attach_adapter: Callback for bus addition (deprecated)
 * @probe: Callback for device binding - soon to be deprecated
 * @probe_new: New callback for device binding
 * @remove: Callback for device unbinding
 * @shutdown: Callback for device shutdown
 * @alert: Alert callback, for example for the SMBus alert protocol
 * @command: Callback for bus-wide signaling (optional)
 * @driver: Device driver model driver
 * @id_table: List of I2C devices supported by this driver
 * @detect: Callback for device detection
 * @address_list: The I2C addresses to probe (for detect)
 * @clients: List of detected clients we created (for i2c-core use only)
 * @disable_i2c_core_irq_mapping: Tell the i2c-core to not do irq-mapping
 *
 * 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.
 */

struct i2c_driver {
	unsigned int class; // 表示我们将注册的是那种设备(探测时用)

	/* Notifies the driver that a new bus has appeared. You should avoid
	 * using this, it will be removed in a near future.
	 */
	int (*attach_adapter)(struct i2c_adapter *) __deprecated; // 添加总线时,告诉驱动的回调函数(以后可能要弃用)

	/* Standard driver model interfaces */
	int (*probe)(struct i2c_client *, const struct i2c_device_id *); // 绑定设备时的回调函数
	int (*remove)(struct i2c_client *); // 解除绑定时调用的回调函数

	/* New driver model interface to aid the seamless removal of the
	 * current probe()'s, more commonly unused than used second parameter.
	 */
	int (*probe_new)(struct i2c_client *); // 新的设备绑定回调函数

	/* driver model interfaces that don't relate to enumeration  */
	void (*shutdown)(struct i2c_client *); // 设备关闭时调用的回调函数

	/* Alert callback, for example for the SMBus alert protocol.
	 * The format and meaning of the data value depends on the protocol.
	 * For the SMBus alert protocol, there is a single bit of data passed
	 * as the alert response's low bit ("event flag").
	 * For the SMBus Host Notify protocol, the data corresponds to the
	 * 16-bit payload data reported by the slave device acting as master.
	 */
	void (*alert)(struct i2c_client *, enum i2c_alert_protocol protocol,
		      unsigned int data); // 警告回调函数(例如SMBus警报协议)

	/* a ioctl like command that can be used to perform specific functions
	 * with the device.
	 */
	int (*command)(struct i2c_client *client, unsigned int cmd, void *arg); // 类似于ioctl 的命令控制函数

	struct device_driver driver; // 设备驱动模型中的驱动
	const struct i2c_device_id *id_table; // 这个i2c驱动支持的设备链表

	/* Device detection callback for automatic device creation */
	int (*detect)(struct i2c_client *, struct i2c_board_info *); // 检测设备的回调函数;
	const unsigned short *address_list; // 要探测的I2C地址(用于检测)
	struct list_head clients; // 我们创建的检测到的clients(仅供i2c核心使用)

	bool disable_i2c_core_irq_mapping;
};

例如:RTC设备的驱动

/* drivers/rtc/rtc-ds1307.c */
static struct i2c_driver ds1307_driver = {
    .driver = {
        .name   = "rtc-ds1307",
        .of_match_table = of_match_ptr(ds1307_of_match),
        .acpi_match_table = ACPI_PTR(ds1307_acpi_ids),
    },
    .probe      = ds1307_probe,
    .id_table   = ds1307_id,
};

i2c 客户端

i2c_client:代表一个连接到i2c_bus总线上的从设备。

/**
 * struct i2c_client - represent an I2C slave device
 * @flags: 
 	- I2C_CLIENT_TEN : the device uses a ten bit chip address; 表示i2c从设备使用的芯片地址为10bit
	- I2C_CLIENT_PEC : it uses SMBus Packet Error Checking;   表示设备使用SMBus错误检查
 * @addr: Address used on the I2C bus connected to the parent adapter.
 * @name: Indicates the type of the device, usually a chip name that's
 *	generic enough to hide second-sourcing and compatible revisions.
 * @adapter: manages the bus segment hosting this I2C device
 * @dev: Driver model device node for the slave.
 * @irq: indicates the IRQ generated by this device (if any)
 * @detected: member of an i2c_driver.clients list or i2c-core's
 *	userspace_devices list
 * @slave_cb: Callback when I2C slave mode of an adapter is used. The adapter
 *	calls it to pass on slave events to the slave driver.
 *
 * 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.
 */
struct i2c_client {
	unsigned short flags;	 // 一个标示,丰富这个设备的特殊细节
	unsigned short addr;		/* chip address - NOTE: 7bit;addresses are stored in the _LOWER_ 7 bits	 */ // 从设备在连接到相应适配器总线上使用的地址;默认使用低七位。
	char name[I2C_NAME_SIZE]; // 设备的名字;
	struct i2c_adapter *adapter;	/* the adapter we sit on	*/ // 挂接设备的适配器;
	struct device dev;		/* the device structure		*/ // 访问设备的驱动;
	int irq;			/* irq issued by device		*/ // 表明由设备产生的中断;
	struct list_head detected; // 一个i2c_driver支持的client的数量或i2c-core的用户空间设备的链表。
#if IS_ENABLED(CONFIG_I2C_SLAVE)
	i2c_slave_cb_t slave_cb;	/* callback for slave mode	*/ // 从模式下的回调函数
#endif
};

i2c_client的信息通常在BSP的板文件中通过i2c_board_info填充, 如下面的代码就定义了一个I2C设备的ID为“wm8580”、 地址为0x1b、 的i2c_client:

static struct i2c_board_info i2c_devs0[] __initdata = {
    {
        I2C_BOARD_INFO("wm8580", 0x1b),
    },
};

struct i2c_board_info {
	char		type[I2C_NAME_SIZE];
	unsigned short	flags;
	unsigned short	addr;
	void		*platform_data;
	struct dev_archdata	*archdata;
#ifdef CONFIG_OF
	struct device_node *of_node;
#endif
	int		irq;
};

i2c适配器

i2c_adapter:一个用于标识物理总线(也就是i2c总线)连同访问它必要的算法的一个结构

/*
 * i2c_adapter is the structure used to identify a physical i2c bus along
 * with the access algorithms necessary to access it.
 */
struct i2c_adapter {
	struct module *owner;
	unsigned int class;		  /* classes to allow probing for */
	const struct i2c_algorithm *algo; /* the algorithm to access the bus */
	void *algo_data;

	/* data fields that are valid for all devices	*/
	const struct i2c_lock_operations *lock_ops;
	struct rt_mutex bus_lock;
	struct rt_mutex mux_lock;

	int timeout;			/* in jiffies */
	int retries;
	struct device dev;		/* the adapter device */

	int nr;
	char name[48];
	struct completion dev_released;

	struct mutex userspace_clients_lock;
	struct list_head userspace_clients;

	struct i2c_bus_recovery_info *bus_recovery_info;
	const struct i2c_adapter_quirks *quirks;

	struct irq_domain *host_notify_domain;
};

i2c_algorithm中的关键函数master_xfer() 用于产生I2C访问周期需要的信号, 以i2c_msg(即I2C消息) 为单位(i2c_msg中的成员表明了I2C的传输地址、 方向、 缓冲区、 缓冲区长度等信息) 。

/**
 * struct i2c_msg - an I2C transaction segment beginning with START
 * @addr: Slave address, either seven or ten bits.  When this is a ten
 *	bit address, I2C_M_TEN must be set in @flags and the adapter
 *	must support I2C_FUNC_10BIT_ADDR.
 * @flags: I2C_M_RD is handled by all adapters.  No other flags may be
 *	provided unless the adapter exported the relevant I2C_FUNC_*
 *	flags through i2c_check_functionality().
 * @len: Number of data bytes in @buf being read from or written to the
 *	I2C slave address.  For read transactions where I2C_M_RECV_LEN
 *	is set, the caller guarantees that this buffer can hold up to
 *	32 bytes in addition to the initial length byte sent by the
 *	slave (plus, if used, the SMBus PEC); and this value will be
 *	incremented by the number of block data bytes received.
 * @buf: The buffer into which data is read, or from which it's written.
 *
 * An i2c_msg is the low level representation of one segment of an I2C
 * transaction.  It is visible to drivers in the @i2c_transfer() procedure,
 * to userspace from i2c-dev, and to I2C adapter drivers through the
 * @i2c_adapter.@master_xfer() method.
 *
 * Except when I2C "protocol mangling" is used, all I2C adapters implement
 * the standard rules for I2C transactions.  Each transaction begins with a
 * START.  That is followed by the slave address, and a bit encoding read
 * versus write.  Then follow all the data bytes, possibly including a byte
 * with SMBus PEC.  The transfer terminates with a NAK, or when all those
 * bytes have been transferred and ACKed.  If this is the last message in a
 * group, it is followed by a STOP.  Otherwise it is followed by the next
 * @i2c_msg transaction segment, beginning with a (repeated) START.
 *
 * Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then
 * passing certain @flags may have changed those standard protocol behaviors.
 * Those flags are only for use with broken/nonconforming slaves, and with
 * adapters which are known to support the specific mangling options they
 * need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR).
 */
struct i2c_msg {
	__u16 addr;	/* slave address			*/
	__u16 flags;
#define I2C_M_RD		0x0001	/* read data, from slave to master */
					/* I2C_M_RD is guaranteed to be 0x0001! */
#define I2C_M_TEN		0x0010	/* this is a ten bit chip address */
#define I2C_M_RECV_LEN		0x0400	/* length will be first received byte */
#define I2C_M_NO_RD_ACK		0x0800	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK	0x1000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_REV_DIR_ADDR	0x2000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NOSTART		0x4000	/* if I2C_FUNC_NOSTART */
#define I2C_M_STOP		0x8000	/* if I2C_FUNC_PROTOCOL_MANGLING */
	__u16 len;		/* msg length				*/
	__u8 *buf;		/* pointer to msg data			*/
};

i2c通信方法

i2c_algorithm是为一类使用相同总线算法寻址的一个接口。

  • 当适配器不能使用i2c访问设备时,把master_xfer设置为NULL
  • 如果一个适配器可以做SMBus访问时,设置smbus_xfer;如果把smbus_xfer设置成NULL,SMBus协议使用通用I2C模拟的消息。
/**
 * struct i2c_algorithm - represent I2C transfer method
 * @master_xfer: 
     Issue a set of i2c transactions to the given I2C adapter defined by the 
     msgs array, with num messages available to transfer via the adapter 
     specified by adap.
 * @smbus_xfer: 
  	 Issue smbus transactions to the given I2C adapter. If this is not present,
     then the bus layer will try and convert the SMBus calls into I2C transfers
     instead.
 * @functionality: Return the flags that this algorithm/adapter pair supports
 *   from the I2C_FUNC_* flags.
 * @reg_slave: Register given client to I2C slave mode of this adapter
 * @unreg_slave: Unregister given client from I2C slave mode of this adapter
 *
 * 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.
 */
struct i2c_algorithm {
	/* If an adapter algorithm can't do I2C-level access, set master_xfer
	   to NULL. If an adapter algorithm can do SMBus access, set
	   smbus_xfer. If set to NULL, the SMBus protocol is simulated
	   using common I2C messages */
	/* master_xfer should return the number of messages successfully
	   processed, or a negative value on error */
	int (*master_xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs,
			   int num); 
    // 向msgs数组定义的给定i2c适配器发出一组i2c事务,其中num条消息可通过adap指定的适配器传输。
	int (*smbus_xfer) (struct i2c_adapter *adap, u16 addr,
			   unsigned short flags, char read_write,
			   u8 command, int size, union i2c_smbus_data *data);
    //  向给定的I2C适配器发出smbus事务。如果这不存在,那么总线层将尝试将SMBus调用转换为I2C传输。

	/* To determine what the adapter supports */
	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
};

对象之间的关系

i2c_adapter和i2c_algorithm

由于i2c_adapter对应与物理上的一个适配器,而i2c_algorithm对应一套通信方法。

一个i2c适配器需要i2c_algorithm中提供的通信函数来控制适配器上产生特定的访问周期。

缺少i2c_algorithm的i2c_adapter什么也做不了,因此i2c_adapter中包含其使用i2c_algorithm的指针。

i2c_driver和i2c_client

i2c_driver对应于一套驱动方法, 其主要成员函数是probe()remove()suspend()resume()等;

另外, struct i2c_device_id形式的id_table是该驱动所支持的I2C设备的ID表。 i2c_client对应于真实的物理设备, 每个I2C设备都需要一个i2c_client来描述。 i2c_driveri2c_client的关系是一对多, 一个i2c_driver可以支持多个同类型的i2c_client

每个探测到的设备通过在client数据结构中得到自己的数据

在I2C总线驱动i2c_bus_type的match()函数i2c_device_match() 中, 会调用i2c_match_id() 函数匹配在板文件中定义的ID和i2c_driver所支持的ID表。

static int i2c_device_match(struct device *dev, struct device_driver *drv)
{
    struct i2c_client	*client = i2c_verify_client(dev);
    struct i2c_driver	*driver;

    if (!client)
        return 0;

    driver = to_i2c_driver(drv);
    /* match on an id table if there is one */
    if (driver->id_table)
        return i2c_match_id(driver->id_table, client) != NULL;

    return 0;
}

static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
                                                const struct i2c_client *client)
{
    while (id->name[0]) {
        if (strcmp(client->name, id->name) == 0)
            return id;
        id++;
    }
    return NULL;
}

i2c_adpater与i2c_client

i2c_adpater与i2c_client的关系与I2C硬件体系中适配器和设备的关系一致, 即i2c_client依附于i2c_adpater。 由于一个适配器可以连接多个I2C设备, 所以一个i2c_adpater也可以被多个i2c_client依附,i2c_adpater中包括依附于它的i2c_client的链表。

参考

https://i2c.wiki.kernel.org/index.php/Driver_Architecture
https://blog.csdn.net/xie0812/article/details/22942375

整理了一些学习书籍、视频资料(Linux 内核,有需要的可以自行添加学习交流群:739729163 领取哦!!!

本篇文章由 Schips 经过整理后发布。

你可能感兴趣的:(Linux,linux)