• 编写SPI设备驱动程序


    一、SPI驱动框架

    在这里插入图片描述
    spi_bus_type是一个总线,左右两边管理spi_drivers(SPI驱动),spi_device(SPI设备)。都遵守总线、设备、驱动的模型。
    在解析设备树时,会有spi_device结构体,注册进虚拟的spi总线里,spi总线里会有一个或者多个SPI设备。
    当我们写了一些驱动后,会注册spi_driver,在注册时,注册进spi驱动的链表。如果两边匹配的话,probe函数就会被调用。
    就可以注册字符设备。

    二、怎么编写SPI设备驱动程序

    2.1 编写设备树

    • 查看原理图,确定这个设备链接在哪个SPI控制器下
    • 在设备树里,找到SPI控制器的节点
    • 在这个节点下创建子节点,用来表示SPI设备
    &ecspi1 {
    	pinctrl-names = "default";
    	pinctrl-0 = <&pinctrl_ecspi1>;
    
 	fsl,spi-num-chipselects = <2>;
    	cs-gpios = <&gpio4 26 GPIO_ACTIVE_LOW>, <&gpio4 24 GPIO_ACTIVE_LOW>;
    	status = "okay";
    
 	dac: dac {
    		compatible = "100ask,dac";
    		reg = <0>;
    		spi-max-frequency = <10000000>;
    	};
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.2 注册spi_driver

    SPI设备的设备树节点,会被转换为一个spi_device结构体
    我们需要编写一个spi_driver来支持它。

    static const struct of_device_id dac_of_match[] = {
    	{.compatible = "100ask,dac"},
    	{}
    };
    
    static struct spi_driver dac_driver = {
    	.driver = {
    		.name = "dac",
    		.of_match_table = dac_of_match,
    	},
    	.probe = dac_probe,
    	.remove = dac_remove,
    	//.id_table = dac_spi_ids,
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2.3 怎么发起SPI传输

    2.3.1 接口函数

    接口函数都在这个内核文件里:include\linux\spi\spi.h

    • 简易函数
    /**
     * spi_write - SPI synchronous write
     * @spi: device to which data will be written
     * @buf: data buffer
     * @len: data buffer size
     * Context: can sleep
     *  
     * This function writes the buffer @buf.
     * Callable only from contexts that can sleep.
     *
     * Return: zero on success, else a negative error code.
     */ 
    static inline int
    spi_write(struct spi_device *spi, const void *buf, size_t len)
    
    
    /** 
     * spi_read - SPI synchronous read
     * @spi: device from which data will be read
     * @buf: data buffer
     * @len: data buffer size
     * Context: can sleep
     *
     * This function reads the buffer @buf.
     * Callable only from contexts that can sleep.
     *
     * Return: zero on success, else a negative error code.
     */
    static inline int
    spi_read(struct spi_device *spi, void *buf, size_t len)
    
    /**
     * spi_write_then_read - SPI synchronous write followed by read
     * @spi: device with which data will be exchanged
     * @txbuf: data to be written (need not be dma-safe)
     * @n_tx: size of txbuf, in bytes
     * @rxbuf: buffer into which data will be read (need not be dma-safe)
     * @n_rx: size of rxbuf, in bytes
     * Context: can sleep
     *
     * This performs a half duplex MicroWire style transaction with the
     * device, sending txbuf and then reading rxbuf.  The return value
     * is zero for success, else a negative errno status code.
     * This call may only be used from a context that may sleep.
     *  
     * Parameters to this routine are always copied using a small buffer;
     * portable code should never use this for more than 32 bytes.
     * Performance-sensitive or bulk transfer code should instead use
     * spi_{async,sync}() calls with dma-safe buffers.
     *  
     * Return: zero on success, else a negative error code.
     */
    int spi_write_then_read(struct spi_device *spi,
            const void *txbuf, unsigned n_tx,
            void *rxbuf, unsigned n_rx)
    
    /**
     * spi_w8r8 - SPI synchronous 8 bit write followed by 8 bit read
     * @spi: device with which data will be exchanged
     * @cmd: command to be written before data is read back
     * Context: can sleep
     *
     * Callable only from contexts that can sleep.
     *
     * Return: the (unsigned) eight bit number returned by the
     * device, or else a negative error code.
     */
    static inline ssize_t spi_w8r8(struct spi_device *spi, u8 cmd)
    
    
    /**
     * spi_w8r16 - SPI synchronous 8 bit write followed by 16 bit read
     * @spi: device with which data will be exchanged
     * @cmd: command to be written before data is read back
     * Context: can sleep
     *
     * The number is returned in wire-order, which is at least sometimes
     * big-endian.
     *
     * Callable only from contexts that can sleep.
     *
     * Return: the (unsigned) sixteen bit number returned by the
     * device, or else a negative error code.
     */
    static inline ssize_t spi_w8r16(struct spi_device *spi, u8 cmd)
    
    /**
     * spi_w8r16be - SPI synchronous 8 bit write followed by 16 bit big-endian read
     * @spi: device with which data will be exchanged
     * @cmd: command to be written before data is read back
     * Context: can sleep
     *
     * This function is similar to spi_w8r16, with the exception that it will
     * convert the read 16 bit data word from big-endian to native endianness.
     *
     * Callable only from contexts that can sleep.
     *
     * Return: the (unsigned) sixteen bit number returned by the device in cpu
     * endianness, or else a negative error code.
     */
    static inline ssize_t spi_w8r16be(struct spi_device *spi, u8 cmd)
    
    
    /**
     * spi_async - asynchronous SPI transfer
     * @spi: device with which data will be exchanged
     * @message: describes the data transfers, including completion callback
     * Context: any (irqs may be blocked, etc)
     *
     * This call may be used in_irq and other contexts which can't sleep,
     * as well as from task contexts which can sleep.
     *
     * The completion callback is invoked in a context which can't sleep.
     * Before that invocation, the value of message->status is undefined.
     * When the callback is issued, message->status holds either zero (to
     * indicate complete success) or a negative error code.  After that
     * callback returns, the driver which issued the transfer request may
     * deallocate the associated memory; it's no longer in use by any SPI
     * core or controller driver code.
     *      
     * Note that although all messages to a spi_device are handled in
     * FIFO order, messages may go to different devices in other orders.
     * Some device might be higher priority, or have various "hard" access
     * time requirements, for example.
     *  
     * On detection of any fault during the transfer, processing of
     * the entire message is aborted, and the device is deselected.
     * Until returning from the associated message completion callback,
     * no other spi_message queued to that device will be processed.
     * (This rule applies equally to all the synchronous transfer calls,
     * which are wrappers around this core asynchronous primitive.)
     *  
     * Return: zero on success, else a negative error code.
     */
    int spi_async(struct spi_device *spi, struct spi_message *message)
    
    /**
     * spi_sync - blocking/synchronous SPI data transfers
     * @spi: device with which data will be exchanged
     * @message: describes the data transfers
     * Context: can sleep
     *
     * This call may only be used from a context that may sleep.  The sleep
     * is non-interruptible, and has no timeout.  Low-overhead controller
     * drivers may DMA directly into and out of the message buffers.
     *
     * Note that the SPI device's chip select is active during the message,
     * and then is normally disabled between messages.  Drivers for some
     * frequently-used devices may want to minimize costs of selecting a chip,
     * by leaving it selected in anticipation that the next message will go
     * to the same chip.  (That may increase power usage.)
     *
     * Also, the caller is guaranteeing that the memory associated with the
     * message will not be freed before this call returns.
     *
     * Return: zero on success, else a negative error code.
     */
    int spi_sync(struct spi_device *spi, struct spi_message *message)
    
    /**
     * spi_sync_transfer - synchronous SPI data transfer
     * @spi: device with which data will be exchanged
     * @xfers: An array of spi_transfers
     * @num_xfers: Number of items in the xfer array
     * Context: can sleep
     *
     * Does a synchronous SPI data transfer of the given spi_transfer array.
     *
     * For more specific semantics see spi_sync().
     *
     * Return: Return: zero on success, else a negative error code.
     */
    static inline int
    spi_sync_transfer(struct spi_device *spi, struct spi_transfer *xfers,
        unsigned int num_xfers)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175

    2.3.2 函数解析

    在SPI子系统中,用spi_transfer结构体描述一个传输,用spi_message管理整个传输。
    SPI传输时,发出N个字节,就可以同事得到N个字节。

    • 即使指向读N个字节,也必须发出N个字节:可以发出0xff
    • 即使指向发出N个字节,也会读到N个字节:可以忽略读到的数据

    spi_transfer结构体如下图所示:

    • tx_buf:不是NULL的话,要发送的数据保存在里面
    • rx_buf:不是NULL的话,表示读到的数据不要丢弃,保存进rx_buf里

    当发起一次spi_transfer时,需要构造一个spi_transfer

    struct spi_transfer {
    	/* it's ok if tx_buf == rx_buf (right?)
    	 * for MicroWire, one buffer must be null
    	 * buffers must work with dma_*map_single() calls, unless
    	 *   spi_message.is_dma_mapped reports a pre-existing mapping
    	 */
    	const void	*tx_buf;	//发送buffer
    	void		*rx_buf;		//接收buffer
    	unsigned	len;			//长度,表示发送和接收多少字节
    
    	dma_addr_t	tx_dma;
    	dma_addr_t	rx_dma;
    	struct sg_table tx_sg;
    	struct sg_table rx_sg;
    
    	unsigned	cs_change:1;
    	unsigned	tx_nbits:3;
    	unsigned	rx_nbits:3;
    #define	SPI_NBITS_SINGLE	0x01 /* 1bit transfer */
    #define	SPI_NBITS_DUAL		0x02 /* 2bits transfer */
    #define	SPI_NBITS_QUAD		0x04 /* 4bits transfer */
    	u8		bits_per_word;
    	u16		delay_usecs;
    	u32		speed_hz;
    
    	struct list_head transfer_list;
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    可以构造多个spi_transfer结构体,把她们放入一个spi_message里面。
    spi_message结构体如下图所示:

    struct spi_message {
    	struct list_head	transfers;		//用来管理多个spi_transfer的链表
    
    	struct spi_device	*spi;
    
    	unsigned		is_dma_mapped:1;
    
    	/* REVISIT:  we might want a flag affecting the behavior of the
    	 * last transfer ... allowing things like "read 16 bit length L"
    	 * immediately followed by "read L bytes".  Basically imposing
    	 * a specific message scheduling algorithm.
    	 *
    	 * Some controller drivers (message-at-a-time queue processing)
    	 * could provide that as their default scheduling algorithm.  But
    	 * others (with multi-message pipelines) could need a flag to
    	 * tell them about such special cases.
    	 */
    
    	/* completion is reported through a callback */
    	void			(*complete)(void *context);
    	void			*context;
    	unsigned		frame_length;
    	unsigned		actual_length;
    	int			status;
    
    	/* for optional use by whatever driver currently owns the
    	 * spi_message ...  between calls to spi_async and then later
    	 * complete(), that's the spi_controller controller driver.
    	 */
    	struct list_head	queue;
    	void			*state;
    
    	/* list of spi_res reources when the spi message is processed */
    	struct list_head        resources;
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    传输示例:

    static inline ssize_t
    spidev_sync_write(struct spidev_data *spidev, size_t len)
    {
    	struct spi_transfer	t = {		//1. spi_transfer表示读多少、写多少
    			.tx_buf		= spidev->tx_buffer,
    			.len		= len,
    			.speed_hz	= spidev->speed_hz,
    		};
    	struct spi_message	m;
    
    	spi_message_init(&m);		//2. 初始化spi_message
    	spi_message_add_tail(&t, &m);	//3. 把spi_transfer放入spi_message
    	return spidev_sync(spidev, &m);	//4. 发起SPI传输
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    springboot banner
    SuperMap iClient3D for WebGL教程(S3MTilesLayer)- 显示优化设置
    微服务与领域驱动设计,架构实践总结
    2-1.spring源码--Container
    【已解决】Pycharm:卡顿解决方案汇总
    AtCoder Beginner Contest 278 G.Generalized Subtraction Game(思维题/博弈 multi-sg)
    leetcode_208 实现Trie(前缀树)
    LeetCode算法心得——生成特殊数字的最少操作(贪心找规律)
    【C++百宝箱】语法总结:引用 | 内联函数 | auto | 范围for循环
    【小沐学Python】Python实现在线电子书(MkDocs + readthedocs + github + Markdown)
  • 原文地址:https://blog.csdn.net/ch122633/article/details/126837223