I2C驅動程序設計(4)—I2C自編設備驅動設計

在分析驅動程序之前我們再來分析一下I2C子系統的模型。I2C的設備驅動中有2中方式,一種是通過通用驅動來編寫用戶驅動。另一種就是直接在I2C子系統中添加一個I2C的設備驅動,比如說針對AT24C02的驅動程序,接下來我們來學習怎麼編寫一個I2C設備驅動。

1.驅動程序分析

  • 我們先在Linux內核代碼中打開一個叫做At24.c的文件,只要是屬於AT24開頭的設備都可以使用這個驅動。我們接下來分析這個驅動。
/*-------------------------------------------------------------------------*/
 
 
static struct i2c_driver at24_driver = {
.driver = {
.name = "at24",
.owner = THIS_MODULE,
},
.probe = at24_probe,
.remove = __devexit_p(at24_remove),
.id_table = at24_ids,
};
 
 
static int __init at24_init(void)
{
io_limit = rounddown_pow_of_two(io_limit);
return i2c_add_driver(&at24_driver);
}
module_init(at24_init);
 
 
static void __exit at24_exit(void)
{
i2c_del_driver(&at24_driver);
}
module_exit(at24_exit);
  • 初始化函數中主要是註冊一個I2C設備驅動。我們分析(&at24_driver)裏面的成員,比較重要的成員有2個,一個是probe函數,另一個是at24_ids,這裏面存放支持AT24設備的ID列表,比如說AT24C02,AT24C08等等,有興趣的可以看一下這個表。
  • 我們接下來分析probe函數。這個函數很長,如果要做到讀懂每一行代碼肯定是非常難的,我們最基本的應該掌握這個函數大概的流程和中心。比如說註冊某個東西,創建某個東西,初始化某個東西。
/*-------------------------------------------------------------------------*/
 
