rk3399下iic驱动

先简要说明一下东西, 板子是rk3399的板子,跑的安卓系统,安卓7.1,由于板载一块音频编解码芯片,正好可以支持iic接口,于是就尝试读取他的Device ID 0x6281 寄存器地址0xff,内核文档下kernel\Documentation\iic目录下有iic相关的文档说明该内核版本下相对上一版本(iic的版本)改动的说明,该目录下upgrading-clients文件中有说明,

Upgrading I2C Drivers to the new 2.6 Driver Model
=================================================

Ben Dooks <[email protected]>

Introduction
------------

This guide outlines how to alter existing Linux 2.6 client drivers from
the old to the new new binding methods.
Example old-style driver
------------------------


struct example_state {
	struct i2c_client	client;
	....
};

static struct i2c_driver example_driver;

static unsigned short ignore[] = { I2C_CLIENT_END };
static unsigned short normal_addr[] = { OUR_ADDR, I2C_CLIENT_END };

I2C_CLIENT_INSMOD;

static int example_attach(struct i2c_adapter *adap, int addr, int kind)
{
	struct example_state *state;
	struct device *dev = &adap->dev;  /* to use for dev_ reports */
	int ret;

	state = kzalloc(sizeof(struct example_state), GFP_KERNEL);
	if (state == NULL) {
		dev_err(dev, "failed to create our state\n");
		return -ENOMEM;
	}

	example->client.addr    = addr;
	example->client.flags   = 0;
	example->client.adapter = adap;

	i2c_set_clientdata(&state->i2c_client, state);
	strlcpy(client->i2c_client.name, "example", I2C_NAME_SIZE);

	ret = i2c_attach_client(&state->i2c_client);
	if (ret < 0) {
		dev_err(dev, "failed to attach client\n");
		kfree(state);
		return ret;
	}

	dev = &state->i2c_client.dev;

	/* rest of the initialisation goes here. */

	dev_info(dev, "example client created\n");

	return 0;
}

static int example_detach(struct i2c_client *client)
{
	struct example_state *state = i2c_get_clientdata(client);

	i2c_detach_client(client);
	kfree(state);
	return 0;
}

static int example_attach_adapter(struct i2c_adapter *adap)
{
	return i2c_probe(adap, &addr_data, example_attach);
}

static struct i2c_driver example_driver = {
 	.driver		= {
		.owner		= THIS_MODULE,
		.name		= "example",
		.pm		= &example_pm_ops,
	},
	.attach_adapter = example_attach_adapter,
	.detach_client	= example_detach,
};

现在的iic

struct example_state {
	struct i2c_client	*client;
	....
};

static int example_probe(struct i2c_client *client,
		     	 const struct i2c_device_id *id)
{
	struct example_state *state;
	struct device *dev = &client->dev;

	state = kzalloc(sizeof(struct example_state), GFP_KERNEL);
	if (state == NULL) {
		dev_err(dev, "failed to create our state\n");
		return -ENOMEM;
	}

	state->client = client;
	i2c_set_clientdata(client, state);

	/* rest of the initialisation goes here. */

	dev_info(dev, "example client created\n");

	return 0;
}

static int example_remove(struct i2c_client *client)
{
	struct example_state *state = i2c_get_clientdata(client);

	kfree(state);
	return 0;
}

static struct i2c_device_id example_idtable[] = {
	{ "example", 0 },
	{ }
};

MODULE_DEVICE_TABLE(i2c, example_idtable);

static struct i2c_driver example_driver = {
 	.driver		= {
		.owner		= THIS_MODULE,
		.name		= "example",
		.pm		= &example_pm_ops,
	},
	.id_table	= example_idtable,
	.probe		= example_probe,
	.remove		= example_remove,
};

这就是现在内核版本的iic驱动,下面说说设备注册这一块的东西,之前旧版本的iic由驱动程序去探测每一个适配器(adapter)上面的iic设备,用驱动程序里面给定好的iic从机地址去找到这个设备挂接在哪个适配器(adapter)上面,这个环节在驱动程序里面体现为example_attach_adapter这个函数,下面是函数的实体

static int example_attach_adapter(struct i2c_adapter *adap)
{
	return i2c_probe(adap, &addr_data, example_attach);
}

里面有i2c_probe函数的作用就是使用adap这个适配器的传输函数,发出addr_data这个从机地址,如果发现这个设备存在,则会调用example_attach这个回调函数

static unsigned short ignore[]      = { I2C_CLIENT_END };
static unsigned short normal_addr[] = { 不包含地址的最后一位, I2C_CLIENT_END }; 
                                        

