下面来看一下Linux中的SPI驱动。在Linux设备驱动框架的设计中,有一个重要的主机、外设驱动框架分离的思想,如下图。
外设a,b,c的驱动与主机控制器A,B,C的驱动不相关,主机控制器驱动不关心外设,而外设驱动也不关心主机,外设只是访问核心层的通用的API进行数据的传输,主机和外设之间可以进行任意的组合。如果我们不进行如图的主机和外设分离,外设a,b,c和主机A,B,C进行组合的时候,需要9种不同的驱动。设想一共有m个主机控制器,n个外设,分离的结构是需要m+n个驱动,不分离则需要m*n个驱动。
下面介绍spi子系统的数据结构:
在Linux中,使用spi_master结构来描述一个SPI主机控制器的驱动。
- struct spi_master {
- struct device dev
- s16 bus_num;/*总线编号,从0开始*/
- u16 num_chipselect; //*支持的片选的数量,从设备的片选号不能大于这个数量*/
- u16 dma_alignment
- int (*setup)(struct spi_device *spi);/*改变spi_device的特性如:传输模式,字长,时钟频率*/
- int (*transfer)(struct spi_device *spi,struct spi_message *mesg); );/*添加消息到队列的方法,这个函数不可睡眠,他的任务是安排发生的传送并且调用注册的回调函数complete()*/
- void (*cleanup)(struct spi_device *spi);
- };
分配,注册和注销的SPI主机的API由SPI核心提供:
- struct spi_master *spi_alloc_master(struct device *host, unsigned size);
- int spi_register_master(struct spi_master *master);
- void spi_unregister_master(struct spi_master *master);
在Linux中用spi_driver来描述一个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_driver结构体和platform_driver结构体有极大的相似性,都有probe(),remove(),suspend(),resume()这样的接口。
Linux用spi_device来描述一个SPI外设设备。
- struct spi_device {
- struct device dev;
- struct spi_master *master;
- max_speed_hz;
- 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;
- char modalias[32];
- };
如下图,看这三个结构的关系,这里spi_device与spi_master是同一个父设备(挂接在同一口上),这是在spi_new_device函数中设定的,一般这个设备是一个物理设备。
这里的spi_master_class,spi_bus_type又是什么呢,看下边两个结构体:
- struct bus_type spi_bus_type = {
- .name ="spi",
- .dev_attrs = spi_dev_attrs,
- .match = spi_match_device,
- .uevent = spi_uevent,
- .suspend = spi_suspend,
- .resume = spi_resume,
- };
- static struct class spi_master_class = {
- .name ="spi_master",
- .owner = THIS_MODULE,
- .dev_release = spi_master_release,
- };
spi_bus_type对应spi中的spi bus总线,spidev的类定义如下:
- static struct class *spidev_class;
创建这个类的主要目的是使mdev/udev能在/dev下创建设备节点/dev/spiB.C。B代表总线,C代表片外设备的片选号。
下边来看两个板级的结构,其中spi_board_info用来初始化spi_device,s3c2410_spi_info用来初始化spi_master。这两个板级的结构需要在移植的时候在arch/arm/mach-s3c2440/mach-smdk2440.c中初始化。
- struct spi_board_info {
- char modalias[32];
- constvoid *platform_data;
- void *controller_data;
- int irq;
- u32 max_speed_hz;
- u16 bus_num;
- u16 chip_select;
- u8 mode;
- };
-
- struct s3c2410_spi_info {
- int pin_cs;
- unsignedint num_cs;
- int bus_num;
- void (*gpio_setup)(struct s3c2410_spi_info *spi, int enable);
- void (*set_cs)(struct s3c2410_spi_info *spi, int cs,int pol);
- };
boardinfo是用来管理spi_board_info的结构,spi_board_info通过spi_register_board_info(struct spi_board_info const *info, unsigned n)交由boardinfo来管理,并挂到board_list链表上,list_add_tail(&bi->list,&board_list);
- struct boardinfo {
-
- struct list_head list;
-
- unsigned n_board_info;
-
- struct spi_board_info board_info[0];
- };
s3c24xx_spi是S3C2440的SPI控制器在Linux内核中的具体描述,该结构包含spi_bitbang内嵌结构,控制器时钟频率和占用的中断资源等重要成员,其中spi_bitbang具体负责SPI数据的传输。
- struct s3c24xx_spi {
-
- struct spi_bitbang bitbang;
- struct completion done;
- void __iomem *regs;
- int irq;
- int len;
- int count;
- void (*set_cs)(struct s3c2410_spi_info *spi, int cs,int pol);
- const unsignedchar *tx;
- unsignedchar *rx;
- struct clk *clk;
- struct resource *ioarea;
- struct spi_master *master;
- struct spi_device *curdev;
- struct device *dev;
- struct s3c2410_spi_info *pdata;
- };
为了解决多个不同的SPI设备共享SPI控制器而带来的访问冲突,spi_bitbang使用内核提供的工作队列(workqueue)。workqueue是Linux内核中定义的一种回调处理方式。采用这种方式需要传输数据时,不直接完成数据的传输,而是将要传输的工作分装成相应的消息(spi_message),发送给对应的workqueue,由与workqueue关联的内核守护线程(daemon)负责具体的执行。由于workqueue会将收到的消息按时间先后顺序排列,这样就是对设备的访问严格串行化,解决了冲突。
- struct spi_bitbang {
- struct workqueue_struct *workqueue; //工作队列
- struct work_struct work; //每一次传输都传递下来一个spi_message,都向工作队列头添加一个
- workspinlock_t lock;
- struct list_head queue; //挂接spi_message,如果上一次的spi_message还没有处理完,接下来的spi_message就挂接在queue上等待处理
- u8 busy; //忙碌标志
- u8 use_dma;
- u8 flags;
- struct spi_master *master;/*一下3个函数都是在函数s3c24xx_spi_probe()中被初始化*/
- int (*setup_transfer)(struct spi_device *spi,struct spi_transfer *t); //设置传输模式
- void (*chipselect)(struct spi_device *spi, int is_on); //片选
- #define BITBANG_CS_ACTIVE 1 /* normally nCS, active low */
- #define BITBANG_CS_INACTIVE 0/*传输函数,由s3c24xx_spi_txrx来实现*/
- int (*txrx_bufs)(struct spi_device *spi, struct spi_transfer *t);
- u32 (*txrx_word[4])(struct spi_device *spi,unsigned nsecs,u32 word, u8 bits);
- };
下面来看看spi_message:
- struct spi_message {
- struct list_head transfers;
- struct spi_device *spi;
- unsigned is_dma_mapped:1;
- void (*complete)(void *context);
- void *context;
- unsigned actual_length;
- int status;
- struct list_head queue;
- void *state;
- };
在有消息需要传递的时候,会将spi_transfer通过自己的transfer_list字段挂到spi_message的transfers链表头上。spi_message用来原子的执行spi_transfer表示的一串数组传输请求。这个传输队列是原子的,这意味着在这个消息完成之前不会有其他消息占用总线。消息的执行总是按照FIFO的顺序。
下面看一看spi_transfer:
- struct spi_transfer {
- constvoid *tx_buf;
- void *rx_buf;
- unsigned len;
- dma_addr_t tx_dma;
- dma_addr_t rx_dma;
- unsigned cs_change:1;
- bits_per_word;
- u16 delay_usecs;
- u32 speed_hz;
- struct list_head transfer_list;
}
这篇来分析spi子系统的建立过程。
嵌入式微处理器访问SPI设备有两种方式:使用GPIO模拟SPI接口的工作时序或者使用SPI控制器。使用GPIO模拟SPI接口的工作时序是非常容易实现的,但是会导致大量的时间耗费在模拟SPI接口的时序上,访问效率比较低。
这个是由sys文件系统导出的spi子系统在内核中的视图了。
首先了解一下Linux内核中的几个文件:spi.c也就是spi子系统的核心了,spi_s3c24xx.c是s3c24xx系列芯片的SPI controller驱动,它向更上层的SPI核心层(spi.c)提供接口用来控制外设,是一个被其他驱动使用的驱动。而spidev.c是在核心层基础之上将SPI controller模拟成一个字符型的驱动,向文件系统提供标准的文件系统接口,用来操作对应的SPI controller。
下面我们来看看spi子系统是怎么注册进内核的:
- staticint __init spi_init(void) //spi.c
- {
- int status;
- buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
- if (!buf) {
- status = -ENOMEM;
- goto err0;
- }
- status = bus_register(&spi_bus_type);
- if (status < 0)
- goto err1;
- status = class_register(&spi_master_class);
- if (status < 0)
- goto err2;
- return 0;
- err2:
- bus_unregister(&spi_bus_type);
- err1:
- kfree(buf);
- buf = NULL;
- err0:
- return status;
- }
- postcore_initcall(spi_init);
这里注册了一个spi_bus_type,也就是一个spi总线,和一个spi_master的class。分别对应上图中sys/bus/下的spi目录和sys/class/下的spi_master目录。
下面来分析SPI controller驱动的注册与初始化过程,首先执行的是s3c24xx_spi_init。
- staticint __init s3c24xx_spi_init(void) //spi_s3c24xx.c
- {
- return platform_driver_probe(&s3c24xx_spi_driver, s3c24xx_spi_probe);
- }
platform_driver_probe中完成了s3c24xx_spi_driver这个平台驱动的注册,相应的平台设备在devs.c中定义,在smdk2440_devices中添加&s3c_device_spi0,&s3c_device_spi1,这就生成了图中所示的s3c24xx-spi.0与s3c24xx-spi.1,当然了这图是在网上找的,不是我画的,所以是6410的。这里s3c24xx-spi.0表示s3c2440的spi controller的0号接口,s3c24xx-spi.1表示s3c2440的spi controller的1号接口。注册了s3c24xx_spi_driver后,赋值了平台驱动的probe函数为s3c24xx_spi_probe。添加了platform_driver后会match成功后,调用s3c24xx_spi_probe,这里看其实现:
- static int __init s3c24xx_spi_probe(struct platform_device *pdev)
- {
- struct s3c2410_spi_info *pdata;
- struct s3c24xx_spi *hw;
- struct spi_master *master;
- struct resource *res;
- interr =0;
- /*分配struct spi_master+struct s3c24xx_spi大小的数据,把s3c24xx_spi设为spi_master的私有数据*/
- master =spi_alloc_master(&pdev->dev, sizeof(struct s3c24xx_spi));
- if (master == NULL) {
- dev_err(&pdev->dev, "No memory for spi_master\n");
- err = -ENOMEM;
- goto err_nomem;
- }
- /*从master中获得s3c24xx_spi*/
- hw =spi_master_get_devdata(master);
- memset(hw, 0, sizeof(struct s3c24xx_spi));
-
-
- hw->master =spi_master_get(master);
- /*驱动移植的时候需要实现的重要结构,初始化为&s3c2410_spi0_platdata*/
- hw->pdatapdata = pdata = pdev->dev.platform_data;
- hw->dev = &pdev->dev;
-
-
- if (pdata == NULL) {
- dev_err(&pdev->dev, "No platform data supplied\n");
- err = -ENOENT;
- goto err_no_pdata;
- }
- /*设置平台的私有数据为s3c24xx_spi*/
- platform_set_drvdata(pdev, hw);
- init_completion(&hw->done);
-
-
- /* setup the master state. */
- /*该总线上的设备数*/
- master->num_chipselect = hw->pdata->num_cs;
- /*总线号*/
- master->bus_num =pdata->bus_num;
-
-
- /* setup the state for the bitbang driver */
- /*spi_bitbang专门负责数据的传输*/
- hw->bitbang.master =hw->master;
- hw->bitbang.setup_transfer =s3c24xx_spi_setupxfer;//transfer里的参数设置speed和bits_per_word要调用这个setup_transfer,重新设置传输参数
- hw->bitbang.chipselect =s3c24xx_spi_chipsel;
- hw->bitbang.txrx_bufs =s3c24xx_spi_txrx;
- hw->bitbang.master->setup = s3c24xx_spi_setup;
-
-
- dev_dbg(hw->dev, "bitbang at %p\n", &hw->bitbang);
-
- 。。。。。。。。。。。。。。。。。。。。。。。。
-
- /*初始化设置寄存器,包括对SPIMOSI,SPIMISO,SPICLK引脚的设置*/
- s3c24xx_spi_initialsetup(hw);
-
-
- /* register our spi controller */
-
-
- err =spi_bitbang_start(&hw->bitbang);
- 。。。。。。。。。。。。。。。。。。。。。
- }
spi controller的register在spi_bitbang_start函数中实现:
- int spi_bitbang_start(struct spi_bitbang *bitbang)
- {
- int status;
-
-
- if (!bitbang->master || !bitbang->chipselect)
- return -EINVAL;
- /*动态创建一个work_struct结构,它的处理函数是bitbang_work*/
- INIT_WORK(&bitbang->work, bitbang_work);
- spin_lock_init(&bitbang->lock);
- INIT_LIST_HEAD(&bitbang->queue); //链表头
- /*spi的数据传输就是用这个方法*/
- if (!bitbang->master->transfer)
- bitbang->master->transfer = spi_bitbang_transfer;
- if (!bitbang->txrx_bufs) { //在s3c24xx_spi_probe里定义了txrx_bufs
- bitbang->use_dma =0;
- /*spi_s3c24xx.c中有spi_bitbang_bufs方法,在bitbang_work中被调用*/
- bitbang->txrx_bufs =spi_bitbang_bufs;
- if (!bitbang->master->setup) { //在s3c24xx_spi_probe里定义了master->setup
- if (!bitbang->setup_transfer) //在s3c24xx_spi_probe里定义了 setup_transfer=s3c24xx_spi_setupxfer
- bitbang->setup_transfer =
- spi_bitbang_setup_transfer;
- /*在spi_s3c24xx.c中有setup的处理方法,在spi_new_device中被调用*/
- bitbang->master->setup = spi_bitbang_setup;
- bitbang->master->cleanup = spi_bitbang_cleanup;
- }
- } else if (!bitbang->master->setup)
- return -EINVAL;
-
-
- /* this task is the only thing to touch the SPI bits */
- bitbang->busy =0;
- /调用create_singlethread_workqueue创建单个工作线程/
- bitbang->workqueue =create_singlethread_workqueue(
- dev_name(bitbang->master->dev.parent));
- if (bitbang->workqueue == NULL) {
- status = -EBUSY;
- goto err1;
- }
- status =spi_register_master(bitbang->master);
- if (status<0)
- goto err2;
- return status;
- err2:
- destroy_workqueue(bitbang->workqueue);
- err1:
- return status;
- }
然后看这里是怎样注册spi主机控制器驱动的:
- int spi_register_master(struct spi_master *master)
- {
- 。。。。。。。。。。。。。。。。
-
- dev_set_name(&master->dev,"spi%u", master->bus_num);
- status = device_add(&master->dev);
- scan_boardinfo(master);
- }
这里跟踪scan_boardinfo函数:
- staticvoid scan_boardinfo(struct spi_master *master)
- {
- struct boardinfo *bi;
- mutex_lock(&board_lock);
-
- list_for_each_entry(bi, &board_list, list) {
- struct spi_board_info *chip = bi->board_info;
- unsigned n;
-
- for (n = bi->n_board_info; n > 0; n--, chip++) {
- if (chip->bus_num != master->bus_num)
- continue;
- (void) spi_new_device(master, chip);
- }
- }
- mutex_unlock(&board_lock);
- }
在移植的时候我们会在mach-smdk2440.c中的smdk2440_machine_init中添加spi_register_board_info
这个函数完成了将spi_board_info交由boardinfo管理,并把boardinfo挂载到board_list链表上。也就是说在系统初始化的时候将spi_device交由到挂在board_list上的boardinfo管理,在spi controller的driver注册的时候不但注册这个主机控制器的驱动,还要遍历这个主机控制器的总线上的spi_device,将总线上的spi_device全部注册进内核。当注册进内核并且spi_driver已经注册的时候,如果总线match成功,则会调用spi_driver的probe函数,这个将在后边进行分析。
- int __init
- spi_register_board_info(struct spi_board_info const *info, unsigned n) //n=1
- {
- struct boardinfo *bi;
-
- bi =kmalloc(sizeof(*bi) + n * sizeof *info, GFP_KERNEL);
- if (!bi)
- return -ENOMEM;
- bi->nn_board_info = n;
- memcpy(bi->board_info, info, n * sizeof *info);
-
-
- mutex_lock(&board_lock);
- list_add_tail(&bi->list, &board_list);
- mutex_unlock(&board_lock);
- return 0;
- }
看一下创建新设备的函数:
- struct spi_device *spi_new_device(struct spi_master *master,
- struct spi_board_info *chip)
- {
- struct spi_device *proxy;
- int status;
- proxy =spi_alloc_device(master);
- if (!proxy)
- return NULL;
-
-
- WARN_ON(strlen(chip->modalias)>= sizeof(proxy->modalias));
- /*初始化spi_device的各个字段*/
- proxy->chipchip_select = chip->chip_select;
- proxy->max_speed_hz =chip->max_speed_hz;
- proxy->mode =chip->mode;//设置mode
- proxy->irq =chip->irq;
- /*这里获得了spi_device的名字,这个modalias也是在我们移植时在mach-smdk2440.c中的s3c2410_spi0_board中设定的*/
- strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias)); //spi_bus_type match的时候用到
- proxy->dev.platform_data = (void *) chip->platform_data;
- proxy->controller_data =chip->controller_data;
- proxy->controller_state =NULL;
- /*主要完成将spi_device添加到内核*/
- status =spi_add_device(proxy);
- if (status<0) {
- spi_dev_put(proxy);
- return NULL;
- }
-
-
- return proxy;
- }
下面来看分配spi_alloc_device的函数,主要完成了分配spi_device,并初始化spi->dev的一些字段。
- struct spi_device *spi_alloc_device(struct spi_master *master)
- {
- struct spi_device *spi;
- struct device *dev = master->dev.parent;
- if (!spi_master_get(master))
- return NULL;
- spi = kzalloc(sizeof *spi, GFP_KERNEL);
- if (!spi) {
- dev_err(dev,"cannot alloc spi_device\n");
- spi_master_put(master);
- return NULL;
- }
- spi->master = master;
- spi->dev.parent = dev;
-
- spi->dev.bus = &spi_bus_type;
- spi->dev.release = spidev_release;
- device_initialize(&spi->dev);
- return spi;
- }
下面来看分配的这个spi_device是怎样注册进内核的:
- int spi_add_device(struct spi_device *spi)
- {
- static DEFINE_MUTEX(spi_add_lock);
- struct device *dev = spi->master->dev.parent;
- int status;
-
- if (spi->chip_select >= spi->master->num_chipselect) {//num_chipselect=挂载的总设备数
- dev_err(dev,"cs%d >= max %d\n",
- spi->chip_select,
- spi->master->num_chipselect);
- return -EINVAL;
- }
-
- dev_set_name(&spi->dev,"%s.%u", dev_name(&spi->master->dev), //见spi_register_master
- spi->chip_select);
- mutex_lock(&spi_add_lock);
-
- if (bus_find_device_by_name(&spi_bus_type, NULL, dev_name(&spi->dev))
- != NULL) {
- dev_err(dev,"chipselect %d already in use\n",
- spi->chip_select);
- status = -EBUSY;
- goto done;
- }
- /对spi_device的时钟等进行设置/
- status = spi->master->setup(spi); //不同的设备的频率和分频数不同,结果写在spi的成员变量
- if (status < 0) {
- dev_err(dev,"can't %s %s, status %d\n",
- "setup", dev_name(&spi->dev), status);
- goto done;
- }
-
- status = device_add(&spi->dev);
- if (status < 0)
- dev_err(dev,"can't %s %s, status %d\n",
- "add", dev_name(&spi->dev), status);
- else
- dev_dbg(dev,"registered child %s\n", dev_name(&spi->dev));
-
-
- done:
- mutex_unlock(&spi_add_lock);
- return status;
- }
-
-
static int s3c24xx_spi_setup(struct spi_device *spi)
{
struct s3c24xx_spi_devstate *cs = spi->controller_state;//<span style="color:#009900;">cs是spi_device的成员,保存成员设备信息</span>
struct s3c24xx_spi *hw = to_hw(spi);
int ret;
/* allocate settings on the first call */
if (!cs) {// NULL first
cs = kzalloc(sizeof(struct s3c24xx_spi_devstate), GFP_KERNEL);
if (!cs) {
dev_err(&spi->dev, "no memory for controller state\n");
return -ENOMEM;
}
cs->spcon = SPCON_DEFAULT;
cs->hz = -1;
spi->controller_state = cs;//only set spcon,hz
}
/* initialise the state from the device */
ret = s3c24xx_spi_update_state(spi, NULL);
if (ret)
return ret;
spin_lock(&hw->bitbang.lock);
if (!hw->bitbang.busy) {
hw->bitbang.chipselect(spi, BITBANG_CS_INACTIVE);//cs invalid
/* need to ndelay for 0.5 clocktick ? */
}
spin_unlock(&hw->bitbang.lock);
return 0;
}
-
static int s3c24xx_spi_update_state(struct spi_device *spi,
struct spi_transfer *t) // 第一次t = NULL,以后每来一个transfer都不为空
{
struct s3c24xx_spi *hw = to_hw(spi);
struct s3c24xx_spi_devstate *cs = spi->controller_state;
unsigned int bpw;
unsigned int hz;
unsigned int div;
unsigned long clk;
bpw = t ? t->bits_per_word : spi->bits_per_word;
hz = t ? t->speed_hz : spi->max_speed_hz;
if (!bpw)
bpw = 8;
if (!hz)
hz = spi->max_speed_hz;
if (bpw != 8) {
dev_err(&spi->dev, "invalid bits-per-word (%d)\n", bpw);
return -EINVAL;
}
if (spi->mode != cs->mode) {
u8 spcon = SPCON_DEFAULT | S3C2410_SPCON_ENSCK;
if (spi->mode & SPI_CPHA)
spcon |= S3C2410_SPCON_CPHA_FMTB;
if (spi->mode & SPI_CPOL)
spcon |= S3C2410_SPCON_CPOL_HIGH;
cs->mode = spi->mode;
cs->spcon = spcon;
}
if (cs->hz != hz) {//hz=spi->max_speed_hz
clk = clk_get_rate(hw->clk);//already get hw->clk
div = DIV_ROUND_UP(clk, hz * 2) - 1;//hz=what we want
if (div > 255)
div = 255;
dev_dbg(&spi->dev, "pre-scaler=%d (wanted %d, got %ld)\n",
div, hz, clk / (2 * (div + 1)));
cs->hz = hz;//记录该设备的时钟频率
cs->sppre = div;//记录该设备的分频
}
return 0;
}
-
下面来看这个spi_driver是怎样注册的,又是与spi_device怎样match上的。
在spidev.c中:
- staticint __init spidev_init(void)
- {
- int status;
- BUILD_BUG_ON(N_SPI_MINORS > 256);
- status = register_chrdev(SPIDEV_MAJOR,"spi", &spidev_fops);
- if (status < 0)
- return status;
- spidev_class = class_create(THIS_MODULE,"spidev");
- if (IS_ERR(spidev_class)) {
- unregister_chrdev(SPIDEV_MAJOR, spidev_spi.driver.name);
- return PTR_ERR(spidev_class);
- }
- status = spi_register_driver(&spidev_spi);
- if (status < 0) {
- class_destroy(spidev_class);
- unregister_chrdev(SPIDEV_MAJOR, spidev_spi.driver.name);
- }
- return status;
- }
注册了名为”spi”的字符驱动,然后注册了spidev_spi驱动,这个就是图中sys/Bus/Spi/Drivers/下的spidev。
- staticstruct spi_driver spidev_spi = {
- .driver = {
- .name = "spidev",
- .owner = THIS_MODULE,
- },
- .probe = spidev_probe,
- .remove = __devexit_p(spidev_remove),
- };
这里来看__driver_attach(设备和驱动匹配的时候会调用此函数)这个函数,其中分别调用了driver_match_device,driver_probe_device函数。如果匹配成果调用probe函数,否则返回。
- staticint __driver_attach(struct device *dev,void *data)
- {
- struct device_driver *drv = data;
- if (!driver_match_device(drv, dev))
- return 0;
-
- if (dev->parent)
- down(&dev->parent->sem);
- down(&dev->sem);
- if (!dev->driver)
- driver_probe_device(drv, dev);
- up(&dev->sem);
- if (dev->parent)
- up(&dev->parent->sem);
-
- return 0;
- }
static inline int driver_match_device(struct device_driver *drv,
struct device *dev)
{
return drv->bus->match ? drv->bus->match(dev, drv) : 1;
}<span style="font-family:verdana,sans-serif;font-size:14px;color:#333333;margin: 0px; padding: 0px; line-height: 26px; white-space: normal; background-color: rgb(255, 255, 255);"><span style="font-size:18px;margin: 0px; padding: 0px;">匹配的时候调用的bus的match函数。</span></span><br style="margin: 0px; padding: 0px; color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px; white-space: normal; background-color: rgb(255, 255, 255);" />
- struct bus_type spi_bus_type = {
- .name ="spi",
- .dev_attrs = spi_dev_attrs,
- .match = spi_match_device,
- .uevent = spi_uevent,
- .suspend = spi_suspend,
- .resume = spi_resume,
- };
- staticint spi_match_device(struct device *dev,struct device_driver *drv)
- {
- conststruct spi_device *spi = to_spi_device(dev);
-
-
- return strcmp(spi->modalias, drv->name) == 0;
- }
可以看到这里根据驱动和设备的名字进行匹配,匹配成功后最终会调用驱动的probe函数,如下。
先调用spi_drv_probe后在调用设备probe
- staticint spi_drv_probe(struct device *dev)
- {
- conststruct spi_driver *sdrv = to_spi_driver(dev->driver);
-
-
- return sdrv->probe(to_spi_device(dev));
- }
static int spidev_probe(struct spi_device *spi)
{
struct spidev_data *spidev;
int status;
unsigned long minor;
。。。。
if (status == 0) {
set_bit(minor, minors);
list_add(&spidev->device_entry, &device_list);<span style="color:#009900;">//添加到device_list</span>
}
。。。。
return status;
}
可以看到调用了具体的probe函数,这里实现了把spidev添加到device_list,这样这个虚拟的字符驱动就注册并初始化完毕。
- staticint spidev_remove(struct spi_device *spi)
- {
- struct spidev_data *spidev = spi_get_drvdata(spi);
-
-
-
- spin_lock_irq(&spidev->spi_lock);
- spidev->spi = NULL;
- spi_set_drvdata(spi, NULL);
- spin_unlock_irq(&spidev->spi_lock);
-
-
-
- mutex_lock(&device_list_lock);
- list_del(&spidev->device_entry); //从链表上删除该结点
- device_destroy(spidev_class, spidev->devt);
- clear_bit(MINOR(spidev->devt), minors);
- if (spidev->users == 0)
- kfree(spidev);
- mutex_unlock(&device_list_lock);
-
-
- return 0;
- }
在spidev的注册函数中注册了文件操作集合file_operations,为用户空间提供了操作SPI controller的接口。
- staticstruct file_operations spidev_fops = {
- .owner = THIS_MODULE,
-
-
-
-
- .write = spidev_write,
- .read = spidev_read,
- .unlocked_ioctl = spidev_ioctl,
- .open = spidev_open,
- .release = spidev_release,
- };
到此为止spi子系统与spi_master,spi_device,spi_driver这个Linux设备驱动模型已经建立完了。
这篇文档主要介绍spi数据传输过程。
当应用层要向设备传输数据的时候,会通过ioctl向设备驱动发送传输数据的命令。如图,向SPI从设备发送读写命令,实际的读写操作还是调用了主机控制器驱动的数据传输函数。transfer函数用于spi的IO传输。但是,transfer函数一般不会执行真正的传输操作,而是把要传输的内容放到一个队列里,然后调用一种类似底半部的机制进行真正的传输。这是因为,spi总线一般会连多个spi设备,而spi设备间的访问可能会并发。如果直接在transfer函数中实现传输,那么会产生竞态,spi设备互相间会干扰。所以,真正的spi传输与具体的spi控制器的实现有关,spi的框架代码中没有涉及。像spi设备的片选,根据具体设备进行时钟调整等等都在实现传输的代码中被调用。spi的传输命令都是通过结构spi_message定义,设备程序调用transfer函数将spi_message交给spi总线驱动,总线驱动再将message传到底半部排队,实现串行化传输。
spi_transfer->spi_message->queue_work传输
在spidev.c中实现了file_operations:
- staticstruct file_operations spidev_fops = {
- .owner = THIS_MODULE,
- .write = spidev_write,
- .read = spidev_read,
- .unlocked_ioctl = spidev_ioctl,
- .open = spidev_open,
- .release = spidev_release,
- };
这里看spidev_ioctl的实现:
- staticlong
- spidev_ioctl(struct file *filp, unsignedint cmd, unsignedlong arg)
- {
- int err = 0;
- int retval = 0;
- struct spidev_data *spidev;
- struct spi_device *spi;
- u32 tmp;
- unsigned n_ioc;
- struct spi_ioc_transfer *ioc;
-
-
- if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC)
- return -ENOTTY;
-
-
- if (_IOC_DIR(cmd) & _IOC_READ)
- err = !access_ok(VERIFY_WRITE,
- (void __user *)arg, _IOC_SIZE(cmd));
-
- if (err == 0 && _IOC_DIR(cmd) & _IOC_WRITE)
- err = !access_ok(VERIFY_READ,
- (void __user *)arg, _IOC_SIZE(cmd));
- if (err)
- return -EFAULT;
-
-
-
-
- spidev = filp->private_data;
- spin_lock_irq(&spidev->spi_lock);
- spi = spi_dev_get(spidev->spi);
- spin_unlock_irq(&spidev->spi_lock);
-
- if (spi == NULL)
- return -ESHUTDOWN;
-
- mutex_lock(&spidev->buf_lock);
-
- switch (cmd) {
-
- case SPI_IOC_RD_MODE:
-
- retval = __put_user(spi->mode & SPI_MODE_MASK,
- (__u8 __user *)arg);
- break;
- case SPI_IOC_RD_LSB_FIRST:
- retval = __put_user((spi->mode & SPI_LSB_FIRST) ? 1 : 0,
- (__u8 __user *)arg);
- break;
- case SPI_IOC_RD_BITS_PER_WORD:
- retval = __put_user(spi->bits_per_word, (__u8 __user *)arg);
- break;
- case SPI_IOC_RD_MAX_SPEED_HZ:
- retval = __put_user(spi->max_speed_hz, (__u32 __user *)arg);
- break;
-
-
- case SPI_IOC_WR_MODE:
- retval = __get_user(tmp, (u8 __user *)arg);
- if (retval == 0) {
-
- u8 save = spi->mode;
-
- if (tmp & ~SPI_MODE_MASK) {
- retval = -EINVAL;
- break;
- }
-
- tmp |= spi->mode & ~SPI_MODE_MASK;
- spi->mode = (u8)tmp;
- retval = spi_setup(spi);
- if (retval < 0)
- spi->mode = save;
- else
- dev_dbg(&spi->dev,"spi mode %02x\n", tmp);
- }
- break;
- case SPI_IOC_WR_LSB_FIRST:
- retval = __get_user(tmp, (__u8 __user *)arg);
- if (retval == 0) {
- u8 save = spi->mode;
-
- if (tmp)
- spi->mode |= SPI_LSB_FIRST;
- else
- spi->mode &= ~SPI_LSB_FIRST;
- retval = spi_setup(spi);
- if (retval < 0)
- spi->mode = save;
- else
- dev_dbg(&spi->dev,"%csb first\n",
- tmp ?'l' :'m');
- }
- break;
- case SPI_IOC_WR_BITS_PER_WORD:
- retval = __get_user(tmp, (__u8 __user *)arg);
- if (retval == 0) {
- u8 save = spi->bits_per_word;
-
- spi->bits_per_word = tmp;
- retval = spi_setup(spi);
- if (retval < 0)
- spi->bits_per_word = save;
- else
- dev_dbg(&spi->dev,"%d bits per word\n", tmp);
- }
- break;
- case SPI_IOC_WR_MAX_SPEED_HZ:
- retval = __get_user(tmp, (__u32 __user *)arg);
- if (retval == 0) {
- u32 save = spi->max_speed_hz;
-
- spi->max_speed_hz = tmp;
- retval = spi_setup(spi);
- if (retval < 0)
- spi->max_speed_hz = save;
- else
- dev_dbg(&spi->dev,"%d Hz (max)\n", tmp);
- }
- break;
-
- default:
-
- if (_IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0))
- || _IOC_DIR(cmd) != _IOC_WRITE) {
- retval = -ENOTTY;
- break;
- }
-
- tmp = _IOC_SIZE(cmd);
-
- if ((tmp %sizeof(struct spi_ioc_transfer)) != 0) {
- retval = -EINVAL;
- break;
- }
-
- n_ioc = tmp /sizeof(struct spi_ioc_transfer);
- if (n_ioc == 0)
- break;
-
-
- ioc = kmalloc(tmp, GFP_KERNEL);
- if (!ioc) {
- retval = -ENOMEM;
- break;
- }
-
- if (__copy_from_user(ioc, (void __user *)arg, tmp)) {
- kfree(ioc);
- retval = -EFAULT;
- break;
- }
-
-
- retval = spidev_message(spidev, ioc, n_ioc); //spidev_message(spidev,struct spi_io_transfer ioc,int no);
- kfree(ioc);
- break;
- }
-
- mutex_unlock(&spidev->buf_lock);
- spi_dev_put(spi);
- return retval;
- }
-
下面跟踪spidev_message看看:
- staticint spidev_message(struct spidev_data *spidev,
- struct spi_ioc_transfer *u_xfers, unsigned n_xfers)
- {
- struct spi_message msg;
- struct spi_transfer *k_xfers;
- struct spi_transfer *k_tmp;
- struct spi_ioc_transfer *u_tmp;
- unsigned n, total;
- u8 *buf;
- int status = -EFAULT;
-
- spi_message_init(&msg);
-
- k_xfers = kcalloc(n_xfers,sizeof(*k_tmp), GFP_KERNEL);
- if (k_xfers == NULL)
- return -ENOMEM;
-
- buf = spidev->buffer;
- total = 0;
-
- for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
- n;
- n--, k_tmp++, u_tmp++) {
-
- k_tmp->len = u_tmp->len;
-
- total += k_tmp->len;
- if (total > bufsiz) {
- status = -EMSGSIZE;
- goto done;
- }
-
- if (u_tmp->rx_buf) {
- k_tmp->rx_buf = buf;
- if (!access_ok(VERIFY_WRITE, (u8 __user *)
- (uintptr_t) u_tmp->rx_buf,
- u_tmp->len))
- goto done;
- }
-
- if (u_tmp->tx_buf) {
- k_tmp->tx_buf = buf;
- if (copy_from_user(buf, (const u8 __user *)
- (uintptr_t) u_tmp->tx_buf,
- u_tmp->len))
- goto done;
- }
-
- buf += k_tmp->len;
-
- k_tmp->cs_change = !!u_tmp->cs_change;
-
- k_tmp->bits_per_word = u_tmp->bits_per_word;
-
- k_tmp->delay_usecs = u_tmp->delay_usecs;
-
- k_tmp->speed_hz = u_tmp->speed_hz;
-
- spi_message_add_tail(k_tmp, &msg); //将一个spi_transfer 添加到msg链表上,将所有任务添加到msg中
- }
-
- status = spidev_sync(spidev, &msg);
- if (status < 0)
- goto done;
-
-
- buf = spidev->buffer;
-
- for (n = n_xfers, u_tmp = u_xfers; n; n--, u_tmp++) {
- if (u_tmp->rx_buf) { //上层有数据要接受
- if (__copy_to_user((u8 __user *)
- (uintptr_t) u_tmp->rx_buf, buf,
- u_tmp->len)) {
- status = -EFAULT;
- goto done;
- }
- }
- buf += u_tmp->len;
- }
- status = total;
-
- done:
- kfree(k_xfers);
- return status;
- }
-
看spidev_sync的实现:
- static ssize_t
- spidev_sync(struct spidev_data *spidev,struct spi_message *message)
- {
-
- DECLARE_COMPLETION_ONSTACK(done);
- int status;
-
- message->complete = spidev_complete;
- message->context = &done;
-
- spin_lock_irq(&spidev->spi_lock);
- if (spidev->spi == NULL)
- status = -ESHUTDOWN;
- else
-
- status = spi_async(spidev->spi, message); //开始真正的传输
- spin_unlock_irq(&spidev->spi_lock);
-
- if (status == 0) {
-
- wait_for_completion(&done); //同步机制,见下面--由于传输和本线程是两个不同的线程,所以要同步
- status = message->status;
- if (status == 0)
- status = message->actual_length;
- }
- return status;
- }
-
spi_async在spi.h中定义的:
- staticinlineint
- spi_async(struct spi_device *spi,struct spi_message *message)
- {
- message->spi = spi;
- return spi->master->transfer(spi, message);
- }
-
这里的master->transfer是在spi_bitbang_start中进行赋值的:
bitbang->master->transfer= spi_bitbang_transfer;
看spi_bitbang_transfer的实现:
- int spi_bitbang_transfer(struct spi_device *spi, struct spi_message *m)
- {
- struct spi_bitbang *bitbang;
- unsignedlong flags;
- int status = 0;
-
- m->actual_length = 0;
- m->status = -EINPROGRESS;
-
- bitbang = spi_master_get_devdata(spi->master);
-
- spin_lock_irqsave(&bitbang->lock, flags);
- if (!spi->max_speed_hz)
- status = -ENETDOWN;
- else {
-
- list_add_tail(&m->queue, &bitbang->queue);
-
- queue_work(bitbang->workqueue, &bitbang->work);
- }
- spin_unlock_irqrestore(&bitbang->lock, flags);
-
- return status;
- }
- EXPORT_SYMBOL_GPL(spi_bitbang_transfer);
-
分析工作队列的处理函数:
- staticvoid bitbang_work(struct work_struct *work)
- {
- struct spi_bitbang *bitbang =
- container_of(work,struct spi_bitbang, work);
- unsignedlong flags;
-
- spin_lock_irqsave(&bitbang->lock, flags);
-
- bitbang->busy = 1;
-
- while (!list_empty(&bitbang->queue)) {
- struct spi_message *m;
- struct spi_device *spi;
- unsigned nsecs;
- struct spi_transfer *t = NULL;
- unsigned tmp;
- unsigned cs_change;
- int status;
- int (*setup_transfer)(struct spi_device *,
- struct spi_transfer *);
-
- m = container_of(bitbang->queue.next,struct spi_message,
- queue);
-
- list_del_init(&m->queue);
- spin_unlock_irqrestore(&bitbang->lock, flags);
-
- nsecs = 100;
-
- spi = m->spi;
- tmp = 0;
- cs_change = 1;
- status = 0;
- setup_transfer = NULL;
-
- list_for_each_entry (t, &m->transfers, transfer_list) {
-
/* override speed or wordsize? */
if (t->speed_hz || t->bits_per_word)
do_setup = 1;//重新设置
/* init (-1) or override (1) transfer params */
if (do_setup != 0) {
status = bitbang->setup_transfer(spi, t);//如果transfer里设置了speed_hz或者bits_per_word要重新设置传输参数=s3c24xx_spi_setupxfer
if (status < 0)
break;
if (do_setup == -1)
do_setup = 0;
}
/* set up default clock polarity, and activate chip;
* this implicitly updates clock and spi modes as
* previously recorded for this device via setup().
* (and also deselects any other chip that might be
* selected ...)
*/
if (cs_change) {//最初本代码里cs_change=1,
bitbang->chipselect(spi, BITBANG_CS_ACTIVE);
ndelay(nsecs);
}
cs_change = t->cs_change;//cs_change=本次处理cs的设定值。通常1至n-1的cs=0,n的cs=1,即执行最后一个transfer后要取消片选
- if (t->len) { //说明有数据要处理
- if (!m->is_dma_mapped)
- t->rx_dma = t->tx_dma = 0;
-
- status = bitbang->txrx_bufs(spi, t); //一次所有传输完毕,才会结束
- }
- 。。。。。。。。
-
/* protocol tweaks before next transfer */
if (t->delay_usecs)
udelay(t->delay_usecs);
if (cs_change && !list_is_last(&t->transfer_list, &m->transfers)) {
/* sometimes a short mid-message deselect of the chip
* may be needed to terminate a mode or command
*/
ndelay(nsecs);
bitbang->chipselect(spi, BITBANG_CS_INACTIVE);
ndelay(nsecs);
}
- } //一个transfer执行完毕,循环下一个
- 。。。。。。。。。。。。。。。。
-
- m->status = status;
-
- m->complete(m->context); //同步机制,唤醒对象见上面
-
-
- if (setup_transfer)
- setup_transfer(spi, NULL);
- //假设transfer[0].cs_chagen=0,[1]..[n-1]=0,[n]=1,这里判断的cs_transfer是最后一个transfer
- if (!(status == 0 && cs_change)) {
- ndelay(nsecs);
- bitbang->chipselect(spi, BITBANG_CS_INACTIVE);
- ndelay(nsecs);
- }
-
- spin_lock_irqsave(&bitbang->lock, flags);
- }
- bitbang->busy = 0;
- spin_unlock_irqrestore(&bitbang->lock, flags);
- }
-
这个工作队列的处理函数中调用了spi controller driver中的传输函数:
- static int s3c24xx_spi_txrx(struct spi_device *spi,struct spi_transfer *t)
- {
- struct s3c24xx_spi *hw = to_hw(spi);
-
- dev_dbg(&spi->dev,"txrx: tx %p, rx %p, len %d\n",
- t->tx_buf, t->rx_buf, t->len);
-
- hw->tx = t->tx_buf;
- hw->rx = t->rx_buf;
- hw->len = t->len;
- hw->count = 0;
-
- init_completion(&hw->done);
-
-
-
-
- writeb(hw_txbyte(hw, 0), hw->regs + S3C2410_SPTDAT);//发送结束即接收结束
-
- wait_for_completion(&hw->done); //等待该次transfer传输完毕(被唤醒2)
- return hw->count;
- }
- staticinline unsignedint hw_txbyte(struct s3c24xx_spi *hw, int count)
- {
- return hw->tx ? hw->tx[count] : 0xff;
-
- }
-
下面来分析中断函数:
- static irqreturn_t s3c24xx_spi_irq(int irq, void *dev)
- {
- struct s3c24xx_spi *hw = dev;
-
- unsignedint spsta = readb(hw->regs + S3C2410_SPSTA);
- unsignedint count = hw->count;
-
- if (spsta & S3C2410_SPSTA_DCOL) {
- dev_dbg(hw->dev,"data-collision\n");
-
- complete(&hw->done);
- goto irq_done;
- }
-
- if (!(spsta & S3C2410_SPSTA_READY)) {
- dev_dbg(hw->dev,"spi not ready for tx?\n");
-
- complete(&hw->done);
- goto irq_done;
- }
-
- hw->count++;
-
- if (hw->rx)
- hw->rx[count] = readb(hw->regs + S3C2410_SPRDAT);
-
- count++; //count对于发送和接受都可以用
- //对于接收已经接收到一字节,要存储下一字节,自加1
- //对于发送,进入到中断时已经发送完毕一字节,可以发送下一字节了,所以自加1
-
- if (count < hw->len)
- writeb(hw_txbyte(hw, count), hw->regs + S3C2410_SPTDAT);
- else
-
- complete(&hw->done); //该次transfer传输完毕(唤醒2)
-
- irq_done:
- return IRQ_HANDLED;
- }
-
至此spi数据传输过程完成,如果不想为自己的SPI设备写驱动,那么可以用Linux自带的spidev.c提供的驱动程序,只要在登记时,把设备名设置成spidev就可以了。spidev.c会在device目录下自动为每一个匹配的SPI设备创建设备节点,节点名"spi%d"。之后,用户程序可以通过字符型设备的通用接口控制SPI设备。需要注意的是,spidev创建的设备在设备模型中属于虚拟设备,他的class是spidev_class,他的父设备是在boardinfo中定义的spi设备。
if (!bitbang->txrx_bufs) { //在s3c24xx_spi_probe里定义了txrx_bufs
bitbang->use_dma =0;
/*spi_s3c24xx.c中有spi_bitbang_bufs方法,在bitbang_work中被调用*/
bitbang->txrx_bufs =spi_bitbang_bufs;