【Linux驱动开发】I2C

Linux内核将I2C驱动分成两部分

  • I2C总线驱动:SOC的I2C控制器驱动,也称为I2C适配器驱动。半导体厂商编写
  • I2C设备驱动:具体I2C设备的驱动。SOC使用者编写

I2C总线驱动

Linux内核将SOC的I2C适配器抽象为i2c_adapter,include/linux/i2c.h。

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	*/
	struct rt_mutex bus_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;
};
  • i2c_algorithm类型的指针变量algo,是I2C适配器与I2C设备通信的方法,include/linux/i2c.h。
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);
	int (*smbus_xfer) (struct i2c_adapter *adap, u16 addr,
			   unsigned short flags, char read_write,
			   u8 command, int size, union i2c_smbus_data *data);

	/* 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
};
  • master_xfer:I2C适配器传输函数,与I2C设备进行通信。
  • smbus_xfer:SMBUS总线的传输函数。

I2C总线驱动首先初始化i2c_adapter结构体变量,然后设置i2c_algorithm中的master_xfer函数,最后通过i2c_add_adapteri2c_add_numbered_adapter函数向Linux系统注册。

int i2c_add_adapter(struct i2c_adapter *adapter);
int i2c_add_numbered_adapter(struct i2c_adapter *adap);
  • adapter/adap:要注册的I2C适配器。
  • 返回值:0,成功;负值,失败。

使用i2c_del_adapter删除I2C适配器。

void i2c_del_adapter(struct i2c_adapter *adap);
  • adap:要删除的I2C适配器。
  • 返回值:无。

I2C设备驱动

Linux定义i2c_client结构体描述设备信息,include/linux/i2c.h。

/**
 * struct i2c_client - represent an I2C slave device
 * @flags: I2C_CLIENT_TEN indicates the device uses a ten bit chip address;
 *	I2C_CLIENT_PEC indicates it uses SMBus Packet Error Checking
 * @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.
 */
struct i2c_client {
	unsigned short flags;		/* 标志 */
	unsigned short addr;		/* 芯片地址,低7位 */
	char name[I2C_NAME_SIZE];   /* 名字*/
	struct i2c_adapter *adapter;/* I2C适配器 */
	struct device dev;		    /* 设备结构体 */
	int irq;			        /* 设备中断 */
	struct list_head detected;  /* 成员列表 */
#if IS_ENABLED(CONFIG_I2C_SLAVE)
	i2c_slave_cb_t slave_cb;	/* 回调	*/
#endif
};

一个设备对应一个i2c_client,每检测到一个I2C设备就给这个I2C设备分配一个i2c_client。

Linux定义i2c_driver结构体描述驱动信息,include/linux/i2c.h。

/**
 * 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
 * @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)
 *
 * 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 *);

	/* 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").
	 */
	void (*alert)(struct i2c_client *, unsigned int data);

	/* 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);

	struct device_driver driver;
	const struct i2c_device_id *id_table;

	/* Device detection callback for automatic device creation */
	int (*detect)(struct i2c_client *, struct i2c_board_info *);
	const unsigned short *address_list;
	struct list_head clients;
};
  • probe和remove函数在I2C设备匹配成功和关闭驱动后执行。
  • device_driver:驱动结构体,使用设备树时需要设置of_match_table成员变量。
  • id_table:未使用设备树的匹配列表。

i2c_driver初始化完成后,使用i2c_register_driver向Linux内核注册。

int i2c_register_driver(struct module     *owner,
                        struct i2c_driver *driver);
  • owner:THIS_MODULE。
  • driver:要注册的i2c_driver。
  • 返回值:0,成功;负值,失败。

也可使用宏i2c_add_driver注册,对i2c_register_driver进行封装,只有一个driver参数。

#define i2c_add_driver(driver) i2c_register_driver(THIS_MODULE, driver)

使用i2c_del_driver注销I2C设备驱动。

void i2c_del_driver(struct i2c_driver *driver);
  • driver:要注销的i2c_driver。
  • 返回值:无。

i2c_driver注册流程

