---
title: "Linux 2.6下SPI设备模型--------基于AT91RM9200分析"
author: "mmdev"
date: "2008-08-28T16:20:00Z"
tags: []
slug: "linux-2-6-spi-at91rm9200"
draft: false
lastmod: "2008-08-28T16:20:00Z"
id: 990249
url: "https://mmdev.iteye.com/blog/990249"
---

Linux 2.6下SPI设备模型  
\--------基于AT91RM9200分析  
Atmel公司的ARM AT系列，其SPI驱动在kernel 2.6.23里已经包含。如果你打了at91-patch补丁的话，则在内核配置时要小心。在Device Drivers---- &gt; Character devices ---- &gt;取消选中SPI Driver(legacy) for at91rm9200 processor 。同时Device Drivers---- &gt;SPI Support ---- &gt; 选中SPI Support ,Atmel SPI Controler,同时选中 User mode SPI device driver support 。

SPI Driver(legacy) for at91rm9200 processor是保留选项，为了兼容以前版本。如果同时选中SPI Driver(legacy) for at91rm9200 processor，则在/sys里无法注册类spidev，也就无法将设备和驱动联系在一起。与现有atmel spi驱动发生冲突。

各选项对应的编译情况如下：

\[\*]SPI support ---- Config\_SPI 开启SPI功能

\[\*]Debug support for SPI drivers ---- config SPI\_DEBUG 开启SPI debug调试

----SPI Master Controller Drivers ---- depends on SPI\_MASTER 生成spi.o

&lt;\*&gt;Atmel SPI Controller ---- config SPI\_ATMEL 生成atmel\_spi.o

&lt;\*&gt;Bitbanging SPI master ---- config SPI\_BITBANG 生成spi\_bitbang.o

&lt;\*&gt;AT91RM9200 Bitbang SPI Master ---- CONFIG\_SPI\_AT91 spi\_at91\_bitbang.o

---- SPI Protocol Masters ---- depends on SPI\_MASTER

&lt; &gt;SPI EEPROMs from most vendors ---- config SPI\_AT25 生成at25.o

&lt;\*&gt;User mode SPI device driver support ---- config SPI\_SPIDEV 生成spidev.o

总线  
注册SPI总线

#spi.c

struct bus\_type spi\_bus\_type = {

.name = "spi", // spi总线名称

.dev\_attrs = spi\_dev\_attrs,

.match = spi\_match\_device,

.uevent = spi\_uevent,

.suspend = spi\_suspend,

.resume = spi\_resume,

};

spi总线将在sysfs/bus下显示。

其bus\_type 结构表示总线，它的定义在&lt;linux/device.h&gt;中，如下

struct bus\_type {

const char * name;

struct module * owner;

struct kset subsys;

struct kset drivers;

struct kset devices;

struct klist klist\_devices;

struct klist klist\_drivers;

struct blocking\_notifier\_head bus\_notifier;

struct bus\_attribute * bus\_attrs;

struct device\_attribute * dev\_attrs;

struct driver\_attribute * drv\_attrs;

struct bus\_attribute drivers\_autoprobe\_attr;

struct bus\_attribute drivers\_probe\_attr;

int (\*match)(struct device * dev, struct device\_driver * drv);

int (\*uevent)(struct device \*dev, char \*\*envp,

int num\_envp, char \*buffer, int buffer\_size);

int (\*probe)(struct device * dev);

int (\*remove)(struct device * dev);

void (\*shutdown)(struct device * dev);

int (\*suspend)(struct device * dev, pm\_message\_t state);

int (\*suspend\_late)(struct device * dev, pm\_message\_t state);

int (\*resume\_early)(struct device * dev);

int (\*resume)(struct device * dev);

unsigned int drivers\_autoprobe:1;

};

其中，当一个总线上的新设备或者新驱动被添加时，\*match 函数会被调用。如果指定的驱动程序能够处理指定的设备，该函数返回非零值。

对于spi总线，我们必须调用bus\_register(&spi\_bus\_type)进行注册。调用如果成功，SPI总线子系统将被添加到系统中，在sysfs的/sys/bus目录下可以看到。然后，我们就可以向这个总线添加设备了。代码见下：

static int \_\_init spi\_init(void)

{

int status;

buf = kmalloc(SPI\_BUFSIZ, GFP\_KERNEL);

if (!buf) {

status = -ENOMEM;

goto err0;

}

status = bus\_register(&spi\_bus\_type);

if (status &lt; 0)

goto err1;

status = class\_register(&spi\_master\_class);

if (status &lt; 0)

goto err2;

return 0;

err2:

bus\_unregister(&spi\_bus\_type);

err1:

kfree(buf);

buf = NULL;

err0:

return status;

}

设备  
spi设备的结构如下：

#spi.h