static unsigned short force_addr[] = {ANY_I2C_BUS, 不包含地址的最后一位, I2C_CLIENT_END};
static unsigned short * forces[] = {force_addr, NULL};
										
static struct i2c_client_address_data addr_data = {
	.normal_i2c	= normal_addr,  
	.probe		= ignore,
	.ignore		= ignore,
	//.forces     = forces,
};

让后在example_attach这个函数里面一般会构造一个i2c_client结构体,用于绑定设备和驱动

static int example_attach(struct i2c_adapter *adap, int addr, int kind)
{
	struct example_state *state;
	struct device *dev = &adap->dev;  /* to use for dev_ reports */
	int ret;

	state = kzalloc(sizeof(struct example_state), GFP_KERNEL);
	if (state == NULL) {
		dev_err(dev, "failed to create our state\n");
		return -ENOMEM;
	}

	example->client.addr    = addr;
	example->client.flags   = 0;
	example->client.adapter = adap;

	i2c_set_clientdata(&state->i2c_client, state);
	strlcpy(client->i2c_client.name, "example", I2C_NAME_SIZE);

	ret = i2c_attach_client(&state->i2c_client);
	if (ret < 0) {
		dev_err(dev, "failed to attach client\n");
		kfree(state);
		return ret;
	}

	dev = &state->i2c_client.dev;

	/* rest of the initialisation goes here. */

	dev_info(dev, "example client created\n");

	return 0;
}

后面的read 、write会用到这个结构体,以上就是旧版iic的驱动,新版的iic驱动有些东西已经不能用了,之前尝试使用旧版的驱动,有的结构体已经不存在了,于是没在深究,改用了新版的,现在就贴上读取alc5651这个编解码芯片的Device ID 的程序

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <asm/uaccess.h>


static int major;
static struct class *class;
static struct i2c_client *iic_client;

static int read_reg(const struct i2c_client *client, unsigned int *buf , unsigned char address)
{
	struct i2c_msg msg[2];
	int ret;
	unsigned char date1[2];

	msg[0].addr  = client->addr;  
	msg[0].buf   = &address;              
	msg[0].len   = 1;                     
	msg[0].flags = 0;                   

	msg[1].addr  = client->addr; 
	msg[1].buf   = date1;                 
	msg[1].len   = 2;                    
	msg[1].flags = I2C_M_RD;                   

	ret = i2c_transfer(client->adapter, msg, 2);
	if (ret > 0)
	{
		printk(KERN_INFO "date1 : %d date1 :%d\n",date1[0],date1[1]);
		*buf = (date1[0] << 8) | (date1[1]); 
		return 1;
	}
	else
		return -EIO;
}


static struct file_operations iic_fops = {
	.owner = THIS_MODULE,

};