static int xxx_probe(struct i2c_client *client, 
                     const struct i2c_device_id *id)
{
    /* ... */
    return 0;
}

static int xxx_remove(struct i2c_client *client)
{
    /* ... */
    return 0;
}

/* 无设备树匹配ID列表 */
static const struct i2c_device_id xxx_id[] = {
    {"xxx", 0},
    {}
};

/* 设备树匹配列表 */
static const struct of_device_id xxx_of_match[] = {
    {.compatible = "xxx"},
    {}
};

/* I2C驱动结构体 */
static struct i2c_driver xxx_driver = {
    .probe = xxx_probe,
    .remove = xxx_remove,
    .driver = {
        .owner = THIS_MODULE,
        .name = "xxx",
        .of_match_table = xxx_of_match,
    },
    .id_table = xxx_id,
};

/* 驱动入口函数 */
static int __init xxx_init(void)
{
    int ret = 0;
    ret = i2c_add_driver(&xxx_driver);
    return ret;    
}

/* 驱动出口函数 */
static void __exit xxx_exit(void)
{
    i2c_del_driver(&xxx_driver);
}

module_init(xxx_init);
module_exit(xxx_exit);

I2C设备信息描述

未使用设备树

在BSP里面使用i2c_board_info结构体描述一个具体的I2C设备。

/**
 * struct i2c_board_info - template for device creation
 * @type: chip type, to initialize i2c_client.name
 * @flags: to initialize i2c_client.flags
 * @addr: stored in i2c_client.addr
 * @platform_data: stored in i2c_client.dev.platform_data
 * @archdata: copied into i2c_client.dev.archdata
 * @of_node: pointer to OpenFirmware device node
 * @fwnode: device node supplied by the platform firmware
 * @irq: stored in i2c_client.irq
 *
 * 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.
 */
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;
	int		irq;
};
  •  两个必须设置的变量:type,I2C设备名字。addr,I2C器件地址。

例如:未使用设备树的OV2540的I2C设备信息描述,使用了I2C_BOARD_INFO宏。

/**
 * I2C_BOARD_INFO - macro used to list an i2c device and its address
 * @dev_type: identifies the device type
 * @dev_addr: the device's address on the bus.
 *
 * 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.
 */
#define I2C_BOARD_INFO(dev_type, dev_addr) \
	.type = dev_type, .addr = (dev_addr)
static struct i2c_board_info mx27_3ds_i2c_camera = {
    I2C_BOARD_INFO("ov2640", 0x30);
};

使用设备树

在设备树中创建对应I2C设备节点。

例如:在i2c1节点下创建mag3110磁力计节点和ap3216c三合一传感器,描述这个两个I2C设备信息。

&i2c1 {
	clock-frequency = <100000>;
	pinctrl-names = "default";
	pinctrl-0 = <&pinctrl_i2c1>;
	status = "okay";

	mag3110@0e {
		compatible = "fsl,mag3110";
		reg = <0x0e>;
		position = <2>;
	};

	ap3216c@1e {
		compatible = "ap3216c";
		reg = <0x1e>;
	};
};

&iomuxc {
	pinctrl-names = "default";
	pinctrl-0 = <&pinctrl_hog_1>;
	imx6ul-evk {
		pinctrl_i2c1: i2c1grp {
			fsl,pins = <
				MX6UL_PAD_UART4_TX_DATA__I2C1_SCL 0x4001b8b0
				MX6UL_PAD_UART4_RX_DATA__I2C1_SDA 0x4001b8b0
			>;
		};
    };
};
  • ap3216c@1e:ap3216c为子节点名字,1e为ap3216c的I2C器件地址。
  • compatible属性:用于匹配驱动。
  • reg属性:用于设置器件地址,此处为ap3216c的I2C器件地址。

I2C设备数据收发

使用i2c_transfer函数会调用I2C适配器中的i2c_algorithm里面的master_xfer函数。

int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
  • adap:使用的I2C适配器,i2c_client保存对应的i2c_adapter。
  • msgs:I2C要发送的一个或多个消息。
  • num:msgs消息数量。
  • 返回值:非负值,发送的msgs数量;负值,失败。