static int at24_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
	struct at24_platform_data chip;
	bool writable;
	bool use_smbus = false;
	struct at24_data *at24;
	int err;
	unsigned i, num_addresses;
	kernel_ulong_t magic;
 
	if (client->dev.platform_data) {
		chip = *(struct at24_platform_data *)client->dev.platform_data;
	} else {
		if (!id->driver_data) {
			err = -ENODEV;
			goto err_out;
		}
		magic = id->driver_data;
		chip.byte_len = BIT(magic & AT24_BITMASK(AT24_SIZE_BYTELEN));
		magic >>= AT24_SIZE_BYTELEN;
		chip.flags = magic & AT24_BITMASK(AT24_SIZE_FLAGS);
		/*
		 * This is slow, but we can't know all eeproms, so we better
		 * play safe. Specifying custom eeprom-types via platform_data
		 * is recommended anyhow.
		 */
		chip.page_size = 1;
 
		chip.setup = NULL;
		chip.context = NULL;
	}
 
	if (!is_power_of_2(chip.byte_len))
		dev_warn(&client->dev,
			"byte_len looks suspicious (no power of 2)!\n");
	if (!is_power_of_2(chip.page_size))
		dev_warn(&client->dev,
			"page_size looks suspicious (no power of 2)!\n");
 
	/* Use I2C operations unless we're stuck with SMBus extensions. */
	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
		if (chip.flags & AT24_FLAG_ADDR16) {
			err = -EPFNOSUPPORT;
			goto err_out;
		}
		if (!i2c_check_functionality(client->adapter,
				I2C_FUNC_SMBUS_READ_I2C_BLOCK)) {
			err = -EPFNOSUPPORT;
			goto err_out;
		}
		use_smbus = true;
	}
 
	if (chip.flags & AT24_FLAG_TAKE8ADDR)
		num_addresses = 8;
	else
		num_addresses =	DIV_ROUND_UP(chip.byte_len,
			(chip.flags & AT24_FLAG_ADDR16) ? 65536 : 256);
 
	at24 = kzalloc(sizeof(struct at24_data) +
		num_addresses * sizeof(struct i2c_client *), GFP_KERNEL);
	if (!at24) {
		err = -ENOMEM;
		goto err_out;
	}
 
	mutex_init(&at24->lock);
	at24->use_smbus = use_smbus;
	at24->chip = chip;
	at24->num_addresses = num_addresses;
 
	/*
	 * Export the EEPROM bytes through sysfs, since that's convenient.
	 * By default, only root should see the data (maybe passwords etc)
	 */
	at24->bin.attr.name = "eeprom";
	at24->bin.attr.mode = chip.flags & AT24_FLAG_IRUGO ? S_IRUGO : S_IRUSR;
	at24->bin.read = at24_bin_read;
	at24->bin.size = chip.byte_len;
 
	at24->macc.read = at24_macc_read;
 
	writable = !(chip.flags & AT24_FLAG_READONLY);
	if (writable) {
		if (!use_smbus || i2c_check_functionality(client->adapter,
				I2C_FUNC_SMBUS_WRITE_I2C_BLOCK)) {
 
			unsigned write_max = chip.page_size;
 
			at24->macc.write = at24_macc_write;
 
			at24->bin.write = at24_bin_write;
			at24->bin.attr.mode |= S_IWUSR;
 
			if (write_max > io_limit)
				write_max = io_limit;
			if (use_smbus && write_max > I2C_SMBUS_BLOCK_MAX)
				write_max = I2C_SMBUS_BLOCK_MAX;
			at24->write_max = write_max;
 
			/* buffer (data + address at the beginning) */
			at24->writebuf = kmalloc(write_max + 2, GFP_KERNEL);
			if (!at24->writebuf) {
				err = -ENOMEM;
				goto err_struct;
			}
		} else {
			dev_warn(&client->dev,
				"cannot write due to controller restrictions.");
		}
	}
 
	at24->client[0] = client;
 
	/* use dummy devices for multiple-address chips */
	for (i = 1; i < num_addresses; i++) {
		at24->client[i] = i2c_new_dummy(client->adapter,
					client->addr + i);
		if (!at24->client[i]) {
			dev_err(&client->dev, "address 0x%02x unavailable\n",
					client->addr + i);
			err = -EADDRINUSE;
			goto err_clients;
		}
	}
 
	err = sysfs_create_bin_file(&client->dev.kobj, &at24->bin);
	if (err)
		goto err_clients;
 
	i2c_set_clientdata(client, at24);
 
	dev_info(&client->dev, "%zu byte %s EEPROM %s\n",
		at24->bin.size, client->name,
		writable ? "(writable)" : "(read-only)");
	dev_dbg(&client->dev,
		"page_size %d, num_addresses %d, write_max %d%s\n",
		chip.page_size, num_addresses,
		at24->write_max,
		use_smbus ? ", use_smbus" : "");
 
	/* export data to kernel code */
	if (chip.setup)
		chip.setup(&at24->macc, chip.context);
 
	return 0;
 
err_clients:
	for (i = 1; i < num_addresses; i++)
		if (at24->client[i])
			i2c_unregister_device(at24->client[i]);
 
	kfree(at24->writebuf);
err_struct:
	kfree(at24);
err_out:
	dev_dbg(&client->dev, "probe error %d\n", err);
	return err;
}
  • 這裏好像沒有註冊什麼東西,那麼有沒有創建某個東西呢?可以看到他在sys下面創建了一個文件err = sysfs_create_bin_file(&client->dev.kobj, &at24->bin);這個文件包含什麼東西呢?查看之前對於at24->bin的初始化,可以知道,這個文件叫做eeprom,同時可以猜測,當我們使用這個設備文件來讀寫eeprom時需要使用到文件裏面實現讀寫操作的函數。
  • 查看代碼我們也可以知道這2個函數分別是at24_bin_readat24_bin_write,我們接下來就分析這2個函數。
 
 
 
/*
 * Note that if the hardware write-protect pin is pulled high, the whole
 * chip is normally write protected. But there are plenty of product
 * variants here, including OTP fuses and partial chip protect.
 *
 * We only use page mode writes; the alternative is sloooow. This routine
 * writes at most one page.
 */