static int iic_probe(struct i2c_client *client,const struct i2c_device_id *id)
{
	int ret;
	unsigned int data = 0;
	iic_client = client;
		
	printk(KERN_INFO "%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
	major = register_chrdev(0, "iic", &iic_fops);
	class = class_create(THIS_MODULE, "iic");
	device_create(class, NULL, MKDEV(major, 0), NULL, "iic"); 
	ret = read_reg(iic_client,&data,0xff);
	printk(KERN_INFO "Device ID 0x%x\n",data);
	return 0;
}

static int iic_remove(struct i2c_client *client)
{
	printk(KERN_INFO "%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
	device_destroy(class, MKDEV(major, 0));
	class_destroy(class);
	unregister_chrdev(major, "iic");
		
	return 0;
}

static const struct i2c_device_id iic_id_table[] = {
	{ "iic_test", 0 },
	{}
};


static struct i2c_driver iic_driver = {
	.driver	= {
		.name	= "rt5651_iic",
		.owner	= THIS_MODULE,
	},
	.probe		= iic_probe,
	.remove		= iic_remove,
	.id_table	= iic_id_table,
};

static int iic_drv_init(void)
{
	printk(KERN_INFO "%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
	i2c_add_driver(&iic_driver);
	
	return 0;
}

static void iic_drv_exit(void)
{
	i2c_del_driver(&iic_driver);
}


module_init(iic_drv_init);
module_exit(iic_drv_exit);
MODULE_LICENSE("GPL");


static struct i2c_driver iic_driver = {
	.driver	= {
		.name	= "rt5651_iic",
		.owner	= THIS_MODULE,
	},
	.probe		= iic_probe,
	.remove		= iic_remove,
	.id_table	= iic_id_table,
};


   这里的id_table表示该驱动支持的设备列表,如下

static const struct i2c_device_id iic_id_table[] = {
	{ "iic_test", 0 },
	{}
};

firefly的Wiki教程里边给的信息就是这些东西,另外加上一些设备树的信息,设备树这块我没加,在我的驱动里边没有设备树的内容,那么这儿就有个问题,我们知道iic驱动框架里边一般都有什么匹配机制,一般是总线-驱动-设备这样一种模型,以前的驱动会把所有的适配器上面的iic设备全部match一次,然后找到设备,这里有了驱动的信息,那么设备相关的信息在哪儿呢?如果这个地方你编译驱动然后加载驱动,这里根本就进不去probe函数,内核文档里面声明

Change the example_attach method to accept the new parameters
which include the i2c_client that it will be working with:

- static int example_attach(struct i2c_adapter *adap, int addr, int kind)
+ static int example_probe(struct i2c_client *client,
+			   const struct i2c_device_id *id)

Change the name of example_attach to example_probe to align it with the
i2c_driver entry names. The rest of the probe routine will now need to be
changed as the i2c_client has already been setup for use.

然后你可以看到目录下还有一个文档instantiating-devices,该文档的所有内容,介绍了怎么去初始化iic设备的信息,第一段话仔细阅读,我使用的第二种方式

How to instantiate I2C devices
==============================

Unlike PCI or USB devices, I2C devices are not enumerated at the hardware
level. Instead, the software must know which devices are connected on each
I2C bus segment, and what address these devices are using. For this
reason, the kernel code must instantiate I2C devices explicitly. There are
several ways to achieve this, depending on the context and requirements.


Method 1a: Declare the I2C devices by bus number
------------------------------------------------

This method is appropriate when the I2C bus is a system bus as is the case
for many embedded systems. On such systems, each I2C bus has a number
which is known in advance. It is thus possible to pre-declare the I2C
devices which live on this bus. This is done with an array of struct
i2c_board_info which is registered by calling i2c_register_board_info().

Example (from omap2 h4):

static struct i2c_board_info h4_i2c_board_info[] __initdata = {
	{
		I2C_BOARD_INFO("isp1301_omap", 0x2d),
		.irq		= OMAP_GPIO_IRQ(125),
	},
	{	/* EEPROM on mainboard */
		I2C_BOARD_INFO("24c01", 0x52),
		.platform_data	= &m24c01,
	},
	{	/* EEPROM on cpu card */
		I2C_BOARD_INFO("24c01", 0x57),
		.platform_data	= &m24c01,
	},
};

static void __init omap_h4_init(void)
{
	(...)
	i2c_register_board_info(1, h4_i2c_board_info,
			ARRAY_SIZE(h4_i2c_board_info));
	(...)
}

The above code declares 3 devices on I2C bus 1, including their respective
addresses and custom data needed by their drivers. When the I2C bus in
question is registered, the I2C devices will be instantiated automatically
by i2c-core.

The devices will be automatically unbound and destroyed when the I2C bus
they sit on goes away (if ever.)


Method 1b: Declare the I2C devices via devicetree
-------------------------------------------------

This method has the same implications as method 1a. The declaration of I2C
devices is here done via devicetree as subnodes of the master controller.

Example:

	i2c1: i2c@400a0000 {
		/* ... master properties skipped ... */
		clock-frequency = <100000>;

		flash@50 {
			compatible = "atmel,24c256";
			reg = <0x50>;
		};

		pca9532: gpio@60 {
			compatible = "nxp,pca9532";
			gpio-controller;
			#gpio-cells = <2>;
			reg = <0x60>;
		};
	};

Here, two devices are attached to the bus using a speed of 100kHz. For
additional properties which might be needed to set up the device, please refer
to its devicetree documentation in Documentation/devicetree/bindings/.


Method 1c: Declare the I2C devices via ACPI
-------------------------------------------

ACPI can also describe I2C devices. There is special documentation for this
which is currently located at Documentation/acpi/enumeration.txt.


Method 2: Instantiate the devices explicitly
--------------------------------------------

This method is appropriate when a larger device uses an I2C bus for
internal communication. A typical case is TV adapters. These can have a
tuner, a video decoder, an audio decoder, etc. usually connected to the
main chip by the means of an I2C bus. You won't know the number of the I2C
bus in advance, so the method 1 described above can't be used. Instead,
you can instantiate your I2C devices explicitly. This is done by filling
a struct i2c_board_info and calling i2c_new_device().

Example (from the sfe4001 network driver):

static struct i2c_board_info sfe4001_hwmon_info = {
	I2C_BOARD_INFO("max6647", 0x4e),
};

int sfe4001_init(struct efx_nic *efx)
{
	(...)
	efx->board_info.hwmon_client =
		i2c_new_device(&efx->i2c_adap, &sfe4001_hwmon_info);

	(...)
}

The above code instantiates 1 I2C device on the I2C bus which is on the
network adapter in question.

A variant of this is when you don't know for sure if an I2C device is
present or not (for example for an optional feature which is not present
on cheap variants of a board but you have no way to tell them apart), or
it may have different addresses from one board to the next (manufacturer
changing its design without notice). In this case, you can call
i2c_new_probed_device() instead of i2c_new_device().

Example (from the nxp OHCI driver):

static const unsigned short normal_i2c[] = { 0x2c, 0x2d, I2C_CLIENT_END };

static int usb_hcd_nxp_probe(struct platform_device *pdev)
{
	(...)
	struct i2c_adapter *i2c_adap;
	struct i2c_board_info i2c_info;

	(...)
	i2c_adap = i2c_get_adapter(2);
	memset(&i2c_info, 0, sizeof(struct i2c_board_info));
	strlcpy(i2c_info.type, "isp1301_nxp", I2C_NAME_SIZE);
	isp1301_i2c_client = i2c_new_probed_device(i2c_adap, &i2c_info,
						   normal_i2c, NULL);
	i2c_put_adapter(i2c_adap);
	(...)
}

The above code instantiates up to 1 I2C device on the I2C bus which is on
the OHCI adapter in question. It first tries at address 0x2c, if nothing
is found there it tries address 0x2d, and if still nothing is found, it
simply gives up.

The driver which instantiated the I2C device is responsible for destroying
it on cleanup. This is done by calling i2c_unregister_device() on the
pointer that was earlier returned by i2c_new_device() or
i2c_new_probed_device().


Method 3: Probe an I2C bus for certain devices
----------------------------------------------

Sometimes you do not have enough information about an I2C device, not even
to call i2c_new_probed_device(). The typical case is hardware monitoring
chips on PC mainboards. There are several dozen models, which can live
at 25 different addresses. Given the huge number of mainboards out there,
it is next to impossible to build an exhaustive list of the hardware
monitoring chips being used. Fortunately, most of these chips have
manufacturer and device ID registers, so they can be identified by
probing.

In that case, I2C devices are neither declared nor instantiated
explicitly. Instead, i2c-core will probe for such devices as soon as their
drivers are loaded, and if any is found, an I2C device will be
instantiated automatically. In order to prevent any misbehavior of this
mechanism, the following restrictions apply:
* The I2C device driver must implement the detect() method, which
  identifies a supported device by reading from arbitrary registers.
* Only buses which are likely to have a supported device and agree to be
  probed, will be probed. For example this avoids probing for hardware
  monitoring chips on a TV adapter.

Example:
See lm90_driver and lm90_detect() in drivers/hwmon/lm90.c

I2C devices instantiated as a result of such a successful probe will be
destroyed automatically when the driver which detected them is removed,
or when the underlying I2C bus is itself destroyed, whichever happens
first.

Those of you familiar with the i2c subsystem of 2.4 kernels and early 2.6
kernels will find out that this method 3 is essentially similar to what
was done there. Two significant differences are:
* Probing is only one way to instantiate I2C devices now, while it was the
  only way back then. Where possible, methods 1 and 2 should be preferred.
  Method 3 should only be used when there is no other way, as it can have
  undesirable side effects.
* I2C buses must now explicitly say which I2C driver classes can probe
  them (by the means of the class bitfield), while all I2C buses were
  probed by default back then. The default is an empty class which means
  that no probing happens. The purpose of the class bitfield is to limit
  the aforementioned undesirable side effects.

Once again, method 3 should be avoided wherever possible. Explicit device
instantiation (methods 1 and 2) is much preferred for it is safer and
faster.


Method 4: Instantiate from user-space
-------------------------------------

In general, the kernel should know which I2C devices are connected and
what addresses they live at. However, in certain cases, it does not, so a
sysfs interface was added to let the user provide the information. This
interface is made of 2 attribute files which are created in every I2C bus
directory: new_device and delete_device. Both files are write only and you
must write the right parameters to them in order to properly instantiate,
respectively delete, an I2C device.

File new_device takes 2 parameters: the name of the I2C device (a string)
and the address of the I2C device (a number, typically expressed in
hexadecimal starting with 0x, but can also be expressed in decimal.)

File delete_device takes a single parameter: the address of the I2C
device. As no two devices can live at the same address on a given I2C
segment, the address is sufficient to uniquely identify the device to be
deleted.

Example:
# echo eeprom 0x50 > /sys/bus/i2c/devices/i2c-3/new_device

While this interface should only be used when in-kernel device declaration
can't be done, there is a variety of cases where it can be helpful:
* The I2C driver usually detects devices (method 3 above) but the bus
  segment your device lives on doesn't have the proper class bit set and
  thus detection doesn't trigger.
* The I2C driver usually detects devices, but your device lives at an
  unexpected address.
* The I2C driver usually detects devices, but your device is not detected,
  either because the detection routine is too strict, or because your
  device is not officially supported yet but you know it is compatible.
* You are developing a driver on a test board, where you soldered the I2C
  device yourself.

This interface is a replacement for the force_* module parameters some I2C
drivers implement. Being implemented in i2c-core rather than in each
device driver individually, it is much more efficient, and also has the
advantage that you do not have to reload the driver to change a setting.
You can also instantiate the device before the driver is loaded or even
available, and you don't need to know what driver the device needs.

代码如下

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/regmap.h>
#include <linux/slab.h>


static struct i2c_board_info iic_info = {	
	I2C_BOARD_INFO("iic_test", 0x1a),//0x1a为设备地址,不包含最后一位读写位
};
static struct i2c_client *iic_client;

static int iic_dev_init(void)
{
	struct i2c_adapter *i2c_adap;
	i2c_adap = i2c_get_adapter(1);
	iic_client = i2c_new_device(i2c_adap, &iic_info); 
	i2c_put_adapter(i2c_adap);
	
	return 0;
}

static void iic_dev_exit(void)
{
	i2c_unregister_device(iic_client);
}


module_init(iic_dev_init);
module_exit(iic_dev_exit);
MODULE_LICENSE("GPL");


makefile文件:

#!/bin/bash

obj-m += iic.o 
#obj-m += iic_dts.o 
#obj-m += iic_test.o 
obj-m += iic_dev.o 

KDIR := /rk3399/source/g3399-v7-1-2-20180529/kernel


PWD ?= $(shell pwd)
all:
	make -C $(KDIR) M=$(PWD) modules

clean:
	rm -rf *.o *.ko

程序运行结果,为了增加可靠性,还是贴一下结果

g3399:/storage/0000-0000 $ su
g3399:/storage/0000-0000 # ls
LOST.DIR                  cmd_test iic_dev.ko test.ko      
System Volume Information iic.ko   iic_dts.ko test_char.ko 
g3399:/storage/0000-0000 # lsmod
Module                  Size  Used by
g3399:/storage/0000-0000 # insmod iic_dev.ko                                   
[   39.747705] type=1400 audit(1358499045.073:17): avc: denied { module_load } for pid=1520 comm="insmod" path="/storage/0000-0000/iic_dev.ko" dev="fuse" ino=284 scontext=u:r:su:s0 tcontext=u:object_r:fuse:s0 tclass=system permissive=1
[   39.770335] i2c i2c-1: 1 i2c clients have been registered at 0x1a
g3399:/storage/0000-0000 # insmod iic
iic.ko       iic_dev.ko   iic_dts.ko
g3399:/storage/0000-0000 # insmod iic.ko                                       
[   44.852023] /rk3399/source/g3399-v7-1-2-20180529/test_code/iic/iic.c iic_drv_init 92
[   44.858918] /rk3399/source/g3399-v7-1-2-20180529/test_code/iic/iic.c iic_probe 55
[   44.861947] datage1 e/0008 0-0d000 # 1 :129
[   44.862001] Device ID 0x6281

g3399:/storage/0000-0000 # 

对了,另外说明一个事情,alc5651的寄存器是16位的,所以,内核提供的api也能使用,但是读出来的数据是相反的,alc5651高位在前地位在后,所以我自己写了个传输函数,如下(不要在意细节)

static int read_reg(const struct i2c_client *client, unsigned int *buf , unsigned char address)
{
	struct i2c_msg msg[2];
	int ret;
	unsigned char date1[2];

	msg[0].addr  = client->addr;  
	msg[0].buf   = &address;              
	msg[0].len   = 1;                     
	msg[0].flags = 0;                   

	msg[1].addr  = client->addr; 
	msg[1].buf   = date1;                 
	msg[1].len   = 2;                    
	msg[1].flags = I2C_M_RD;                   

	ret = i2c_transfer(client->adapter, msg, 2);
	if (ret > 0)
	{
		printk(KERN_INFO "date1 : %d date1 :%d\n",date1[0],date1[1]);
		*buf = (date1[0] << 8) | (date1[1]); 
		return 1;
	}
	else
		return -EIO;
}

猜你喜欢

转载自blog.csdn.net/qq_33166886/article/details/83892644