struct spi\_device {

struct device dev;

struct spi\_master \*master;

u32 max\_speed\_hz;

u8 chip\_select;

u8 mode;

#define SPI\_CPHA 0x01 /* clock phase \*/

#define SPI\_CPOL 0x02 /* clock polarity \*/

#define SPI\_MODE\_0 (0|0) /* (original MicroWire) \*/

#define SPI\_MODE\_1 (0|SPI\_CPHA)

#define SPI\_MODE\_2 (SPI\_CPOL|0)

#define SPI\_MODE\_3 (SPI\_CPOL|SPI\_CPHA)

#define SPI\_CS\_HIGH 0x04 /* chipselect active high? \*/

#define SPI\_LSB\_FIRST 0x08 /* per-word bits-on-wire \*/

#define SPI\_3WIRE 0x10 /* SI/SO signals shared \*/

#define SPI\_LOOP 0x20 /* loopback mode \*/

u8 bits\_per\_word;

int irq;

void \*controller\_state;

void \*controller\_data;

const char \*modalias;

/*

\* likely need more hooks for more protocol options affecting how

\* the controller talks to each chip, like:

\* - memory packing (12 bit samples into low bits, others zeroed)

\* - priority

\* - drop chipselect after each word

\* - chipselect delays

\* - ...

\*/

};

device结构中包含了设备模型核心用来模拟系统的信息。spidev还有设备的其他信息，因此spi设备结构包含在spidev\_data结构里。

struct spidev\_data {

struct device dev;

struct spi\_device \*spi;

struct list\_head device\_entry;

struct mutex buf\_lock;

unsigned users;

u8 \*buffer;

};

注册spi设备，

#spidev.c

static int spidev\_probe(struct spi\_device \*spi)

{

…

…

status = device\_register(&spidev-&gt;dev);

…

…

}

完成这个调用之后，我们就可以在sysfs中看到它了。

SPI设备驱动程序  
spi驱动程序结构如下：

struct spi\_driver {

int (\*probe)(struct spi\_device \*spi);

int (\*remove)(struct spi\_device \*spi);

void (\*shutdown)(struct spi\_device \*spi);

int (\*suspend)(struct spi\_device \*spi, pm\_message\_t mesg);

int (\*resume)(struct spi\_device \*spi);

struct device\_driver driver;

};

spi驱动程序注册函数如下：

int spi\_register\_driver(struct spi\_driver \*sdrv)

{

sdrv-&gt;driver.bus = &spi\_bus\_type;

if (sdrv-&gt;probe)

sdrv-&gt;driver.probe = spi\_drv\_probe;

if (sdrv-&gt;remove)

sdrv-&gt;driver.remove = spi\_drv\_remove;

if (sdrv-&gt;shutdown)

sdrv-&gt;driver.shutdown = spi\_drv\_shutdown;

return driver\_register(&sdrv-&gt;driver);

}

spidev的驱动名如下：

static struct spi\_driver spidev\_spi = {

.driver = {

.name = "spidev",

.owner = THIS\_MODULE,

},

.probe = spidev\_probe,

.remove = \_\_devexit\_p(spidev\_remove),

};

一个spi\_register\_driver调用将spidev添加到系统中。一旦初始化完成，就可以在sysfs中看到驱动程序信息。

类  
spidev类结构如下:

static struct class spidev\_class = {

.name = "spidev",

.owner = THIS\_MODULE,

.dev\_release = spidev\_classdev\_release,

};

AT91RM9200 SPIDEV初始化  
AT91RM9200的spi驱动，对于EK板，原先的SPI是用于dataflash的。其代码如下：

