2019独角兽企业重金招聘Python工程师标准>>>
备注:所有图片来源于网络
1,I2C协议:
物理拓扑:
I2C总线由两根信号线组成,一条是时钟信号线SCL,一条是数据信号线SDA。一条I2C总线可以接多个设备,每个设备都接入I2C总线的SCL和SDA。I2C总线是主从模式的总线架构,每个设备都可以作为主设备,其他设备作为从设备,但是同一时刻只能有一个主设备。其物理总线拓扑图如下(图片来源于网络):
总线协议:
(1)起始条件(边沿触发):当SCL总线处于高电平时,SDA总线从高电平到低电平的跳变触发一次传输的开始条件。
(2)结束条件(边沿触发):当SCL总线处于高电平时,SDA总线从低电平到高电平的跳变触发一次传输的结束条件。
起始和结束的时序图如下:
(3)数据传输格式:
起始条件触发之后,SCL处于高电平时,检测SDA总线的高低电平值1和0,SCL处于低电平时,SDA高低电平跳变切换数据1和0。
SDA的数据传输以8bit(一个字节)为单位,每个字节传输之后都跟随一个bit的ACK位。起始条件之后的第一个字节应该是地址字段(包含7bit的地址+1bit的R/W位),随后是8bit为单位的数据,数据可以无限制的多次发送。注意,地址字节和每个数据字节之后都跟随一个bit的ACK位。
I2C总线的数据格式如下:
I2C的传输数据时序图如下:
(4)以s3c24xx I2C为例,可以工作在4中模式:主机发送模式,主机接收模式,从机发送模式,从机接收模式。Linux中主要应用主机发送和接收模式。主机发送模式如下:
主机接收模式如下:
2,内核中I2C驱动框架
Kernel中I2C总线框架分为三层:I2C总线核心层,I2C总线控制器驱动层,I2C设备驱动层。
(1)总线核心层:这是I2C的核心框架层,定义了I2C核心的数据结构,提供了I2C控制器,I2C设备和驱动的注册/注销框架,并提供了设备数据传输接口。如下:
控制器注册注销接口:int i2c_add_adapter(struct i2c_adapter *adapter);
void i2c_del_adapter(struct i2c_adapter *adap);
设备驱动注册注销接口:int i2c_register_driver(struct module *owner, struct i2c_driver *driver);
void i2c_del_driver(struct i2c_driver *driver);
数据传输接口:int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num);
int i2c_master_send(const struct i2c_client *client, const char *buf, int count);
int i2c_master_recv(const struct i2c_client *client, char *buf, int count);
(2)控制器驱动层:由 i2c_adapter 结构描述了某个具体的I2C总线控制器特性,并通过 i2c_algorithm 结构提供了I2C总线周期的开始,停止,数据发送和接收等方法。同一个i2c_algorithm可以提供给多个 i2c_adapter 使用,i2c_adapter在注册的同时,会去(通过设备树配置或者老式的platform相关的硬编码)轮询该i2c总线下的所有i2c设备,并创建对应的 i2c_client 设备。换句话说,注册一个i2c_adapter,该总线下的所有从设备都会被注册到 i2c_bus_type下。
(3)设备驱动层:由 i2c_driver 结构表示,用于表示各个具体从设备的驱动,跟 i2c_client 绑定,通过 i2c_client 关联的 adapter的algorithm实现具体从设备的通信协议。遵循kernel设备驱动框架,注册在 i2c_bus_type 下【i2c_bus_type总线下挂 i2c_driver 和 i2c_client,注册 i2c_driver 的时候,会去轮询 i2c_bus_type 总线下的所有 i2c_client 设备,调用 bus 的 match()方法,匹配后,调用 i2c_driver 的probe()方法并关联该 i2c_client。在注册 i2c_adapter 同时,扫描注册该总线下所有的 i2c_client的时候,调用 bus 的match()方法匹配 i2c_bus_type 总线下的 i2c_driver 驱动后,在调用 i2c_driver的probe()方法并关联该 i2c_driver】。
这三层之间的关系如下:
3,I2C驱动框架源码分析
(1)I2C设备控制器注册:int i2c_add_adapter(struct i2c_adapter *adapter);
int i2c_add_adapter(struct i2c_adapter *adapter)
{
struct device *dev = &adapter->dev;
int id;
if (dev->of_node) {
id = of_alias_get_id(dev->of_node, "i2c"); // 通过设备树配置获取 i2c 的总线编号
if (id >= 0) {
adapter->nr = id;
return __i2c_add_numbered_adapter(adapter); // 注册已编号的adapter,内部调用 i2c_register_adapter()
}
}
mutex_lock(&core_lock);
id = idr_alloc(&i2c_adapter_idr, adapter,
__i2c_first_dynamic_bus_num, 0, GFP_KERNEL); // 动态获取 i2c 总线编号
mutex_unlock(&core_lock);
if (id < 0)
return id;
adapter->nr = id;
return i2c_register_adapter(adapter); // 注册adapter
}
static int i2c_register_adapter(struct i2c_adapter *adap)
{
int res = 0;
/* Can't register until after driver model init */
if (unlikely(WARN_ON(!i2c_bus_type.p))) {
res = -EAGAIN;
goto out_list;
}
/* Sanity checks */
if (unlikely(adap->name[0] == '\0')) {
pr_err("i2c-core: Attempt to register an adapter with "
"no name!\n");
return -EINVAL;
}
if (unlikely(!adap->algo)) {
pr_err("i2c-core: Attempt to register adapter '%s' with "
"no algo!\n", adap->name);
return -EINVAL;
}
rt_mutex_init(&adap->bus_lock);
mutex_init(&adap->userspace_clients_lock);
INIT_LIST_HEAD(&adap->userspace_clients);
/* Set default timeout to 1 second if not already set */
if (adap->timeout == 0)
adap->timeout = HZ;
dev_set_name(&adap->dev, "i2c-%d", adap->nr);
adap->dev.bus = &i2c_bus_type; // adapter 注册在 i2c_bus_type 总线下
adap->dev.type = &i2c_adapter_type; // 设置 dev 的类型是 i2c_adapter_type 类型,用以区分其他设备类型
res = device_register(&adap->dev); // 注册进kernel设备框架
if (res)
goto out_list;
dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
pm_runtime_no_callbacks(&adap->dev);
#ifdef CONFIG_I2C_COMPAT
res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
adap->dev.parent);
if (res)
dev_warn(&adap->dev,
"Failed to create compatibility class link\n");
#endif
/* bus recovery specific initialization */
if (adap->bus_recovery_info) {
struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
if (!bri->recover_bus) {
dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
adap->bus_recovery_info = NULL;
goto exit_recovery;
}
/* Generic GPIO recovery */
if (bri->recover_bus == i2c_generic_gpio_recovery) {
if (!gpio_is_valid(bri->scl_gpio)) {
dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
adap->bus_recovery_info = NULL;
goto exit_recovery;
}
if (gpio_is_valid(bri->sda_gpio))
bri->get_sda = get_sda_gpio_value;
else
bri->get_sda = NULL;
bri->get_scl = get_scl_gpio_value;
bri->set_scl = set_scl_gpio_value;
} else if (!bri->set_scl || !bri->get_scl) {
/* Generic SCL recovery */
dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
adap->bus_recovery_info = NULL;
}
}
exit_recovery:
/* create pre-declared device nodes */
of_i2c_register_devices(adap); // 扫描设备树配置,构造i2c_board_info创建 i2c_client并注册
acpi_i2c_register_devices(adap);
acpi_i2c_install_space_handler(adap);
if (adap->nr < __i2c_first_dynamic_bus_num)
i2c_scan_static_board_info(adap); // 根据前期静态配置好的board info,创建并注册i2c_client
/* Notify drivers */
mutex_lock(&core_lock);
bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter); // 扫描 i2c_bus_type 总线下的驱动i2c_driver,探测并创建driver支持的 i2c_client,注册之
mutex_unlock(&core_lock);
return 0;
out_list:
mutex_lock(&core_lock);
idr_remove(&i2c_adapter_idr, adap->nr);
mutex_unlock(&core_lock);
return res;
}
static int __process_new_adapter(struct device_driver *d, void *data)
{
return i2c_do_add_adapter(to_i2c_driver(d), data); // 匹配 i2c_driver 下的 address_list,探测 i2c_client
}
static int i2c_do_add_adapter(struct i2c_driver *driver,
struct i2c_adapter *adap)
{
/* Detect supported devices on that bus, and instantiate them */
i2c_detect(adap, driver); // 探测 i2c_client
/* Let legacy drivers scan this bus for matching devices */
if (driver->attach_adapter) {
dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
driver->driver.name);
dev_warn(&adap->dev, "Please use another way to instantiate "
"your i2c_client\n");
/* We ignore the return code; if it fails, too bad */
driver->attach_adapter(adap);
}
return 0;
}
static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
{
const unsigned short *address_list;
struct i2c_client *temp_client;
int i, err = 0;
int adap_id = i2c_adapter_id(adapter);
address_list = driver->address_list; // 驱动支持的 i2c_client address
if (!driver->detect || !address_list)
return 0;
/* Warn that the adapter lost class based instantiation */
if (adapter->class == I2C_CLASS_DEPRECATED) {
dev_dbg(&adapter->dev,
"This adapter dropped support for I2C classes and "
"won't auto-detect %s devices anymore. If you need it, check "
"'Documentation/i2c/instantiating-devices' for alternatives.\n",
driver->driver.name);
return 0;
}
/* Stop here if the classes do not match */
if (!(adapter->class & driver->class))
return 0;
/* Set up a temporary client to help detect callback */
temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL); // 创建临时 i2c_client
if (!temp_client)
return -ENOMEM;
temp_client->adapter = adapter;
for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
"addr 0x%02x\n", adap_id, address_list[i]);
temp_client->addr = address_list[i];
err = i2c_detect_address(temp_client, driver); // 根据 driver 支持的 address_list,执行探测函数
if (unlikely(err))
break;
}
kfree(temp_client);
return err;
}
static int i2c_detect_address(struct i2c_client *temp_client,
struct i2c_driver *driver)
{
struct i2c_board_info info;
struct i2c_adapter *adapter = temp_client->adapter;
int addr = temp_client->addr;
int err;
/* Make sure the address is valid */
err = i2c_check_7bit_addr_validity_strict(addr);
if (err) {
dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
addr);
return err;
}
/* Skip if already in use (7 bit, no need to encode flags) */
if (i2c_check_addr_busy(adapter, addr))
return 0;
/* Make sure there is something at this address */
if (!i2c_default_probe(adapter, addr)) // 执行默认的探测函数
return 0;
/* Finally call the custom detection function */
memset(&info, 0, sizeof(struct i2c_board_info));
info.addr = addr;
err = driver->detect(temp_client, &info); // 执行驱动定义的探测函数
if (err) {
/* -ENODEV is returned if the detection fails. We catch it
here as this isn't an error. */
return err == -ENODEV ? 0 : err;
}
/* Consistency check */
if (info.type[0] == '\0') {
dev_err(&adapter->dev, "%s detection function provided "
"no name for 0x%x\n", driver->driver.name,
addr);
} else {
struct i2c_client *client;
/* Detection succeeded, instantiate the device */
if (adapter->class & I2C_CLASS_DEPRECATED)
dev_warn(&adapter->dev,
"This adapter will soon drop class based instantiation of devices. "
"Please make sure client 0x%02x gets instantiated by other means. "
"Check 'Documentation/i2c/instantiating-devices' for details.\n",
info.addr);
dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
info.type, info.addr);
client = i2c_new_device(adapter, &info); // 创建并注册这个正式的 i2c_client
if (client)
list_add_tail(&client->detected, &driver->clients); // 将该 i2c_client 链入 driver->clients链表
else
dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
info.type, info.addr);
}
return 0;
}
由上面的代码流程可见,在注册 i2c_adapter的过程中,i2c核心层会根据设备树配置,静态board info 配置去创建该 i2c_adapter下的子设备 i2c_client并匹配相应的 i2c_driver,最后注册进 i2c_bus_type。
(2)I2C设备驱动注册:int i2c_register_driver(struct module *owner, struct i2c_driver *driver);
int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
{
int res;
/* Can't register until after driver model init */
if (unlikely(WARN_ON(!i2c_bus_type.p)))
return -EAGAIN;
/* add the driver to the list of i2c drivers in the driver core */
driver->driver.owner = owner;
driver->driver.bus = &i2c_bus_type; // 设置驱动的注册总线 i2c_bus_type
/* When registration returns, the driver core
* will have called probe() for all matching-but-unbound devices.
*/
res = driver_register(&driver->driver); // 注册进kernel设备驱动框架
if (res)
return res;
pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
INIT_LIST_HEAD(&driver->clients);
/* Walk the adapters that are already present */
i2c_for_each_dev(driver, __process_new_driver); // 轮询 i2c_bus_type 下的所有设备,并匹配驱动
return 0;
}
static int __process_new_driver(struct device *dev, void *data)
{
if (dev->type != &i2c_adapter_type) // 非 i2c_adapter 不能进一步处理
return 0;
return i2c_do_add_adapter(data, to_i2c_adapter(dev)); // 根据该驱动支持的address list,探测,创建并注册相应的i2c_client
}
(3)I2C 数据发送:int i2c_master_send(const struct i2c_client *client, const char *buf, int count);
int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
{
int ret;
struct i2c_adapter *adap = client->adapter;
struct i2c_msg msg;
// 构造 i2c_msg
msg.addr = client->addr;
msg.flags = client->flags & I2C_M_TEN;
msg.len = count;
msg.buf = (char *)buf;
ret = i2c_transfer(adap, &msg, 1); // 发送数据
/*
* If everything went ok (i.e. 1 msg transmitted), return #bytes
* transmitted, else error code.
*/
return (ret == 1) ? count : ret;
}
int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
{
int ret;
/* REVISIT the fault reporting model here is weak:
*
* - When we get an error after receiving N bytes from a slave,
* there is no way to report "N".
*
* - When we get a NAK after transmitting N bytes to a slave,
* there is no way to report "N" ... or to let the master
* continue executing the rest of this combined message, if
* that's the appropriate response.
*
* - When for example "num" is two and we successfully complete
* the first message but get an error part way through the
* second, it's unclear whether that should be reported as
* one (discarding status on the second message) or errno
* (discarding status on the first one).
*/
if (adap->algo->master_xfer) {
#ifdef DEBUG
for (ret = 0; ret < num; ret++) {
dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
"len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
(msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
}
#endif
if (in_atomic() || irqs_disabled()) {
ret = i2c_trylock_adapter(adap);
if (!ret)
/* I2C activity is ongoing. */
return -EAGAIN;
} else {
i2c_lock_adapter(adap);
}
ret = __i2c_transfer(adap, msgs, num); // 锁定 i2c_adapter,然后调用 __i2c_transfer 进行实际的数据发送
i2c_unlock_adapter(adap);
return ret;
} else {
dev_dbg(&adap->dev, "I2C level transfers not supported\n");
return -EOPNOTSUPP;
}
}
int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
{
unsigned long orig_jiffies;
int ret, try;
if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
return -EOPNOTSUPP;
/* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
* enabled. This is an efficient way of keeping the for-loop from
* being executed when not needed.
*/
if (static_key_false(&i2c_trace_msg)) {
int i;
for (i = 0; i < num; i++)
if (msgs[i].flags & I2C_M_RD)
trace_i2c_read(adap, &msgs[i], i);
else
trace_i2c_write(adap, &msgs[i], i);
}
/* Retry automatically on arbitration loss */
orig_jiffies = jiffies;
for (ret = 0, try = 0; try <= adap->retries; try++) {
ret = adap->algo->master_xfer(adap, msgs, num); // 最终调用i2c_client关联的adapter的algo的master_xfer方法
if (ret != -EAGAIN)
break;
if (time_after(jiffies, orig_jiffies + adap->timeout))
break;
}
if (static_key_false(&i2c_trace_msg)) {
int i;
for (i = 0; i < ret; i++)
if (msgs[i].flags & I2C_M_RD)
trace_i2c_reply(adap, &msgs[i], i);
trace_i2c_result(adap, i, ret);
}
return ret;
}
由此可见,每个具体子设备的数据发送和接收,最终还是调用adapter的algorithm方法。adapter的algorithm实现的是底层的I2C总线协议,是该总线通用的数据收发方法。每个子设备的更复杂的协议是建立在该通用方法之上。
4,s3c24xx I2C控制器驱动分析
源码路径:drivers/i2c/busses/i2c-s3c2410.c
I2C控制器设备要么通过设备树配置,要么通过平台相关代码在kernel初始化时注册到系统platform总线。那么,通过注册一个platform_driver,匹配该 i2c 控制器设备 platform_device,然后在driver的probe()的时候,注册该i2c的adapter。也就是说,通过注册一个i2c的platform_driver,最终会把该i2c总线的adapter及该总线下的所有i2c_client全部注册起来,如果总线上预先注册了i2c_driver驱动,在注册i2c_client的同时,也会去匹配相应的i2c_driver驱动。代码分析如下:
(1)i2c_adapter注册:
static struct platform_driver s3c24xx_i2c_driver = {
.probe = s3c24xx_i2c_probe, // 驱动探测方法
.remove = s3c24xx_i2c_remove,
.id_table = s3c24xx_driver_ids, // 平台设备id_table匹配
.driver = {
.name = "s3c-i2c",
.pm = S3C24XX_DEV_PM_OPS,
.of_match_table = of_match_ptr(s3c24xx_i2c_match), // 设备树 compatible 字段匹配
},
};
static int __init i2c_adap_s3c_init(void)
{
return platform_driver_register(&s3c24xx_i2c_driver);
}
subsys_initcall(i2c_adap_s3c_init); // 子系统初始化时调用 i2c_adap_s3c_init
struct s3c24xx_i2c { // 本质上这个结构是一个i2c_adapter
wait_queue_head_t wait; // 用户进程/线程等待队列
kernel_ulong_t quirks;
unsigned int suspended:1;
struct i2c_msg *msg; // i2c_msg类型数组
unsigned int msg_num; // i2c_msg数组大小
unsigned int msg_idx; // 处理数组的索引
unsigned int msg_ptr; // i2c_msg内部buffer索引
unsigned int tx_setup;
unsigned int irq; // 中断请求编号
enum s3c24xx_i2c_state state;
unsigned long clkrate;
void __iomem *regs; // 控制器寄存器起始地址
struct clk *clk;
struct device *dev;
struct i2c_adapter adap; // 内嵌一个 i2c_adapter 结构
struct s3c2410_platform_i2c *pdata;
int gpios[2];
struct pinctrl *pctrl;
#if defined(CONFIG_ARM_S3C24XX_CPUFREQ)
struct notifier_block freq_transition;
#endif
struct regmap *sysreg;
unsigned int sys_i2c_cfg;
};
static int s3c24xx_i2c_probe(struct platform_device *pdev)
{
struct s3c24xx_i2c *i2c;
struct s3c2410_platform_i2c *pdata = NULL;
struct resource *res;
int ret;
if (!pdev->dev.of_node) {
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "no platform data\n");
return -EINVAL;
}
}
i2c = devm_kzalloc(&pdev->dev, sizeof(struct s3c24xx_i2c), GFP_KERNEL); // 分配一个s3c24xx_i2c结构,本质上是一个i2c_adapter
if (!i2c)
return -ENOMEM;
i2c->pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!i2c->pdata)
return -ENOMEM;
i2c->quirks = s3c24xx_get_device_quirks(pdev);
i2c->sysreg = ERR_PTR(-ENOENT);
if (pdata)
memcpy(i2c->pdata, pdata, sizeof(*pdata));
else
s3c24xx_i2c_parse_dt(pdev->dev.of_node, i2c);
strlcpy(i2c->adap.name, "s3c2410-i2c", sizeof(i2c->adap.name));
i2c->adap.owner = THIS_MODULE;
i2c->adap.algo = &s3c24xx_i2c_algorithm; // 初始化adapter的算法结构
i2c->adap.retries = 2; // 重传次数
i2c->adap.class = I2C_CLASS_DEPRECATED;
i2c->tx_setup = 50;
init_waitqueue_head(&i2c->wait);
/* find the clock and enable it */
i2c->dev = &pdev->dev;
i2c->clk = devm_clk_get(&pdev->dev, "i2c");
if (IS_ERR(i2c->clk)) {
dev_err(&pdev->dev, "cannot get clock\n");
return -ENOENT;
}
dev_dbg(&pdev->dev, "clock source %p\n", i2c->clk);
/* map the registers */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
i2c->regs = devm_ioremap_resource(&pdev->dev, res); // 重映射 io端口寄存器
if (IS_ERR(i2c->regs))
return PTR_ERR(i2c->regs);
dev_dbg(&pdev->dev, "registers %p (%p)\n",
i2c->regs, res);
/* setup info block for the i2c core */
i2c->adap.algo_data = i2c;
i2c->adap.dev.parent = &pdev->dev;
i2c->pctrl = devm_pinctrl_get_select_default(i2c->dev);
/* inititalise the i2c gpio lines */
if (i2c->pdata->cfg_gpio) {
i2c->pdata->cfg_gpio(to_platform_device(i2c->dev));
} else if (IS_ERR(i2c->pctrl) && s3c24xx_i2c_parse_dt_gpio(i2c)) {
return -EINVAL;
}
/* initialise the i2c controller */
clk_prepare_enable(i2c->clk);
ret = s3c24xx_i2c_init(i2c); // 设置 i2c 分频
clk_disable(i2c->clk);
if (ret != 0) {
dev_err(&pdev->dev, "I2C controller init failed\n");
return ret;
}
/* find the IRQ for this unit (note, this relies on the init call to
* ensure no current IRQs pending
*/
if (!(i2c->quirks & QUIRK_POLL)) {
i2c->irq = ret = platform_get_irq(pdev, 0);
if (ret <= 0) {
dev_err(&pdev->dev, "cannot find IRQ\n");
clk_unprepare(i2c->clk);
return ret;
}
ret = devm_request_irq(&pdev->dev, i2c->irq, s3c24xx_i2c_irq, 0,
dev_name(&pdev->dev), i2c); // 请求中断,注册中断处理上半部
if (ret != 0) {
dev_err(&pdev->dev, "cannot claim IRQ %d\n", i2c->irq);
clk_unprepare(i2c->clk);
return ret;
}
}
ret = s3c24xx_i2c_register_cpufreq(i2c);
if (ret < 0) {
dev_err(&pdev->dev, "failed to register cpufreq notifier\n");
clk_unprepare(i2c->clk);
return ret;
}
/* Note, previous versions of the driver used i2c_add_adapter()
* to add the bus at any number. We now pass the bus number via
* the platform data, so if unset it will now default to always
* being bus 0.
*/
i2c->adap.nr = i2c->pdata->bus_num;
i2c->adap.dev.of_node = pdev->dev.of_node;
platform_set_drvdata(pdev, i2c);
pm_runtime_enable(&pdev->dev);
ret = i2c_add_numbered_adapter(&i2c->adap); // 注册 adapter
if (ret < 0) {
dev_err(&pdev->dev, "failed to add bus to i2c core\n");
pm_runtime_disable(&pdev->dev);
s3c24xx_i2c_deregister_cpufreq(i2c);
clk_unprepare(i2c->clk);
return ret;
}
pm_runtime_enable(&i2c->adap.dev);
dev_info(&pdev->dev, "%s: S3C I2C adapter\n", dev_name(&i2c->adap.dev));
return 0;
}
(2)中断处理函数:
static irqreturn_t s3c24xx_i2c_irq(int irqno, void *dev_id)
{
struct s3c24xx_i2c *i2c = dev_id;
unsigned long status;
unsigned long tmp;
status = readl(i2c->regs + S3C2410_IICSTAT);
if (status & S3C2410_IICSTAT_ARBITR) {
/* deal with arbitration loss */
dev_err(i2c->dev, "deal with arbitration loss\n");
}
if (i2c->state == STATE_IDLE) {
dev_dbg(i2c->dev, "IRQ: error i2c->state == IDLE\n");
tmp = readl(i2c->regs + S3C2410_IICCON);
tmp &= ~S3C2410_IICCON_IRQPEND;
writel(tmp, i2c->regs + S3C2410_IICCON);
goto out;
}
/* pretty much this leaves us with the fact that we've
* transmitted or received whatever byte we last sent */
i2c_s3c_irq_nextbyte(i2c, status); // 处理i2c消息状态
out:
return IRQ_HANDLED;
}
static int i2c_s3c_irq_nextbyte(struct s3c24xx_i2c *i2c, unsigned long iicstat)
{
unsigned long tmp;
unsigned char byte;
int ret = 0;
switch (i2c->state) {
case STATE_IDLE:
dev_err(i2c->dev, "%s: called in STATE_IDLE\n", __func__);
goto out;
case STATE_STOP:
dev_err(i2c->dev, "%s: called in STATE_STOP\n", __func__);
s3c24xx_i2c_disable_irq(i2c); // 停止中断处理,结束本次传输周期
goto out_ack; // 发送 ACK
case STATE_START:
/* last thing we did was send a start condition on the
* bus, or started a new i2c message
*/
if (iicstat & S3C2410_IICSTAT_LASTBIT &&
!(i2c->msg->flags & I2C_M_IGNORE_NAK)) { // 异常处理,发送START消息后没有收到ACK消息
/* ack was not received... */
dev_dbg(i2c->dev, "ack was not received\n");
s3c24xx_i2c_stop(i2c, -ENXIO);
goto out_ack;
}
if (i2c->msg->flags & I2C_M_RD)
i2c->state = STATE_READ; // 发送START消息后,修改I2C状态为接收数据状态
else
i2c->state = STATE_WRITE; // 发送START消息后,修改I2C状态为发送数据状态
/* terminate the transfer if there is nothing to do
* as this is used by the i2c probe to find devices. */
if (is_lastmsg(i2c) && i2c->msg->len == 0) {
s3c24xx_i2c_stop(i2c, 0);
goto out_ack;
}
if (i2c->state == STATE_READ)
goto prepare_read; // 准备好接收消息缓存,等待下次中断处理,转到 STATE_READ状态
/* fall through to the write state, as we will need to
* send a byte as well */
case STATE_WRITE:
/* we are writing data to the device... check for the
* end of the message, and if so, work out what to do
*/
if (!(i2c->msg->flags & I2C_M_IGNORE_NAK)) {
if (iicstat & S3C2410_IICSTAT_LASTBIT) {
dev_dbg(i2c->dev, "WRITE: No Ack\n");
s3c24xx_i2c_stop(i2c, -ECONNREFUSED);
goto out_ack;
}
}
// 发送数据
retry_write:
if (!is_msgend(i2c)) { // 当前消息没有发送完
byte = i2c->msg->buf[i2c->msg_ptr++];
writeb(byte, i2c->regs + S3C2410_IICDS); // 继续发送当前消息的一个字节
/* delay after writing the byte to allow the
* data setup time on the bus, as writing the
* data to the register causes the first bit
* to appear on SDA, and SCL will change as
* soon as the interrupt is acknowledged */
ndelay(i2c->tx_setup);
} else if (!is_lastmsg(i2c)) { // 上一个消息发送完,转到下一个消息开始
/* we need to go to the next i2c message */
dev_dbg(i2c->dev, "WRITE: Next Message\n");
i2c->msg_ptr = 0;
i2c->msg_idx++;
i2c->msg++;
/* check to see if we need to do another message */
if (i2c->msg->flags & I2C_M_NOSTART) {
if (i2c->msg->flags & I2C_M_RD) { // 异常处理,消息本身不支持 START,但是消息由WRITE变成READ必须发送START,停止
/* cannot do this, the controller
* forces us to send a new START
* when we change direction */
s3c24xx_i2c_stop(i2c, -EINVAL);
}
goto retry_write;
} else {
/* send the new start */
s3c24xx_i2c_message_start(i2c, i2c->msg); // 发送一个新的消息,必须重新传输 START 消息(addr+R/W)
i2c->state = STATE_START; // 状态重置为 STATE_START
}
} else {
/* send stop */
s3c24xx_i2c_stop(i2c, 0);
}
break;
case STATE_READ:
/* we have a byte of data in the data register, do
* something with it, and then work out whether we are
* going to do any more read/write
*/
byte = readb(i2c->regs + S3C2410_IICDS); // 从数据寄存器读取一个byte数据
i2c->msg->buf[i2c->msg_ptr++] = byte;
/* Add actual length to read for smbus block read */
if (i2c->msg->flags & I2C_M_RECV_LEN && i2c->msg->len == 1)
i2c->msg->len += byte;
// 准备好下一次传输buffer
prepare_read:
if (is_msglast(i2c)) {
/* last byte of buffer */
if (is_lastmsg(i2c))
s3c24xx_i2c_disable_ack(i2c); // 最后一个消息的最后一个字节,停止接收
} else if (is_msgend(i2c)) { // 当前消息buffer已满
/* ok, we've read the entire buffer, see if there
* is anything else we need to do */
if (is_lastmsg(i2c)) { // 当前消息是最后一个消息,传输已经完成,停止接收
/* last message, send stop and complete */
dev_dbg(i2c->dev, "READ: Send Stop\n");
s3c24xx_i2c_stop(i2c, 0); // 停止数据传输,唤醒等待队列上的进程/线程,完成数据传输
} else { // 当前消息缓存未满,准备好接收buffer,继续等待下一次中断接收处理
/* go to the next transfer */
dev_dbg(i2c->dev, "READ: Next Transfer\n");
i2c->msg_ptr = 0;
i2c->msg_idx++;
i2c->msg++;
}
}
break;
}
/* acknowlegde the IRQ and get back on with the work */
out_ack: // 清除中断挂起
tmp = readl(i2c->regs + S3C2410_IICCON);
tmp &= ~S3C2410_IICCON_IRQPEND;
writel(tmp, i2c->regs + S3C2410_IICCON);
out:
return ret;
}
static inline void s3c24xx_i2c_stop(struct s3c24xx_i2c *i2c, int ret)
{
unsigned long iicstat = readl(i2c->regs + S3C2410_IICSTAT);
dev_dbg(i2c->dev, "STOP\n");
/*
* The datasheet says that the STOP sequence should be:
* 1) I2CSTAT.5 = 0 - Clear BUSY (or 'generate STOP')
* 2) I2CCON.4 = 0 - Clear IRQPEND
* 3) Wait until the stop condition takes effect.
* 4*) I2CSTAT.4 = 0 - Clear TXRXEN
*
* Where, step "4*" is only for buses with the "HDMIPHY" quirk.
*
* However, after much experimentation, it appears that:
* a) normal buses automatically clear BUSY and transition from
* Master->Slave when they complete generating a STOP condition.
* Therefore, step (3) can be done in doxfer() by polling I2CCON.4
* after starting the STOP generation here.
* b) HDMIPHY bus does neither, so there is no way to do step 3.
* There is no indication when this bus has finished generating
* STOP.
*
* In fact, we have found that as soon as the IRQPEND bit is cleared in
* step 2, the HDMIPHY bus generates the STOP condition, and then
* immediately starts transferring another data byte, even though the
* bus is supposedly stopped. This is presumably because the bus is
* still in "Master" mode, and its BUSY bit is still set.
*
* To avoid these extra post-STOP transactions on HDMI phy devices, we
* just disable Serial Output on the bus (I2CSTAT.4 = 0) directly,
* instead of first generating a proper STOP condition. This should
* float SDA & SCK terminating the transfer. Subsequent transfers
* start with a proper START condition, and proceed normally.
*
* The HDMIPHY bus is an internal bus that always has exactly two
* devices, the host as Master and the HDMIPHY device as the slave.
* Skipping the STOP condition has been tested on this bus and works.
*/
if (i2c->quirks & QUIRK_HDMIPHY) {
/* Stop driving the I2C pins */
iicstat &= ~S3C2410_IICSTAT_TXRXEN;
} else {
/* stop the transfer */
iicstat &= ~S3C2410_IICSTAT_START;
}
writel(iicstat, i2c->regs + S3C2410_IICSTAT);
i2c->state = STATE_STOP;
s3c24xx_i2c_master_complete(i2c, ret); // 消息缓存处理,等待队列进程/线程唤醒
s3c24xx_i2c_disable_irq(i2c);
}
static inline void s3c24xx_i2c_master_complete(struct s3c24xx_i2c *i2c, int ret)
{
dev_dbg(i2c->dev, "master_complete %d\n", ret);
// 缓存处理
i2c->msg_ptr = 0;
i2c->msg = NULL;
i2c->msg_idx++;
i2c->msg_num = 0;
if (ret)
i2c->msg_idx = ret;
if (!(i2c->quirks & QUIRK_POLL))
wake_up(&i2c->wait); // 等待队列唤醒
}
(3)adapter算法:
static const struct i2c_algorithm s3c24xx_i2c_algorithm = {
.master_xfer = s3c24xx_i2c_xfer,
.functionality = s3c24xx_i2c_func,
};
static int s3c24xx_i2c_xfer(struct i2c_adapter *adap,
struct i2c_msg *msgs, int num)
{
struct s3c24xx_i2c *i2c = (struct s3c24xx_i2c *)adap->algo_data;
int retry;
int ret;
pm_runtime_get_sync(&adap->dev);
ret = clk_enable(i2c->clk);
if (ret)
return ret;
for (retry = 0; retry < adap->retries; retry++) { // 传输失败,重传
ret = s3c24xx_i2c_doxfer(i2c, msgs, num); // 实际的数据传输
if (ret != -EAGAIN) {
clk_disable(i2c->clk);
pm_runtime_put(&adap->dev);
return ret;
}
dev_dbg(i2c->dev, "Retrying transmission (%d)\n", retry);
udelay(100);
}
clk_disable(i2c->clk);
pm_runtime_put(&adap->dev);
return -EREMOTEIO;
}
static int s3c24xx_i2c_doxfer(struct s3c24xx_i2c *i2c,
struct i2c_msg *msgs, int num)
{
unsigned long timeout;
int ret;
if (i2c->suspended)
return -EIO;
ret = s3c24xx_i2c_set_master(i2c); // 设置本I2C控制器为主控设备
if (ret != 0) {
dev_err(i2c->dev, "cannot get bus (error %d)\n", ret);
ret = -EAGAIN;
goto out;
}
// 构造 i2c_msg 消息
i2c->msg = msgs;
i2c->msg_num = num;
i2c->msg_ptr = 0;
i2c->msg_idx = 0;
i2c->state = STATE_START;
s3c24xx_i2c_enable_irq(i2c); // 使能中断
s3c24xx_i2c_message_start(i2c, msgs); // 发送 START 消息(addr+R/W)
if (i2c->quirks & QUIRK_POLL) {
ret = i2c->msg_idx;
if (ret != num)
dev_dbg(i2c->dev, "incomplete xfer (%d)\n", ret);
goto out;
}
timeout = wait_event_timeout(i2c->wait, i2c->msg_num == 0, HZ * 5); // 当前进程/线程挂起在条件等待队列,要么超时唤醒,要么i2c->msg_num == 0 条件满足唤醒
ret = i2c->msg_idx;
/* having these next two as dev_err() makes life very
* noisy when doing an i2cdetect */
if (timeout == 0)
dev_dbg(i2c->dev, "timeout\n"); // 超时唤醒
else if (ret != num)
dev_dbg(i2c->dev, "incomplete xfer (%d)\n", ret); // 传输未完成
/* For QUIRK_HDMIPHY, bus is already disabled */
if (i2c->quirks & QUIRK_HDMIPHY)
goto out;
s3c24xx_i2c_wait_idle(i2c);
s3c24xx_i2c_disable_bus(i2c);
out:
i2c->state = STATE_IDLE;
return ret;
}
以上是I2C总线驱动框架部分,代码框架比较清晰。一般来说,I2C总线控制器的驱动代码kernel已经集成(除非新的i2c总线控制器kernel还未支持),需要用户编写的驱动程序一般是从设备驱动代码,即,i2c_driver代码。下一篇将会分析一个基于I2C的eeprom的驱动程序,来完善I2C的体系架构。