static ssize_t at24_eeprom_write(struct at24_data *at24, const char *buf,
		unsigned offset, size_t count)
{
	struct i2c_client *client;
	struct i2c_msg msg;
	ssize_t status;
	unsigned long timeout, write_time;
	unsigned next_page;
 
 
	/* Get corresponding I2C address and adjust offset */
	client = at24_translate_offset(at24, &offset);
 
 
	/* write_max is at most a page */
	if (count > at24->write_max)
		count = at24->write_max;
 
 
	/* Never roll over backwards, to the start of this page */
	next_page = roundup(offset + 1, at24->chip.page_size);
	if (offset + count > next_page)
		count = next_page - offset;
 
 
	/* If we'll use I2C calls for I/O, set up the message */
	if (!at24->use_smbus) {
		int i = 0;
 
 
		msg.addr = client->addr;
		msg.flags = 0;
 
 
		/* msg.buf is u8 and casts will mask the values */
		msg.buf = at24->writebuf;
		if (at24->chip.flags & AT24_FLAG_ADDR16)
			msg.buf[i++] = offset >> 8;
 
 
		msg.buf[i++] = offset;
		memcpy(&msg.buf[i], buf, count);
		msg.len = i + count;
	}
 
 
	/*
	 * Writes fail if the previous one didn't complete yet. We may
	 * loop a few times until this one succeeds, waiting at least
	 * long enough for one entire page write to work.
	 */
	timeout = jiffies + msecs_to_jiffies(write_timeout);
	do {
		write_time = jiffies;
		if (at24->use_smbus) {
			status = i2c_smbus_write_i2c_block_data(client,
					offset, count, buf);
			if (status == 0)
				status = count;
		} else {
			status = i2c_transfer(client->adapter, &msg, 1);
			if (status == 1)
				status = count;
		}
		dev_dbg(&client->dev, "write %zu@%d --> %zd (%ld)\n",
				count, offset, status, jiffies);
 
 
		if (status == count)
			return count;
 
 
		/* REVISIT: at HZ=100, this is sloooow */
		msleep(1);
	} while (time_before(write_time, timeout));
 
 
	return -ETIMEDOUT;
}
		unsigned offset, size_t count)
{
	struct i2c_client *client;
	struct i2c_msg msg;
	ssize_t status;
	unsigned long timeout, write_time;
	unsigned next_page;


	/* Get corresponding I2C address and adjust offset */
	client = at24_translate_offset(at24, &offset);


	/* write_max is at most a page */
	if (count > at24->write_max)
		count = at24->write_max;


	/* Never roll over backwards, to the start of this page */
	next_page = roundup(offset + 1, at24->chip.page_size);
	if (offset + count > next_page)
		count = next_page - offset;


	/* If we'll use I2C calls for I/O, set up the message */
	if (!at24->use_smbus) {
		int i = 0;


		msg.addr = client->addr;
		msg.flags = 0;


		/* msg.buf is u8 and casts will mask the values */
		msg.buf = at24->writebuf;
		if (at24->chip.flags & AT24_FLAG_ADDR16)
			msg.buf[i++] = offset >> 8;


		msg.buf[i++] = offset;
		memcpy(&msg.buf[i], buf, count);
		msg.len = i + count;
	}


	/*
	 * Writes fail if the previous one didn't complete yet. We may
	 * loop a few times until this one succeeds, waiting at least
	 * long enough for one entire page write to work.
	 */
	timeout = jiffies + msecs_to_jiffies(write_timeout);
	do {
		write_time = jiffies;
		if (at24->use_smbus) {
			status = i2c_smbus_write_i2c_block_data(client,
					offset, count, buf);
			if (status == 0)
				status = count;
		} else {
			status = i2c_transfer(client->adapter, &msg, 1);
			if (status == 1)
				status = count;
		}
		dev_dbg(&client->dev, "write %zu@%d --> %zd (%ld)\n",
				count, offset, status, jiffies);


		if (status == count)
			return count;


		/* REVISIT: at HZ=100, this is sloooow */
		msleep(1);
	} while (time_before(write_time, timeout));


	return -ETIMEDOUT;
}
  • 簡要分析一下可以知道,它主要做了2件事,一個是構造msg,另一件事是使用i2c_transfer函數來傳輸數據,上一節的分析可以知道,i2c設備驅動如果要讀寫數據,都是通過i2c_transfer把它交給i2c總線驅動或者說是i2c控制器驅動。對應msg的構造我們在上一節課已經講的非常清楚了,對於i2c_transfer函數,它是屬於i2c-core裏面的函數,查看他的代碼可以知道,他並沒有做什麼實質性的操作,而是調用i2c適配器裏面的讀寫方法來實現數據的傳輸 ret = adap->algo->master_xfer(adap, msgs, num);
  • 接下來分析讀函數,讀函數和寫函數的調用過程也類似,依次調用at24_bin_read->at24_read->at24_eeprom_read來實現eeprom的讀數據,at24_eeprom_read的實現過程也主要分爲msg的構造和數據的傳輸,msg的構造和上一節課講的消息構造差不多,也是需要分爲2個消息,一個是寫消息,然後是讀消息的構造。
