下面来看一下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);
- 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; //对应的控制器指针u32
- max_speed_hz; //spi通信的时钟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;
- char modalias[32]; //名字
- };
这里的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,
- };
- static struct class *spidev_class;
下边来看两个板级的结构,其中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); //spi管脚配置函数
- void (*set_cs)(struct s3c2410_spi_info *spi, int cs,int pol);
- };
- struct boardinfo {
- /*用于挂到链表头board_list上*/
- struct list_head list;
- /*管理的spi_board_info的数量*/
- unsigned n_board_info;
- /*存放结构体spi_board_info*/
- struct spi_board_info board_info[0];
- };
- struct s3c24xx_spi {
- /* bitbang has to be first */
- 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);
- /* data buffers */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;
- };
- 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; //如果为真,此次调用提供dma和cpu虚拟地址
- void (*complete)(void *context); //异步调用完成后的回调函数
- void *context; //回调函数的参数
- unsigned actual_length; //此次传输的实际长度
- int status; //执行的结果,成功被置0,否则是一个负的错误码
- struct list_head queue;
- void *state;
- };
下面看一看spi_transfer:
- struct spi_transfer {
- constvoid *tx_buf; //要写入设备的数据(必须是dma_safe),或者为NULL
- void *rx_buf; //要读取的数据缓冲(必须是dma_safe),或者为NULL
- unsigned len; //tx和rx的大小(字节数),这里不是指它的和,而是各自的长度,他们总是相等的
- dma_addr_t tx_dma; //如果spi_message.is_dma_mapped是真,这个是tx的dma地址
- dma_addr_t rx_dma; //如果spi_message.is_dma_mapped是真,这个是rx的dma地址
- unsigned cs_change:1; //影响此次传输之后的片选,指示本次tranfer结束之后是否要重新片选并调用setup改变设置,这个标志可以较少系统开销u8
- bits_per_word; //每个字长的比特数,如果是0,使用默认值
- u16 delay_usecs; //此次传输结束和片选改变之间的延时,之后就会启动另一个传输或者结束整个消息
- u32 speed_hz; //通信时钟。如果是0,使用默认值
- 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 controller驱动的注册与初始化过程,首先执行的是s3c24xx_spi_init。
- staticint __init s3c24xx_spi_init(void) //spi_s3c24xx.c
- {
- return platform_driver_probe(&s3c24xx_spi_driver, 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);
- 。。。。。。。。。。。。。。。。。。。。。
- }
- 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)
- {
- 。。。。。。。。。。。。。。。。
- /*将spi添加到内核,这也是sys/class/Spi_master下产生Spi0,Spi1的原因*/
- 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);
- /*遍历所有挂在board_list上的struct boardinfo*/
- list_for_each_entry(bi, &board_list, list) {
- struct spi_board_info *chip = bi->board_info;
- unsigned n;
- /*遍历每个boardinfo管理的spi_board_info,如果设备的总线号与控制器的总线好相等,则创建新设备*/
- 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);
- }
这个函数完成了将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;
- }
- 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_bus_type,下面会讲到spi_device与spi_driver是怎样match上的*/
- spi->dev.bus = &spi_bus_type;
- spi->dev.release = spidev_release;
- device_initialize(&spi->dev);
- return spi;
- }
- int spi_add_device(struct spi_device *spi)
- {
- static DEFINE_MUTEX(spi_add_lock);
- struct device *dev = spi->master->dev.parent;
- int status;
- /*spi_device的片选号不能大于spi控制器的片选数*/
- 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;
- }
- /*这里设置是spi_device在Linux设备驱动模型中的name,也就是图中的spi0.0,而在/dev/下设备节点的名字是proxy->modalias中的名字*/
- 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; }
-
在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;
- }
- staticstruct spi_driver spidev_spi = {
- .driver = {
- .name = "spidev",
- .owner = THIS_MODULE,
- },
- .probe = spidev_probe,
- .remove = __devexit_p(spidev_remove),
- };
- staticint __driver_attach(struct device *dev,void *data)
- {
- struct device_driver *drv = data;
- if (!driver_match_device(drv, dev))
- return 0;
- if (dev->parent)/* Needed for USB */
- 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);
- /* make sure ops on existing fds can abort cleanly */
- spin_lock_irq(&spidev->spi_lock);
- spidev->spi = NULL;
- spi_set_drvdata(spi, NULL);
- spin_unlock_irq(&spidev->spi_lock);
- /* prevent new opens */
- 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;
- }
- staticstruct file_operations spidev_fops = {
- .owner = THIS_MODULE,
- /* REVISIT switch to aio primitives, so that userspace
- * gets more complete API coverage. It'll simplify things
- * too, except for the locking.
- */
- .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传输
![](https://i-blog.csdnimg.cn/blog_migrate/394124d8e2ae9b0e020e2ef095d4ef49.jpeg)
在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,
- };
- 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;
- /*查看这个命令的幻数字段是否为'k'*/
- 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;
- /* guard against device removal before, or while,
- * we issue this ioctl.
- */
- 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) {
- /* read requests */
- case SPI_IOC_RD_MODE:
- /*因为已经进行了地址是否有效的检查,所以这里使用__put_user,__get_user,__copy_from_user可以节省几个时钟周期呢*/
- 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;
- /*设置SPI模式*/
- 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:
- /* segmented and/or full-duplex I/O request */
- if (_IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0))
- || _IOC_DIR(cmd) != _IOC_WRITE) {
- retval = -ENOTTY;
- break;
- }
- /*得到用户空间数据的大小*/
- tmp = _IOC_SIZE(cmd);
- /*如果这些数据不能分成spi_ioc_transfer的整数倍,则不能进行传输,spi_io_transfer是对spi_transfer的映射*/
- if ((tmp %sizeof(struct spi_ioc_transfer)) != 0) {
- retval = -EINVAL;
- break;
- }
- /*计算出能分多少个spi_ioc_transfer*/
- 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的tranfers链表头*/
- spi_message_init(&msg);
- /*分配n个spi_transfer的内存空间,一个spi_message由多个数据段spi_message组成*/
- k_xfers = kcalloc(n_xfers,sizeof(*k_tmp), GFP_KERNEL);
- if (k_xfers == NULL)
- return -ENOMEM;
- buf = spidev->buffer;
- total = 0;
- /*这个for循环的主要任务是将所有的spi_transfer组装成一个spi_message*/
- for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
- n;
- n--, k_tmp++, u_tmp++) {
- /*u_tmp是从用户空间传下来的spi_ioc_message的大小,spi_ioc_message是对spi_message的映射*/
- k_tmp->len = u_tmp->len;
- /*统计要传输数据的总量*/
- total += k_tmp->len;
- if (total > bufsiz) {
- status = -EMSGSIZE;
- goto done;
- }
- /*spi_transfer是一个读写的buffer对,如果是要接收则把buffer给接收的rx_buf*/
- 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;
- }
- /*如果要传输,这个buffer给tx_buf使用,从用户空间拷过来要传输的数据*/
- 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;
- /*最后一个transfer传输完毕是否会影响片选*/
- 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_transfer通过它的transfer_list字段挂到spi_message的transfer队列上*/
- spi_message_add_tail(k_tmp, &msg); //将一个spi_transfer 添加到msg链表上,将所有任务添加到msg中
- }
- /*调用底层的传输函数*/
- status = spidev_sync(spidev, &msg);
- if (status < 0)
- goto done;
- /* copy any rx data out of bounce buffer */
- 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;
- /*指定spi_message使用的唤醒完成量函数*/
- message->complete = spidev_complete;
- message->context = &done;
- spin_lock_irq(&spidev->spi_lock);
- if (spidev->spi == NULL)
- status = -ESHUTDOWN;
- else
- /*调用spi核心中的函数进行数据传输*/
- 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;
- }
- staticinlineint
- spi_async(struct spi_device *spi,struct spi_message *message)
- {
- message->spi = spi;
- return spi->master->transfer(spi, message);
- }
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;
- /*在spi_alloc_master函数中调用spi_master_set_devdata把struct s3c24xx_spi结构存放起来,而struct spi_bitbang正是struct s3c24xx_spi结构所包含的第一个结构*/
- bitbang = spi_master_get_devdata(spi->master);
- spin_lock_irqsave(&bitbang->lock, flags);
- if (!spi->max_speed_hz)
- status = -ENETDOWN;
- else {
- /*把message加入到bitbang的等待队列中*/
- list_add_tail(&m->queue, &bitbang->queue);
- /*把bitbang-work加入bitbang->workqueue中,调度运行*/
- queue_work(bitbang->workqueue, &bitbang->work);
- }
- spin_unlock_irqrestore(&bitbang->lock, flags);
- return status;
- }
- EXPORT_SYMBOL_GPL(spi_bitbang_transfer);
分析工作队列的处理函数:
![](https://i-blog.csdnimg.cn/blog_migrate/d1f69444e03358fd74c63a54e96c4771.jpeg)
- 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;
- /*对bitqueue中的每一个spi_message进行处理*/
- 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);
- /*从队列中驱动这个spi_message*/
- 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;
- /*对spi_message的transfers上的每个spi_transfer进行处理*/
- 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;
- /*调用bitbang->txrx_bufs进行数据的传输,bitbang->txrx_bufs = s3c24xx_spi_txrx;这个在s3c24xx_spi_probe中进行赋值的*/
- 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); //同步机制,唤醒对象见上面
- /* restore speed and wordsize */
- 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);
- }
- 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; //存放实际spi传输的数据数目
- /*初始化了完成量*/
- init_completion(&hw->done);
- /*
- *只需发送第一个字节(如果发送为空,则发送0xff),每发送完一字节就会进一次中断。判断是否发送完毕,否则继续发送。(并不是在中断中发送,而是在中断中判断是否所有数据执行完毕)
- */
- 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;
- //如果还有数据没接收完且要发送的数据经已发送完毕,发送空数据0xFF
- }
- static irqreturn_t s3c24xx_spi_irq(int irq, void *dev)
- {
- struct s3c24xx_spi *hw = dev;
- /*读取spi的状态寄存器*/
- 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
- /*如果count小于需要发送或接收数据的数目,继续发送其他数据*/
- if (count < hw->len)
- writeb(hw_txbyte(hw, count), hw->regs + S3C2410_SPTDAT);
- else
- /*唤醒完成量,通知s3c24xx_spi_txrx函数*/
- complete(&hw->done); //该次transfer传输完毕(唤醒2)
- irq_done:
- return IRQ_HANDLED;
- }
- 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;