【驱动】SPI驱动分析(七)
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:55
用户态
用户应用层使用spidev驱动的步骤如下:
/dev/spidevX.YSPI_IOC_WR_MODESPI_IOC_WR_BITS_PER_WORDSPI_IOC_WR_MAX_SPEED_HZ
总结起来,spidev驱动提供了一种简单而灵活的方式来与SPI设备进行通信,使得用户可以轻松地在Linux系统上开发和控制SPI设备。
spidevspi_testspidevspi_test
Documentation\spispidev_fdx.cspidev_test.cspidev
parse_opts
static void parse_opts(int argc, char *argv[])
{
while (1) {
static const struct option lopts[] = {
{ "device", 1, 0, 'D' },
{ "speed", 1, 0, 's' },
{ "delay", 1, 0, 'd' },
{ "bpw", 1, 0, 'b' },
{ "loop", 0, 0, 'l' },
{ "cpha", 0, 0, 'H' },
{ "cpol", 0, 0, 'O' },
{ "lsb", 0, 0, 'L' },
{ "cs-high", 0, 0, 'C' },
{ "3wire", 0, 0, '3' },
{ "no-cs", 0, 0, 'N' },
{ "ready", 0, 0, 'R' },
{ "dual", 0, 0, '2' },
{ "verbose", 0, 0, 'v' },
{ "quad", 0, 0, '4' },
{ NULL, 0, 0, 0 },
};
int c;
c = getopt_long(argc, argv, "D:s:d:b:lHOLC3NR24p:v", lopts, NULL);
if (c == -1)
break;
switch (c) {
case 'D':
device = optarg;
break;
case 's':
speed = atoi(optarg);
break;
case 'd':
delay = atoi(optarg);
break;
case 'b':
bits = atoi(optarg);
break;
case 'l':
mode |= SPI_LOOP;
break;
case 'H':
mode |= SPI_CPHA;
break;
case 'O':
mode |= SPI_CPOL;
break;
case 'L':
mode |= SPI_LSB_FIRST;
break;
case 'C':
mode |= SPI_CS_HIGH;
break;
case '3':
mode |= SPI_3WIRE;
break;
case 'N':
mode |= SPI_NO_CS;
break;
case 'v':
verbose = 1;
break;
case 'R':
mode |= SPI_READY;
break;
case 'p':
input_tx = optarg;
break;
case '2':
mode |= SPI_TX_DUAL;
break;
case '4':
mode |= SPI_TX_QUAD;
break;
default:
print_usage(argv[0]);
break;
}
}
if (mode & SPI_LOOP) {
if (mode & SPI_TX_DUAL)
mode |= SPI_RX_DUAL;
if (mode & SPI_TX_QUAD)
mode |= SPI_RX_QUAD;
}
}
loptsgetopt_longgetopt_longdevicespeedprint_usageSPI_LOOPSPI_TX_DUALSPI_TX_QUADSPI_RX_DUALSPI_RX_QUAD
print_usage
static void print_usage(const char *prog)
{
printf("Usage: %s [-DsbdlHOLC3]\n", prog);
puts(" -D --device device to use (default /dev/spidev1.1)\n"
" -s --speed max speed (Hz)\n"
" -d --delay delay (usec)\n"
" -b --bpw bits per word \n"
" -l --loop loopback\n"
" -H --cpha clock phase\n"
" -O --cpol clock polarity\n"
" -L --lsb least significant bit first\n"
" -C --cs-high chip select active high\n"
" -3 --3wire SI/SO signals shared\n"
" -v --verbose Verbose (show tx buffer)\n"
" -p Send data (e.g. \"1234\\xde\\xad\")\n"
" -N --no-cs no chip select\n"
" -R --ready slave pulls low to pause\n"
" -2 --dual dual transfer\n"
" -4 --quad quad transfer\n");
exit(1);
}
-D, --device /dev/spidev1.0-s, --speed -d, --delay -b, --bits -l, --loop-H, --cpha-O, --cpol-L, --lsb-C, --cs-high-3, --3wire-N, --no-cs-v, --verbose-t, --transfer -r, --read -w, --write -f, --file -h, --help
transferioctl
static void transfer(int fd, uint8_t const *tx, uint8_t const *rx, size_t len)
{
int ret;
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = len,
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits,
};
if (mode & SPI_TX_QUAD)
tr.tx_nbits = 4;
else if (mode & SPI_TX_DUAL)
tr.tx_nbits = 2;
if (mode & SPI_RX_QUAD)
tr.rx_nbits = 4;
else if (mode & SPI_RX_DUAL)
tr.rx_nbits = 2;
if (!(mode & SPI_LOOP)) {
if (mode & (SPI_TX_QUAD | SPI_TX_DUAL))
tr.rx_buf = 0;
else if (mode & (SPI_RX_QUAD | SPI_RX_DUAL))
tr.tx_buf = 0;
}
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
pabort("can't send spi message");
if (verbose)
hex_dump(tx, len, 32, "TX");
hex_dump(rx, len, 32, "RX");
}
spi_ioc_transfertrspi_ioc_transfertx_bufrx_buflendelay_usecsspeed_hzbits_per_wordmodetrtx_nbitsrx_nbitsmodeSPI_TX_QUADtx_nbitsmodeSPI_TX_DUALtx_nbitsmodeSPI_RX_QUADrx_nbitsmodeSPI_RX_DUALrx_nbitsmodeSPI_LOOPmodetrtx_bufrx_bufmodeSPI_TX_QUADSPI_TX_DUALrx_bufmodeSPI_RX_QUADSPI_RX_DUALtx_bufioctlSPI_IOC_MESSAGE(1)ioctlretpabortverbosehex_dump
\x
static int unescape(char *_dst, char *_src, size_t len)
{
int ret = 0;
char *src = _src;
char *dst = _dst;
unsigned int ch;
while (*src) {
if (*src == '\\' && *(src+1) == 'x') {
sscanf(src + 2, "%2x", &ch);
src += 4;
*dst++ = (unsigned char)ch;
} else {
*dst++ = *src++;
}
ret++;
}
return ret;
}
maintransfer
int main(int argc, char *argv[])
{
int ret = 0;
int fd;
uint8_t *tx;
uint8_t *rx;
int size;
parse_opts(argc, argv);
fd = open(device, O_RDWR);
if (fd < 0)
pabort("can't open device");
/*
* spi mode
*/
ret = ioctl(fd, SPI_IOC_WR_MODE32, &mode);
if (ret == -1)
pabort("can't set spi mode");
ret = ioctl(fd, SPI_IOC_RD_MODE32, &mode);
if (ret == -1)
pabort("can't get spi mode");
/*
* bits per word
*/
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't set bits per word");
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't get bits per word");
/*
* max speed hz
*/
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't set max speed hz");
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't get max speed hz");
printf("spi mode: 0x%x\n", mode);
printf("bits per word: %d\n", bits);
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
if (input_tx) {
size = strlen(input_tx+1);
tx = malloc(size);
rx = malloc(size);
size = unescape((char *)tx, input_tx, size);
transfer(fd, tx, rx, size);
free(rx);
free(tx);
} else {
transfer(fd, default_tx, default_rx, sizeof(default_tx));
}
close(fd);
return ret;
}
parse_optsopenioctlSPI_IOC_WR_MODE32SPI_IOC_RD_MODE32SPI_IOC_WR_BITS_PER_WORDSPI_IOC_RD_BITS_PER_WORDSPI_IOC_WR_MAX_SPEED_HZSPI_IOC_RD_MAX_SPEED_HZprintfinput_tx\0unescapetransfer
transfer
spidev的缺点
使用read、write函数时,只能读、写,之二十半双工方式 使用ioctl可以达到全双工的读写 但是spidev有2个缺点:
- 不支持中断
- 只支持同步操作,不支持异步操作:就是read/write/ioctl这些函数只能执行完毕才可返回
完成代码如下
/*
* SPI testing utility (using spidev driver)
*
* Copyright (c) 2007 MontaVista Software, Inc.
* Copyright (c) 2007 Anton Vorontsov <avorontsov@ru.mvista.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* Cross-compile with cross-gcc -I/path/to/cross-kernel/include
*/
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
static void pabort(const char *s)
{
perror(s);
abort();
}
static const char *device = "/dev/spidev1.1";
static uint32_t mode;
static uint8_t bits = 8;
static uint32_t speed = 500000;
static uint16_t delay;
static int verbose;
uint8_t default_tx[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x40, 0x00, 0x00, 0x00, 0x00, 0x95,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0x0D,
};
uint8_t default_rx[ARRAY_SIZE(default_tx)] = {0, };
char *input_tx;
static void hex_dump(const void *src, size_t length, size_t line_size, char *prefix)
{
int i = 0;
const unsigned char *address = src;
const unsigned char *line = address;
unsigned char c;
printf("%s | ", prefix);
while (length-- > 0) {
printf("%02X ", *address++);
if (!(++i % line_size) || (length == 0 && i % line_size)) {
if (length == 0) {
while (i++ % line_size)
printf("__ ");
}
printf(" | "); /* right close */
while (line < address) {
c = *line++;
printf("%c", (c < 33 || c == 255) ? 0x2E : c);
}
printf("\n");
if (length > 0)
printf("%s | ", prefix);
}
}
}
/*
* Unescape - process hexadecimal escape character
* converts shell input "\x23" -> 0x23
*/
static int unescape(char *_dst, char *_src, size_t len)
{
int ret = 0;
char *src = _src;
char *dst = _dst;
unsigned int ch;
while (*src) {
if (*src == '\\' && *(src+1) == 'x') {
sscanf(src + 2, "%2x", &ch);
src += 4;
*dst++ = (unsigned char)ch;
} else {
*dst++ = *src++;
}
ret++;
}
return ret;
}
static void transfer(int fd, uint8_t const *tx, uint8_t const *rx, size_t len)
{
int ret;
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = len,
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits,
};
if (mode & SPI_TX_QUAD)
tr.tx_nbits = 4;
else if (mode & SPI_TX_DUAL)
tr.tx_nbits = 2;
if (mode & SPI_RX_QUAD)
tr.rx_nbits = 4;
else if (mode & SPI_RX_DUAL)
tr.rx_nbits = 2;
if (!(mode & SPI_LOOP)) {
if (mode & (SPI_TX_QUAD | SPI_TX_DUAL))
tr.rx_buf = 0;
else if (mode & (SPI_RX_QUAD | SPI_RX_DUAL))
tr.tx_buf = 0;
}
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
pabort("can't send spi message");
if (verbose)
hex_dump(tx, len, 32, "TX");
hex_dump(rx, len, 32, "RX");
}
static void print_usage(const char *prog)
{
printf("Usage: %s [-DsbdlHOLC3]\n", prog);
puts(" -D --device device to use (default /dev/spidev1.1)\n"
" -s --speed max speed (Hz)\n"
" -d --delay delay (usec)\n"
" -b --bpw bits per word \n"
" -l --loop loopback\n"
" -H --cpha clock phase\n"
" -O --cpol clock polarity\n"
" -L --lsb least significant bit first\n"
" -C --cs-high chip select active high\n"
" -3 --3wire SI/SO signals shared\n"
" -v --verbose Verbose (show tx buffer)\n"
" -p Send data (e.g. \"1234\\xde\\xad\")\n"
" -N --no-cs no chip select\n"
" -R --ready slave pulls low to pause\n"
" -2 --dual dual transfer\n"
" -4 --quad quad transfer\n");
exit(1);
}
static void parse_opts(int argc, char *argv[])
{
while (1) {
static const struct option lopts[] = {
{ "device", 1, 0, 'D' },
{ "speed", 1, 0, 's' },
{ "delay", 1, 0, 'd' },
{ "bpw", 1, 0, 'b' },
{ "loop", 0, 0, 'l' },
{ "cpha", 0, 0, 'H' },
{ "cpol", 0, 0, 'O' },
{ "lsb", 0, 0, 'L' },
{ "cs-high", 0, 0, 'C' },
{ "3wire", 0, 0, '3' },
{ "no-cs", 0, 0, 'N' },
{ "ready", 0, 0, 'R' },
{ "dual", 0, 0, '2' },
{ "verbose", 0, 0, 'v' },
{ "quad", 0, 0, '4' },
{ NULL, 0, 0, 0 },
};
int c;
c = getopt_long(argc, argv, "D:s:d:b:lHOLC3NR24p:v", lopts, NULL);
if (c == -1)
break;
switch (c) {
case 'D':
device = optarg;
break;
case 's':
speed = atoi(optarg);
break;
case 'd':
delay = atoi(optarg);
break;
case 'b':
bits = atoi(optarg);
break;
case 'l':
mode |= SPI_LOOP;
break;
case 'H':
mode |= SPI_CPHA;
break;
case 'O':
mode |= SPI_CPOL;
break;
case 'L':
mode |= SPI_LSB_FIRST;
break;
case 'C':
mode |= SPI_CS_HIGH;
break;
case '3':
mode |= SPI_3WIRE;
break;
case 'N':
mode |= SPI_NO_CS;
break;
case 'v':
verbose = 1;
break;
case 'R':
mode |= SPI_READY;
break;
case 'p':
input_tx = optarg;
break;
case '2':
mode |= SPI_TX_DUAL;
break;
case '4':
mode |= SPI_TX_QUAD;
break;
default:
print_usage(argv[0]);
break;
}
}
if (mode & SPI_LOOP) {
if (mode & SPI_TX_DUAL)
mode |= SPI_RX_DUAL;
if (mode & SPI_TX_QUAD)
mode |= SPI_RX_QUAD;
}
}
int main(int argc, char *argv[])
{
int ret = 0;
int fd;
uint8_t *tx;
uint8_t *rx;
int size;
parse_opts(argc, argv);
fd = open(device, O_RDWR);
if (fd < 0)
pabort("can't open device");
/*
* spi mode
*/
ret = ioctl(fd, SPI_IOC_WR_MODE32, &mode);
if (ret == -1)
pabort("can't set spi mode");
ret = ioctl(fd, SPI_IOC_RD_MODE32, &mode);
if (ret == -1)
pabort("can't get spi mode");
/*
* bits per word
*/
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't set bits per word");
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't get bits per word");
/*
* max speed hz
*/
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't set max speed hz");
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't get max speed hz");
printf("spi mode: 0x%x\n", mode);
printf("bits per word: %d\n", bits);
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
if (input_tx) {
size = strlen(input_tx+1);
tx = malloc(size);
rx = malloc(size);
size = unescape((char *)tx, input_tx, size);
transfer(fd, tx, rx, size);
free(rx);
free(tx);
} else {
transfer(fd, default_tx, default_rx, sizeof(default_tx));
}
close(fd);
return ret;
}
内核态
DTS配置
&spi0 {
status = "okay";
max-freq = <48000000>; //spi internal clk, don't modify
//dma-names = "tx", "rx"; //enable dma
pinctrl-names = "default"; //pinctrl according to you board
pinctrl-0 = <&spi0_clk &spi0_tx &spi0_rx &spi0_cs0 &spi0_cs1>;
spi_test@00 {
compatible = "rockchip,spi_test_bus0_cs0";
reg = <0>; //chip select 0:cs0 1:cs1
id = <0>;
spi-max-frequency = <24000000>; //spi output clock
//spi-cpha; not support
//spi-cpol; //if the property is here it is 1:clk is high, else 0:clk is low when idle
};
spi_test@01 {
compatible = "rockchip,spi_test_bus0_cs1";
reg = <1>;
id = <1>;
spi-max-frequency = <24000000>;
spi-cpha;
spi-cpol;
};
};
代码分析
static int __init spi_rockchip_test_init(void)
{
int ret = 0;
misc_register(&spi_test_misc);
ret = spi_register_driver(&spi_rockchip_test_driver);
return ret;
}
module_init(spi_rockchip_test_init);
spi_rockchip_test_initmisc_registerspi_test_miscspi_register_driverspi_rockchip_test_driver
static struct spi_driver spi_rockchip_test_driver = {
.driver = {
.name = "spi_test",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(rockchip_spi_test_dt_match),
},
.probe = rockchip_spi_test_probe,
.remove = rockchip_spi_test_remove,
};
spi_rockchip_test_driverstruct spi_driver
.driver.name"spi_test".driver.owner.driver.of_match_table.proberockchip_spi_test_probe.removerockchip_spi_test_remove
static struct miscdevice spi_test_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "spi_misc_test",
.fops = &spi_test_fops,
};
spi_test_miscstruct miscdevice
.minorMISC_DYNAMIC_MINOR.name"spi_misc_test".fopsspi_test_fops
static const struct file_operations spi_test_fops = {
.write = spi_test_write,
};
spi_test_fopsstruct file_operations.writespi_test_writespi_test_write
static int rockchip_spi_test_probe(struct spi_device *spi)
{
int ret;
int id = 0;
struct spi_test_data *spi_test_data = NULL;
if (!spi)
return -ENOMEM;
if (!spi->dev.of_node)
return -ENOMEM;
spi_test_data = (struct spi_test_data *)kzalloc(sizeof(struct spi_test_data), GFP_KERNEL);
if (!spi_test_data) {
dev_err(&spi->dev, "ERR: no memory for spi_test_data\n");
return -ENOMEM;
}
spi->bits_per_word = 8;
spi_test_data->spi = spi;
spi_test_data->dev = &spi->dev;
ret = spi_setup(spi);
if (ret < 0) {
dev_err(spi_test_data->dev, "ERR: fail to setup spi\n");
return -1;
}
if (of_property_read_u32(spi->dev.of_node, "id", &id)) {
dev_warn(&spi->dev, "fail to get id, default set 0\n");
id = 0;
}
g_spi_test_data[id] = spi_test_data;
printk("%s:name=%s,bus_num=%d,cs=%d,mode=%d,speed=%d\n", __func__, spi->modalias, spi->master->bus_num, spi->chip_select, spi->mode, spi->max_speed_hz);
return ret;
}
spiENOMEMspidevof_nodeENOMEMkzallocstruct spi_test_datakzallocENOMEMspi_test_dataENOMEMbits_per_wordspispi->devspi_test_dataspidevspi_setupof_property_read_u32ididspi_test_datag_spi_test_dataidprintk
static ssize_t spi_test_write(struct file *file,
const char __user *buf, size_t n, loff_t *offset)
{
int argc = 0, i;
char tmp[64];
char *argv[16];
char *cmd, *data;
unsigned int id = 0, times = 0, size = 0;
unsigned long us = 0, bytes = 0;
char *txbuf = NULL, *rxbuf = NULL;
ktime_t start_time;
ktime_t end_time;
ktime_t cost_time;
memset(tmp, 0, sizeof(tmp));
if (copy_from_user(tmp, buf, n))
return -EFAULT;
cmd = tmp;
data = tmp;
while (data < (tmp + n)) {
data = strstr(data, " ");
if (!data)
break;
*data = 0;
argv[argc] = ++data;
argc++;
if (argc >= 16)
break;
}
tmp[n - 1] = 0;
if (!strcmp(cmd, "setspeed")) {
int id = 0, val;
struct spi_device *spi = NULL;
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", &val);
if (id >= MAX_SPI_DEV_NUM)
return n;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return n;
} else {
spi = g_spi_test_data[id]->spi;
}
spi->max_speed_hz = val;
} else if (!strcmp(cmd, "write")) {
char name[64];
int fd;
mm_segment_t old_fs = get_fs();
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", ×);
sscanf(argv[2], "%d", &size);
if (argc > 3) {
sscanf(argv[3], "%s", name);
set_fs(KERNEL_DS);
}
txbuf = kzalloc(size, GFP_KERNEL);
if (!txbuf) {
printk("spi write alloc buf size %d fail\n", size);
return n;
}
if (argc > 3) {
fd = sys_open(name, O_RDONLY, 0);
if (fd < 0) {
printk("open %s fail\n", name);
} else {
sys_read(fd, (char __user *)txbuf, size);
sys_close(fd);
}
set_fs(old_fs);
} else {
for (i = 0; i < size; i++)
txbuf[i] = i % 256;
}
start_time = ktime_get();
for (i = 0; i < times; i++)
spi_write_slt(id, txbuf, size);
end_time = ktime_get();
cost_time = ktime_sub(end_time, start_time);
us = ktime_to_us(cost_time);
bytes = size * times * 1;
bytes = bytes * 1000 / us;
printk("spi write %d*%d cost %ldus speed:%ldKB/S\n", size, times, us, bytes);
kfree(txbuf);
} else if (!strcmp(cmd, "read")) {
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", ×);
sscanf(argv[2], "%d", &size);
rxbuf = kzalloc(size, GFP_KERNEL);
if (!rxbuf) {
printk("spi read alloc buf size %d fail\n", size);
return n;
}
start_time = ktime_get();
for (i = 0; i < times; i++)
spi_read_slt(id, rxbuf, size);
end_time = ktime_get();
cost_time = ktime_sub(end_time, start_time);
us = ktime_to_us(cost_time);
bytes = size * times * 1;
bytes = bytes * 1000 / us;
printk("spi read %d*%d cost %ldus speed:%ldKB/S\n", size, times, us, bytes);
kfree(rxbuf);
} else if (!strcmp(cmd, "loop")) {
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", ×);
sscanf(argv[2], "%d", &size);
txbuf = kzalloc(size, GFP_KERNEL);
if (!txbuf) {
printk("spi tx alloc buf size %d fail\n", size);
return n;
}
rxbuf = kzalloc(size, GFP_KERNEL);
if (!rxbuf) {
kfree(txbuf);
printk("spi rx alloc buf size %d fail\n", size);
return n;
}
for (i = 0; i < size; i++)
txbuf[i] = i % 256;
start_time = ktime_get();
for (i = 0; i < times; i++)
spi_write_and_read_slt(id, txbuf, rxbuf, size);
end_time = ktime_get();
cost_time = ktime_sub(end_time, start_time);
us = ktime_to_us(cost_time);
if (memcmp(txbuf, rxbuf, size))
printk("spi loop test fail\n");
bytes = size * times;
bytes = bytes * 1000 / us;
printk("spi loop %d*%d cost %ldus speed:%ldKB/S\n", size, times, us, bytes);
kfree(txbuf);
kfree(rxbuf);
} else {
printk("echo id number size > /dev/spi_misc_test\n");
printk("echo write 0 10 255 > /dev/spi_misc_test\n");
printk("echo write 0 10 255 init.rc > /dev/spi_misc_test\n");
printk("echo read 0 10 255 > /dev/spi_misc_test\n");
printk("echo loop 0 10 255 > /dev/spi_misc_test\n");
printk("echo setspeed 0 1000000 > /dev/spi_misc_test\n");
}
return n;
}
memsettmpcopy_from_usertmpEFAULTargvargvtmpsscanfargvidvalidng_spi_test_data[id]ng_spi_test_data[id]spispispi->max_speed_hzvalsscanfargvidtimessizesscanfargvnametxbufktime_getspi_write_slttimestxbufsizektime_getspi_read_sltsscanfargvidtimessizetxbufi % 256ktime_getspi_write_and_read_slttimestxbufsizerxbufktime_get
int spi_write_and_read_slt(int id, const void *tx_buf,
void *rx_buf, size_t len)
{
int ret = -1;
struct spi_device *spi = NULL;
struct spi_transfer t = {
.tx_buf = tx_buf,
.rx_buf = rx_buf,
.len = len,
};
struct spi_message m;
if (id >= MAX_SPI_DEV_NUM)
return ret;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return ret;
} else {
spi = g_spi_test_data[id]->spi;
}
spi_message_init(&m);
spi_message_add_tail(&t, &m);
return spi_sync(spi, &m);
}
spi_write_and_read_sltspi_transferspi_messagespi_syncspim
int spi_write_then_read_slt(int id, const void *txbuf, unsigned n_tx,
void *rxbuf, unsigned n_rx)
{
int ret = -1;
struct spi_device *spi = NULL;
if (id >= MAX_SPI_DEV_NUM)
return ret;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return ret;
} else {
spi = g_spi_test_data[id]->spi;
}
ret = spi_write_then_read(spi, txbuf, n_tx, rxbuf, n_rx);
return ret;
}
spi_write_then_read
int spi_read_slt(int id, void *rxbuf, size_t n)
{
int ret = -1;
struct spi_device *spi = NULL;
if (id >= MAX_SPI_DEV_NUM)
return ret;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return ret;
} else {
spi = g_spi_test_data[id]->spi;
}
ret = spi_read(spi, rxbuf, n);
return ret;
}
spi_read_sltspi_read
int spi_write_slt(int id, const void *txbuf, size_t n)
{
int ret = -1;
struct spi_device *spi = NULL;
if (id >= MAX_SPI_DEV_NUM)
return -1;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return -1;
} else {
spi = g_spi_test_data[id]->spi;
}
ret = spi_write(spi, txbuf, n);
return ret;
}
spi_write
测试命令
echo write 0 10 255 > /dev/spi_misc_test
echo write 0 10 255 init.rc > /dev/spi_misc_test
echo read 0 10 255 > /dev/spi_misc_test
echo loop 0 10 255 > /dev/spi_misc_test
echo setspeed 0 1000000 > /dev/spi_misc_test
echo 类型 id 循环次数 传输长度 > /dev/spi_misc_test
echo setspeed id 频率(单位 Hz) > /dev/spi_misc_test
如果需要,可以自己修改测试 case。
常见问题
- 调试前确认驱动有跑起来
- 确保 SPI 4 个引脚的 IOMUX 配置无误
- 确认 TX 送时,TX 引脚有正常的波形,CLK 有正常的 CLOCK 信号,CS 信号有拉低
- 如果 clk 频率较高,可以考虑提高驱动强度来改善信号
完整代码
/*drivers/spi/spi-rockchip-test.c -spi test driver
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/* dts config
&spi0 {
status = "okay";
max-freq = <48000000>; //spi internal clk, don't modify
//dma-names = "tx", "rx"; //enable dma
pinctrl-names = "default"; //pinctrl according to you board
pinctrl-0 = <&spi0_clk &spi0_tx &spi0_rx &spi0_cs0 &spi0_cs1>;
spi_test@00 {
compatible = "rockchip,spi_test_bus0_cs0";
reg = <0>; //chip select 0:cs0 1:cs1
id = <0>;
spi-max-frequency = <24000000>; //spi output clock
//spi-cpha; not support
//spi-cpol; //if the property is here it is 1:clk is high, else 0:clk is low when idle
};
spi_test@01 {
compatible = "rockchip,spi_test_bus0_cs1";
reg = <1>;
id = <1>;
spi-max-frequency = <24000000>;
spi-cpha;
spi-cpol;
};
};
*/
/* how to test spi
* echo write 0 10 255 > /dev/spi_misc_test
* echo write 0 10 255 init.rc > /dev/spi_misc_test
* echo read 0 10 255 > /dev/spi_misc_test
* echo loop 0 10 255 > /dev/spi_misc_test
* echo setspeed 0 1000000 > /dev/spi_misc_test
*/
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/fs.h>
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/spi/spi.h>
#include <linux/gpio.h>
#include <linux/of.h>
#include <linux/of_gpio.h>
#include <linux/miscdevice.h>
#include <linux/hrtimer.h>
#include <linux/platform_data/spi-rockchip.h>
#include <asm/uaccess.h>
#include <linux/syscalls.h>
#define MAX_SPI_DEV_NUM 6
#define SPI_MAX_SPEED_HZ 12000000
struct spi_test_data {
struct device *dev;
struct spi_device *spi;
char *rx_buf;
int rx_len;
char *tx_buf;
int tx_len;
};
static struct spi_test_data *g_spi_test_data[MAX_SPI_DEV_NUM];
int spi_write_slt(int id, const void *txbuf, size_t n)
{
int ret = -1;
struct spi_device *spi = NULL;
if (id >= MAX_SPI_DEV_NUM)
return -1;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return -1;
} else {
spi = g_spi_test_data[id]->spi;
}
ret = spi_write(spi, txbuf, n);
return ret;
}
int spi_read_slt(int id, void *rxbuf, size_t n)
{
int ret = -1;
struct spi_device *spi = NULL;
if (id >= MAX_SPI_DEV_NUM)
return ret;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return ret;
} else {
spi = g_spi_test_data[id]->spi;
}
ret = spi_read(spi, rxbuf, n);
return ret;
}
int spi_write_then_read_slt(int id, const void *txbuf, unsigned n_tx,
void *rxbuf, unsigned n_rx)
{
int ret = -1;
struct spi_device *spi = NULL;
if (id >= MAX_SPI_DEV_NUM)
return ret;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return ret;
} else {
spi = g_spi_test_data[id]->spi;
}
ret = spi_write_then_read(spi, txbuf, n_tx, rxbuf, n_rx);
return ret;
}
int spi_write_and_read_slt(int id, const void *tx_buf,
void *rx_buf, size_t len)
{
int ret = -1;
struct spi_device *spi = NULL;
struct spi_transfer t = {
.tx_buf = tx_buf,
.rx_buf = rx_buf,
.len = len,
};
struct spi_message m;
if (id >= MAX_SPI_DEV_NUM)
return ret;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return ret;
} else {
spi = g_spi_test_data[id]->spi;
}
spi_message_init(&m);
spi_message_add_tail(&t, &m);
return spi_sync(spi, &m);
}
static ssize_t spi_test_write(struct file *file,
const char __user *buf, size_t n, loff_t *offset)
{
int argc = 0, i;
char tmp[64];
char *argv[16];
char *cmd, *data;
unsigned int id = 0, times = 0, size = 0;
unsigned long us = 0, bytes = 0;
char *txbuf = NULL, *rxbuf = NULL;
ktime_t start_time;
ktime_t end_time;
ktime_t cost_time;
memset(tmp, 0, sizeof(tmp));
if (copy_from_user(tmp, buf, n))
return -EFAULT;
cmd = tmp;
data = tmp;
while (data < (tmp + n)) {
data = strstr(data, " ");
if (!data)
break;
*data = 0;
argv[argc] = ++data;
argc++;
if (argc >= 16)
break;
}
tmp[n - 1] = 0;
if (!strcmp(cmd, "setspeed")) {
int id = 0, val;
struct spi_device *spi = NULL;
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", &val);
if (id >= MAX_SPI_DEV_NUM)
return n;
if (!g_spi_test_data[id]) {
pr_err("g_spi.%d is NULL\n", id);
return n;
} else {
spi = g_spi_test_data[id]->spi;
}
spi->max_speed_hz = val;
} else if (!strcmp(cmd, "write")) {
char name[64];
int fd;
mm_segment_t old_fs = get_fs();
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", ×);
sscanf(argv[2], "%d", &size);
if (argc > 3) {
sscanf(argv[3], "%s", name);
set_fs(KERNEL_DS);
}
txbuf = kzalloc(size, GFP_KERNEL);
if (!txbuf) {
printk("spi write alloc buf size %d fail\n", size);
return n;
}
if (argc > 3) {
fd = sys_open(name, O_RDONLY, 0);
if (fd < 0) {
printk("open %s fail\n", name);
} else {
sys_read(fd, (char __user *)txbuf, size);
sys_close(fd);
}
set_fs(old_fs);
} else {
for (i = 0; i < size; i++)
txbuf[i] = i % 256;
}
start_time = ktime_get();
for (i = 0; i < times; i++)
spi_write_slt(id, txbuf, size);
end_time = ktime_get();
cost_time = ktime_sub(end_time, start_time);
us = ktime_to_us(cost_time);
bytes = size * times * 1;
bytes = bytes * 1000 / us;
printk("spi write %d*%d cost %ldus speed:%ldKB/S\n", size, times, us, bytes);
kfree(txbuf);
} else if (!strcmp(cmd, "read")) {
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", ×);
sscanf(argv[2], "%d", &size);
rxbuf = kzalloc(size, GFP_KERNEL);
if (!rxbuf) {
printk("spi read alloc buf size %d fail\n", size);
return n;
}
start_time = ktime_get();
for (i = 0; i < times; i++)
spi_read_slt(id, rxbuf, size);
end_time = ktime_get();
cost_time = ktime_sub(end_time, start_time);
us = ktime_to_us(cost_time);
bytes = size * times * 1;
bytes = bytes * 1000 / us;
printk("spi read %d*%d cost %ldus speed:%ldKB/S\n", size, times, us, bytes);
kfree(rxbuf);
} else if (!strcmp(cmd, "loop")) {
sscanf(argv[0], "%d", &id);
sscanf(argv[1], "%d", ×);
sscanf(argv[2], "%d", &size);
txbuf = kzalloc(size, GFP_KERNEL);
if (!txbuf) {
printk("spi tx alloc buf size %d fail\n", size);
return n;
}
rxbuf = kzalloc(size, GFP_KERNEL);
if (!rxbuf) {
kfree(txbuf);
printk("spi rx alloc buf size %d fail\n", size);
return n;
}
for (i = 0; i < size; i++)
txbuf[i] = i % 256;
start_time = ktime_get();
for (i = 0; i < times; i++)
spi_write_and_read_slt(id, txbuf, rxbuf, size);
end_time = ktime_get();
cost_time = ktime_sub(end_time, start_time);
us = ktime_to_us(cost_time);
if (memcmp(txbuf, rxbuf, size))
printk("spi loop test fail\n");
bytes = size * times;
bytes = bytes * 1000 / us;
printk("spi loop %d*%d cost %ldus speed:%ldKB/S\n", size, times, us, bytes);
kfree(txbuf);
kfree(rxbuf);
} else {
printk("echo id number size > /dev/spi_misc_test\n");
printk("echo write 0 10 255 > /dev/spi_misc_test\n");
printk("echo write 0 10 255 init.rc > /dev/spi_misc_test\n");
printk("echo read 0 10 255 > /dev/spi_misc_test\n");
printk("echo loop 0 10 255 > /dev/spi_misc_test\n");
printk("echo setspeed 0 1000000 > /dev/spi_misc_test\n");
}
return n;
}
static const struct file_operations spi_test_fops = {
.write = spi_test_write,
};
static struct miscdevice spi_test_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "spi_misc_test",
.fops = &spi_test_fops,
};
static int rockchip_spi_test_probe(struct spi_device *spi)
{
int ret;
int id = 0;
struct spi_test_data *spi_test_data = NULL;
if (!spi)
return -ENOMEM;
if (!spi->dev.of_node)
return -ENOMEM;
spi_test_data = (struct spi_test_data *)kzalloc(sizeof(struct spi_test_data), GFP_KERNEL);
if (!spi_test_data) {
dev_err(&spi->dev, "ERR: no memory for spi_test_data\n");
return -ENOMEM;
}
spi->bits_per_word = 8;
spi_test_data->spi = spi;
spi_test_data->dev = &spi->dev;
ret = spi_setup(spi);
if (ret < 0) {
dev_err(spi_test_data->dev, "ERR: fail to setup spi\n");
return -1;
}
if (of_property_read_u32(spi->dev.of_node, "id", &id)) {
dev_warn(&spi->dev, "fail to get id, default set 0\n");
id = 0;
}
g_spi_test_data[id] = spi_test_data;
printk("%s:name=%s,bus_num=%d,cs=%d,mode=%d,speed=%d\n", __func__, spi->modalias, spi->master->bus_num, spi->chip_select, spi->mode, spi->max_speed_hz);
return ret;
}
static int rockchip_spi_test_remove(struct spi_device *spi)
{
printk("%s\n", __func__);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id rockchip_spi_test_dt_match[] = {
{ .compatible = "rockchip,spi_test_bus0_cs0", },
{ .compatible = "rockchip,spi_test_bus0_cs1", },
{ .compatible = "rockchip,spi_test_bus1_cs0", },
{ .compatible = "rockchip,spi_test_bus1_cs1", },
{ .compatible = "rockchip,spi_test_bus2_cs0", },
{ .compatible = "rockchip,spi_test_bus2_cs1", },
{ .compatible = "rockchip,spi_test_bus3_cs0", },
{ .compatible = "rockchip,spi_test_bus3_cs1", },
{ .compatible = "rockchip,spi_test_bus4_cs0", },
{ .compatible = "rockchip,spi_test_bus4_cs1", },
{},
};
MODULE_DEVICE_TABLE(of, rockchip_spi_test_dt_match);
#endif /* CONFIG_OF */
static struct spi_driver spi_rockchip_test_driver = {
.driver = {
.name = "spi_test",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(rockchip_spi_test_dt_match),
},
.probe = rockchip_spi_test_probe,
.remove = rockchip_spi_test_remove,
};
static int __init spi_rockchip_test_init(void)
{
int ret = 0;
misc_register(&spi_test_misc);
ret = spi_register_driver(&spi_rockchip_test_driver);
return ret;
}
module_init(spi_rockchip_test_init);
static void __exit spi_rockchip_test_exit(void)
{
misc_deregister(&spi_test_misc);
return spi_unregister_driver(&spi_rockchip_test_driver);
}
module_exit(spi_rockchip_test_exit);
MODULE_AUTHOR("Luo Wei <lw@rock-chips.com>");
MODULE_AUTHOR("Huibin Hong <hhb@rock-chips.com>");
MODULE_DESCRIPTION("ROCKCHIP SPI TEST Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:spi_test");
- 上一篇: 【驱动】SPI驱动分析(五)
- 下一篇: 【爬虫】python requests模拟登录知乎
相关文章
-
【驱动】SPI驱动分析(五)
【驱动】SPI驱动分析(五)
- 互联网
- 2026年04月04日
-
【趣事】用 JavaScript 对抗 DDOS 攻击 (下)
【趣事】用 JavaScript 对抗 DDOS 攻击 (下)
- 互联网
- 2026年04月04日
-
【趣事】用 JavaScript 对抗 DDOS 攻击
【趣事】用 JavaScript 对抗 DDOS 攻击
- 互联网
- 2026年04月04日
-
【爬虫】python requests模拟登录知乎
【爬虫】python requests模拟登录知乎
- 互联网
- 2026年04月04日
-
【面试题精讲】什么是websocket?如何与前端通信?
【面试题精讲】什么是websocket?如何与前端通信?
- 互联网
- 2026年04月04日
-
【面试题精讲】Redis如何实现分布式锁
【面试题精讲】Redis如何实现分布式锁
- 互联网
- 2026年04月04日






