---
title: Linux I2C子系统分析:1-整体框架介绍
EntryName: linux-subsystem-i2c-0-about
date: 2020-10-13 04:19:26
categories:
tags:
- i2c
- linux
- kernel
---

章节描述:

系列:

内核版本:v4.14

构成

在Linux的I2C架构如图:

内核空间部分可以分为: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中,随着内核版本的不同有差异,但差异不大。

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 内核:I2C子系统分析(0)整体框架介绍的更多相关文章

  1. 嵌入式Linux内核I2C子系统详解

    1.1 I2C总线知识 1.1.1  I2C总线物理拓扑结构     I2C总线在物理连接上非常简单,分别由SDA(串行数据线)和SCL(串行时钟线)及上拉电阻组成.通信原理是通过对SCL和SDA线高 ...

  2. linux内核I2C子系统学习(三)

    写设备驱动: 四部曲: 构建i2c_driver 注册i2c_driver 构建i2c_client ( 第一种方法:注册字符设备驱动.第二种方法:通过板文件的i2c_board_info填充,然后注 ...

  3. linux内核输入子系统分析

    1.为何引入input system? 以前我们写一些输入设备(键盘.鼠标等)的驱动都是采用字符设备.混杂设备处理的.问题由此而来,Linux开源社区的大神们看到了这大量输入设备如此分散不堪,有木有可 ...

  4. Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3.0 ARMv7)

    http://blog.chinaunix.net/uid-20543672-id-3157283.html Linux内核源码分析--内核启动之(3)Image内核启动(C语言部分)(Linux-3 ...

  5. Linux内核源码分析--内核启动之(6)Image内核启动(do_basic_setup函数)(Linux-3.0 ARMv7)【转】

    原文地址:Linux内核源码分析--内核启动之(6)Image内核启动(do_basic_setup函数)(Linux-3.0 ARMv7) 作者:tekkamanninja 转自:http://bl ...

  6. Linux内核源码分析--内核启动之(4)Image内核启动(setup_arch函数)(Linux-3.0 ARMv7)【转】

    原文地址:Linux内核源码分析--内核启动之(4)Image内核启动(setup_arch函数)(Linux-3.0 ARMv7) 作者:tekkamanninja 转自:http://blog.c ...

  7. Linux内核源代码情景分析系列

    http://blog.sina.com.cn/s/blog_6b94d5680101vfqv.html Linux内核源代码情景分析---第五章 文件系统  5.1 概述 构成一个操作系统最重要的就 ...

  8. Linux 内核无线子系统

    Linux 内核无线子系统 浅谈 Linux 内核无线子系统 Table of Contents 1. 全局概览 2. 模块间接口 3. 数据路径与管理路径 4. 数据包是如何被发送? 5. 谈谈管理 ...

  9. Linux内核源码分析方法_转

    Linux内核源码分析方法 转自:http://www.cnblogs.com/fanzhidongyzby/archive/2013/03/20/2970624.html 一.内核源码之我见 Lin ...

  10. 2019-2020-1 20199329《Linux内核原理与分析》第三周作业

    <Linux内核原理与分析>第三周作业 一.上周问题总结: 第二周头脑风暴完成较慢 虚拟机libc配置错误 书本知识使用不够熟练 二.本周学习内容: 1.实验楼环境虚拟一个x86的CPU硬 ...

随机推荐

  1. 一键自动化博客发布工具,chrome和firfox详细配置

    blog-auto-publishing-tools博客自动发布工具现在已经可以同时支持chrome和firefox了. 很多小伙伴可能对于如何进行配置和启动不是很了解,今天带给大家一个详细的保姆教程 ...

  2. 【Python基础】两个参数的for循环步长写法

    一个参数for循环步长写法 >>> for i in range(1,10000,1000):print(i) ... 1 1001 2001 3001 4001 5001 6001 ...

  3. 启动docker某个image(镜像)的已经关闭的container(容器)

    1.创建一个后台运行 ubuntu 容器 root@haima-PC:/home/haima/Desktop# docker run -d --name ubuntu-lnmp ubuntu bf24 ...

  4. ansible系列(20)--ansible的变量详解

    目录 1. Ansible Variables 1.1 变量定义的方式 1.2 在playbook中定义变量 1.2.1 使用vars方式定义变量 1.2.2 使用vars_file方式定义变量 1. ...

  5. 高性能远程控制软件,完美替代Anydesk

    Anydesk是一款来自德国的远程软件,据悉是Teamviewer团队成员出来独立门户做的.Anydesk给人一种小而美的感觉,软件体积小,性能高,被视为Teamviewer的替代产品.现在,AnyD ...

  6. java 反射——任意类型数组扩容

    //java object[]无法转换为原对象类型,可以使用反射来做. //这里的参数不是传object[] 而是传object. public Object GoodArrayGrow(Object ...

  7. SQL必知必会(第5版) 读书笔记

    适用范围 本书涵盖的DBMS一般来说,本书中所讲授的SQL可以应用到任何数据库管理系统(DBMS).但是,各种SQL实现不尽相同,本书介绍的SQL主要适用于以下系统(需要时会给出特殊说明和注释): ❑ ...

  8. Vulkan Support Check and Dynamic Loader C++ code sample

    很多时候不想静态依赖VulkanSDK所提供的静态库,因为会遇到一些过早的电脑不支持vulkan, 那么就需要使用动态加载vulkan-1.dll(for Windows)或libMoltenVK.d ...

  9. kettle从入门到精通 第四十七课 ETL之kettle mongo output 写入

    1.上一节课我们学习了mongo input读取步骤,本节课我们一起学习下mongo out 写入步骤,该步骤可以将数据写入到mongo中,如下图所示. 2. 配置mongo连接,有两种方式,如截图所 ...

  10. P2868

    Sightseeing Cows G 我们先考虑如何求平均乐趣值. 1.总乐趣为 \(\sum^n_{i = 1}f_i \times s_i\),其中 \(f_i\) 为第 \(i\) 个点的乐趣值 ...