if (at24->chip.flags & AT24_FLAG_ADDR16)
			msgbuf[i++] = offset >> 8;
		msgbuf[i++] = offset;

		msg[0].addr = client->addr;
		msg[0].buf = msgbuf;
		msg[0].len = i;

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

2.驅動程序移植

  • 我們現在來對Linux的i2c驅動代碼進行修改和移植。首先是註冊i2c設備,爲什麼要註冊i2c設備呢?我們知道當Linux系統檢測到符合id_table的設備時將會調用probe函數,因此,我們不僅需要註冊i2c驅動,還需要註冊i2c設備。怎麼樣才能註冊一個i2c設備呢?找到Mach-mini2440.c文件,依次添加以下代碼:
// add by david
static struct at24_platform_data at24c08 = {
	.byte_len	= SZ_8K / 8,
	.page_size	= 16,
	.flags = 0,
};

// add by david
static struct i2c_board_info __initdata  mini2440_i2c_devices[] = {
	{
		I2C_BOARD_INFO("24c08", 0x50),
		.platform_data = &at24c08,
	},
};
  • 由於可能有多個i2c設備,所以把它們保存在一個數組裏面。
  • 然後使用i2c_register_board_info函數把我們定義的i2c設備數組註冊到Linux內核中:
i2c_register_board_info(0, mini2440_i2c_devices, ARRAY_SIZE(mini2440_i2c_devices));  // add
  • 添加頭文件
// add by david
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
  • 這樣就算是移植好了i2c的驅動。

3.內核中啓動對eeprom的支持

  • #make menuconfig
  • 選擇device driver,選中並進入Misc devices,然後進入 EEPROM Support,選擇裏面全部的配置,這樣就把eeprom的驅動配置好了,然後當註冊i2c設備的時候,就會調用probe函數,從而生成/sys/bus/i2c/devices/0-0050/eeprom文件
  • 編譯內核:#make uImage ARCH=arm CROSS_COMPILE=arm-linux-
  • 下載到開發板

4.驅動程序測試

  • ​​​​測試程序我們分爲這幾步:
    • 1、打開文件
    • 2、寫入數據s  
    • 3、讀出數據
    • 4、打印
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
	int fd, i;
	char write_data[256];
	char read_data[256];
	
	// 1.打開at24c08對應的sys文件
	fd = open("/sys/bus/i2c/devices/0-0050/eeprom", O_RDWR);
	if (fd < 0) 
	{
        printf("error\n");
        return -1;
    }
    
	// 2.寫入數據
	for (i = 0; i < 256; i++)
		write_data[i] = i;
		
	lseek(fd, 0, SEEK_SET);   // 重新定位讀寫指針
	write(fd, write_data, 256);
	
	// 3.讀出數據
	lseek(fd, 0, SEEK_SET);   // 重新定位讀寫指針
	lseek(fd, 0, SEEK_SET);  
	read(fd, read_data, 256);
	
	// 4.打印對比
	for (i = 0; i < 256; i++)
	{
		if (i % 16 == 0)
			printf("\n");
		printf("%3d ", read_data[i]);		
	}
	printf("\n");
	
	//關閉文件
    close(fd);
    
    return 0;
}
  • 編譯這個程序:
    • #arm-linux-gcc -stati app.c -o app
  • 然後把它拷貝到開發板上運行:./i2c-app

  • 打印出的信息和寫入eeprom數據的應該是一樣的。
發佈了222 篇原創文章 · 獲贊 226 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章