static struct spi\_board\_info ek\_spi\_devices\[] = {

{ /* DataFlash chip \*/

.modalias = "mtd\_dataflash",

.chip\_select = 0,

.max\_speed\_hz = 15 * 1000 * 1000,

}，

我们需要将.modalias改成我们自己的spi设备名

在spi设备初始化代码中，class\_register(&spidev\_class)注册类，spi\_register\_driver(&spidev\_spi)注册spidev驱动。

#drivers/spi/spidev.c

static int \_\_init spidev\_init(void)

{

int status;

/* Claim our 256 reserved device numbers. Then register a class

\* that will key udev/mdev to add/remove /dev nodes. Last, register

\* the driver which manages those device numbers.

\*/

BUILD\_BUG\_ON(N\_SPI\_MINORS &gt; 256);

status = register\_chrdev(SPIDEV\_MAJOR, "spi", &spidev\_fops);

if (status &lt; 0)

return status;

status = class\_register(&spidev\_class);

if (status &lt; 0) {

unregister\_chrdev(SPIDEV\_MAJOR, spidev\_spi.driver.name);

return status;

}

status = spi\_register\_driver(&spidev\_spi);

if (status &lt; 0) {

class\_unregister(&spidev\_class);

unregister\_chrdev(SPIDEV\_MAJOR, spidev\_spi.driver.name);

}

return status;

}

挂载/sys

mount –t sysfs sysfs /sys

可以看到有/sys/class/spidev/spidev0.0，表明设备已经挂载在总线上了，同时与驱动联系起来。

使用mdev –s，可以在/dev下看到spidev0.0这个设备了。

自此，spi设备驱动就可以工作了。

测试程序：  
#include &lt;stdio.h&gt;

#include &lt;unistd.h&gt;

#include &lt;stdlib.h&gt;

#include &lt;fcntl.h&gt;

#include &lt;string.h&gt;

#include &lt;sys/ioctl.h&gt;

#include &lt;sys/types.h&gt;

#include &lt;sys/stat.h&gt;

#include &lt;linux/types.h&gt;

#include &lt;linux/spi/spidev.h&gt;

static int verbose;

static void do\_read(int fd, int len)

{

unsigned char buf\[32], \*bp;

int status;

/* read at least 2 bytes, no more than 32 \*/

if (len &lt; 2)

len = 2;

else if (len &gt; sizeof(buf))

len = sizeof(buf);

memset(buf, 0, sizeof buf);

status = read(fd, buf, len);

if (status &lt; 0) {

perror("read");

return;

}

if (status != len) {

fprintf(stderr, "short read\\n");

return;

}

printf("read(%2d, %2d): %02x %02x,", len, status,

buf\[0], buf\[1]);

status -= 2;

bp = buf + 2;

while (status-- &gt; 0)

printf(" %02x", \*bp++);

printf("\\n");

}

static void do\_msg(int fd, int len)

{

struct spi\_ioc\_transfer xfer\[2];

unsigned char buf\[32], \*bp;

int status;

memset(xfer, 0, sizeof xfer);

memset(buf, 0, sizeof buf);

if (len &gt; sizeof buf)

len = sizeof buf;

buf\[0] = 0xaa;

xfer\[0].tx\_buf = (\_\_u64) buf;

xfer\[0].len = 1;

xfer\[1].rx\_buf = (\_\_u64) buf;

xfer\[1].len = len;

status = ioctl(fd, SPI\_IOC\_MESSAGE(2), xfer);

if (status &lt; 0) {

perror("SPI\_IOC\_MESSAGE");

return;

}

printf("response(%2d, %2d): ", len, status);

for (bp = buf; len; len--)

printf(" %02x", \*bp++);

printf("\\n");

}

static void dumpstat(const char \*name, int fd)

{

\_\_u8 mode, lsb, bits;

\_\_u32 speed;

if (ioctl(fd, SPI\_IOC\_RD\_MODE, &mode) &lt; 0) {

perror("SPI rd\_mode");

return;

}

if (ioctl(fd, SPI\_IOC\_RD\_LSB\_FIRST, &lsb) &lt; 0) {

perror("SPI rd\_lsb\_fist");

return;

}

if (ioctl(fd, SPI\_IOC\_RD\_BITS\_PER\_WORD, &bits) &lt; 0) {

perror("SPI bits\_per\_word");

return;

}

if (ioctl(fd, SPI\_IOC\_RD\_MAX\_SPEED\_HZ, &speed) &lt; 0) {

perror("SPI max\_speed\_hz");

return;

}

printf("%s: spi mode %d, %d bits %sper word, %d Hz max\\n",

name, mode, bits, lsb ? "(lsb first) " : "", speed);

}

int main(int argc, char \*\*argv)

{

int c;

int readcount = 0;

int msglen = 0;

int fd;

const char \*name;

while ((c = getopt(argc, argv, "hm:r:v")) != EOF) {

switch (c) {

case 'm':

msglen = atoi(optarg);

if (msglen &lt; 0)

goto usage;

continue;

case 'r':

readcount = atoi(optarg);

if (readcount &lt; 0)

goto usage;

continue;

case 'v':

verbose++;

continue;

case 'h':

case '?':

usage:

fprintf(stderr,

"usage: %s \[-h] \[-m N] \[-r N] /dev/spidevB.D\\n",

argv\[0]);

return 1;

}

}

if ((optind + 1) != argc)

goto usage;

name = argv\[optind];

fd = open(name, O\_RDWR);

if (fd &lt; 0) {

perror("open");

return 1;

}

dumpstat(name, fd);

if (msglen)

do\_msg(fd, msglen);

if (readcount)

do\_read(fd, readcount);

close(fd);

return 0;

}

备注：

1\. 如果要设置模式，速率等，则可仿照以下语句：

speed =10\*1000\*1000; //10MHz

if (ioctl(fd, SPI\_IOC\_WR\_MAX\_SPEED\_HZ, &speed) &lt; 0) {

perror("SPI max\_speed\_hz");

return;

}

2\. 默认spi\_io\_transfer时，每个字节之间有延时。在atmel\_spi\_setup.c文件里去掉该延时语句：

/* TODO: DLYBS and DLYBCT \*/

//csr |= SPI\_BF(DLYBS, 10);

//csr |= SPI\_BF(DLYBCT, 10);

这样就可以达到无间隙快速传输批量数据。

3\. 标准read(),write()两个函数仅适用于半双工传输，。在传输之间不激活片选。而SPI\_IOC\_MESSAGE(N)则是全双工传输，并且片选始终激活。

4\. SPI\_IOC\_MESSAGE传输长度有限制，默认是一页的长度，但是可以更改。

spi\_ioc\_transfer结构的spi长度 是字节长度，16位传输的时候要注意。