Linux内核定义i2c_msg结构体描述消息,include/uapi/linux/i2c.h。

/**
 * 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. 
 */
struct i2c_msg {
	__u16 addr;	/* slave address			*/
	__u16 flags;
#define I2C_M_TEN		    0x0010	/* this is a ten bit chip address */
#define I2C_M_RD		    0x0001	/* read data, from slave to master */
#define I2C_M_STOP		    0x8000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NOSTART		0x4000	/* if I2C_FUNC_NOSTART */
#define I2C_M_REV_DIR_ADDR	0x2000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_IGNORE_NAK	0x1000	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_NO_RD_ACK		0x0800	/* if I2C_FUNC_PROTOCOL_MANGLING */
#define I2C_M_RECV_LEN		0x0400	/* length will be first received byte */
	__u16 len;		/* msg length				*/
	__u8 *buf;		/* pointer to msg data			*/
};
  • addr:从机地址。
  • flags:标志。
  • len:消息长度
  • buf:消息数据。

I2C数据收发

struct xxx_dev{
    void *private_data; /* 私有数据 */
};

/* 读取I2C设备多个寄存器数据 
 * dev:I2C设备;reg:读取的寄存器地址;val:读取的数据;len:读取数据长度
*/
static int xxx_read_regs(struct xxx_dev *dev, u8 reg, void *val, int len)
{
    int ret;
    struct i2c_msg msg[2];
    struct i2c_client *client = (struct i2c_client *)dev->private_data;
    
    /* msg[0] 第一条写消息,发送要读取的寄存器首地址 */
    msg[0].addr = client->addr;    /* I2C器件地址 */
    msg[0].flags = 0;              /* 标记为发送数据 */
    msg[0].buf = ®             /* 读取的首地址 */
    msg[0].len = 1;                /* reg长度 */

    /* msg[1] 第二条读消息,读取寄存器数据 */
    msg[1].addr = client->addr;    /* I2C器件地址 */
    msg[1].flags = I2C_M_RD;       /* 标记为读取数据 */
    msg[1].buf = val;              /* 读取数据缓冲区 */
    msg[1].len = len;              /* 要读取的数据长度*/

    ret = i2c_transfer(client->adapter, msg, 2);
    if(ret == 2) {
        ret = 0;
    } else {
        ret = -EREMOTEIO;
    }
    return ret;
}

/* 向I2C设备多个寄存器写入数据
 * dev:I2C设备;reg:写入的寄存器地址;val:写入的数据;len:写入的数据长度
*/
static int xxx_write_regs(struct xxx_dev *dev, u8 reg, u8 *buf, u8 len)
{
    u8 b[256];
    struct i2c_msg msg;
    struct i2c_client *client = (struct i2c_client *)dev->private_data;

    b[0] = reg; /* 寄存器首地址 */
    memcpy(&b[1], buf, len); /* 发送的数据拷贝数组b中 */
    msg.addr = client->addr; /* I2C器件地址 */
    msg.flags = 0;           /* 标记为写数据 */
    msg.buf = b;             /* 要发送的数据缓冲区 */
    msg.len = len + 1;       /* 要发送的数据长度 */

    return i2c_transfer(client->adapter, &msg, 1);
}

API函数-发送数据i2c_master_send

int i2c_master_send(const struct i2c_client *client,
                    const char              *buf,
                    int                     count);
  • client:i2c_client。
  • buf:要发送的数据。
  • count:要发送的数据字节数,小于64KB。
  • 返回值:非负值,发送的字节数;负值,失败。

API函数-接收数据i2c_master_recv

int i2c_master_recv(const struct i2c_client *client,
                    char                    *buf,
                    int                     count)
  • client:i2c_client。
  • buf:要接收的数据。
  • count:要接收的数据字节数,小于64KB。
  • 返回值:非负值,接收的字节数;负值,失败。

你可能感兴趣的:(Linux,驱动开发,linux,I2C)