当前位置:   article > 正文

linux驱动开发----zynq----SPI驱动(总线框架)_zynq linux spi驱动开发

zynq linux spi驱动开发

注:本文针对linux-xlnx-xilinx-v2017.4版本进行介绍

一、引言      

        前面我们讲到了SPI的接口标准,以及SPI的工作模式,那么知道这些其实就可以进行SPI驱动的开发了,但是我们这里讲的是linux驱动开发,那么是不是掌握了SPI接口的一些知识就可以进行linux驱动开发呢?当然不是,linux驱动开发对应于总线类型(如:SPI / IIC / USB)的驱动,有一套独立的驱动框架,SPI驱动的开发就需要在SPI驱动框架中去实现。

二、体系结构

        SPI的驱动框架主要包含三个部分:SPI主机控制器驱动、SPI 核心、SPI设备驱动。

组成部分SPI主机控制器驱动SPI 核心SPI设备驱动
主要作用注册平台总线驱动、初始化SPI控制器注册SPI总线以及匹配总线与设备注册SPI设备以及构造file_operation

        可能说到这里,有人对SPI控制器、SPI核心、SPI设备驱动还不清楚是什么东西?那么我们就以xilinx的zynqmp系列芯片来讲解这几个模块。

        SPI主机控制器是具有特定属性的,这个主要看处理器上搭载的是哪个公司生产的SPI控制器,针对zynq中可以在其datasheet中找到其SPI控制器是cadence公司的,那么在内核中必然会存在cadence控制器的驱动程序(如果某个芯片在linux内核驱动中没有对应的驱动程序,那就说明这个芯片太小众了,估计后续技术支持也跟不上)

       SPI核心是通用文件,一方面对SPI子系统进行初始化工作,注册spi bus,注册spi_master class,同时提供spi设备驱动对spi总线进行操作的API。SPI设备驱动包含的种类较多,可以是FLASH驱动、RTC驱动等等,通常对于应用程序来说,在应用层中直接操作设备的file_operation的接口,根本不需要关心SPI总线是如何工作的,这就能很好的将主机与设备进行隔离。

        那有人要说了,我就想用个SPI去发个数据,那怎么办呢?当然,linux内核也可以将主机控制器实现为一个字符设备spidev,这是一个通用的SPI设备文件,应用程序可直接利用spidev来控制SPI主机控制器来产生时序信号,实现对SPI设备的访问。

在linux内核源码里,SPI核心是由\drivers\spi\spi.c来实现的,主机控制器程序是由\drivers\spi\spi-cadence.c来实现的,字符设备spidev由\drivers\spi\spidev.c实现。下面,我们以spidev.c、spi.c、spi-cadence.c这三个文件来分析SPI的总线驱动模型。

       首先,我们看看这个spidev.c文件,我们可以先猜猜这个文件是干啥的?首先它是一个字符设备,那么必然满足字符设备的框架(注册设备、构造file_operation结构体、提供给虚拟文件系统的open、read、write函数接口)。

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/ioctl.h>
  4. #include <linux/fs.h>
  5. #include <linux/device.h>
  6. #include <linux/err.h>
  7. #include <linux/list.h>
  8. #include <linux/errno.h>
  9. #include <linux/mutex.h>
  10. #include <linux/slab.h>
  11. #include <linux/compat.h>
  12. #include <linux/of.h>
  13. #include <linux/of_device.h>
  14. #include <linux/acpi.h>
  15. #include <linux/spi/spi.h>
  16. #include <linux/spi/spidev.h>
  17. #include <linux/uaccess.h>
  18. #define SPIDEV_MAJOR 153 /* assigned */
  19. #define N_SPI_MINORS 32 /* ... up to 256 */
  20. static DECLARE_BITMAP(minors, N_SPI_MINORS);
  21. #define SPI_MODE_MASK (SPI_CPHA | SPI_CPOL | SPI_CS_HIGH \
  22. | SPI_LSB_FIRST | SPI_3WIRE | SPI_LOOP \
  23. | SPI_NO_CS | SPI_READY | SPI_TX_DUAL \
  24. | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)
  25. struct spidev_data { //spidev的结构体
  26. dev_t devt;
  27. spinlock_t spi_lock;
  28. struct spi_device *spi;
  29. struct list_head device_entry;
  30. struct mutex buf_lock;
  31. unsigned users;
  32. u8 *tx_buffer;
  33. u8 *rx_buffer;
  34. u32 speed_hz;
  35. };
  36. static LIST_HEAD(device_list);
  37. static DEFINE_MUTEX(device_list_lock);
  38. static unsigned bufsiz = 4096;
  39. module_param(bufsiz, uint, S_IRUGO);
  40. MODULE_PARM_DESC(bufsiz, "data bytes in biggest supported SPI message");
  41. /*------------------------spidev的同步操作-----------------------------*/
  42. static ssize_t spidev_sync(struct spidev_data *spidev, struct spi_message *message)
  43. {
  44. DECLARE_COMPLETION_ONSTACK(done);
  45. int status;
  46. struct spi_device *spi;
  47. spin_lock_irq(&spidev->spi_lock);
  48. spi = spidev->spi;
  49. spin_unlock_irq(&spidev->spi_lock);
  50. if (spi == NULL)
  51. status = -ESHUTDOWN;
  52. else
  53. status = spi_sync(spi, message); /*调用spi.c中的函数,进行同步操作*/
  54. if (status == 0)
  55. status = message->actual_length;
  56. return status;
  57. }
  58. /*------------------------spidev同步写操作-----------------------------*/
  59. static inline ssize_t
  60. spidev_sync_write(struct spidev_data *spidev, size_t len)
  61. {
  62. struct spi_transfer t = {
  63. .tx_buf = spidev->tx_buffer,
  64. .len = len,
  65. .speed_hz = spidev->speed_hz,
  66. };
  67. struct spi_message m;
  68. spi_message_init(&m);
  69. spi_message_add_tail(&t, &m);
  70. return spidev_sync(spidev, &m);
  71. }
  72. /*------------------------spidev同步读操作-----------------------------*/
  73. static inline ssize_t
  74. spidev_sync_read(struct spidev_data *spidev, size_t len)
  75. {
  76. struct spi_transfer t = {
  77. .rx_buf = spidev->rx_buffer,
  78. .len = len,
  79. .speed_hz = spidev->speed_hz,
  80. };
  81. struct spi_message m;
  82. spi_message_init(&m);
  83. spi_message_add_tail(&t, &m);
  84. return spidev_sync(spidev, &m);
  85. }
  86. /*------------------------spidev只读-----------------------------*/
  87. /* Read-only message with current device setup */
  88. static ssize_t
  89. spidev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
  90. /*spidev读操作(只读模式),,对应于用户空间的read函数*/
  91. {
  92. struct spidev_data *spidev;
  93. ssize_t status = 0;
  94. /* chipselect only toggles at start or end of operation */
  95. if (count > bufsiz)
  96. return -EMSGSIZE;
  97. spidev = filp->private_data;
  98. mutex_lock(&spidev->buf_lock);
  99. status = spidev_sync_read(spidev, count); /*spidev同步读操作*/
  100. if (status > 0) {
  101. unsigned long missing;
  102. missing = copy_to_user(buf, spidev->rx_buffer, status); /*将读回来的数返回给用户空间*/
  103. if (missing == status)
  104. status = -EFAULT;
  105. else
  106. status = status - missing;
  107. }
  108. mutex_unlock(&spidev->buf_lock);
  109. return status;
  110. }
  111. /*------------------------spidev只写-----------------------------*/
  112. /* Write-only message with current device setup */
  113. static ssize_t
  114. spidev_write(struct file *filp, const char __user *buf,
  115. /*spidev写操作(只写模式),对应于用户空间的write函数*/
  116. size_t count, loff_t *f_pos)
  117. {
  118. struct spidev_data *spidev;
  119. ssize_t status = 0;
  120. unsigned long missing;
  121. /* chipselect only toggles at start or end of operation */
  122. if (count > bufsiz)
  123. return -EMSGSIZE;
  124. spidev = filp->private_data;
  125. mutex_lock(&spidev->buf_lock);
  126. missing = copy_from_user(spidev->tx_buffer, buf, count); /*将用户空间中写入spidev的数据拷贝到内核空间*/
  127. if (missing == 0)
  128. status = spidev_sync_write(spidev, count); /*进行同步写操作*/
  129. else
  130. status = -EFAULT;
  131. mutex_unlock(&spidev->buf_lock);
  132. return status;
  133. }
  134. /*------------------------spidev读写操作-----------------------------*/
  135. static int spidev_message(struct spidev_data *spidev, /*启动spidev的数据传输,相当于写一次读一次*/
  136. struct spi_ioc_transfer *u_xfers, unsigned n_xfers)
  137. {
  138. struct spi_message msg;
  139. struct spi_transfer *k_xfers;
  140. struct spi_transfer *k_tmp;
  141. struct spi_ioc_transfer *u_tmp;
  142. unsigned n, total, tx_total, rx_total;
  143. u8 *tx_buf, *rx_buf;
  144. int status = -EFAULT;
  145. spi_message_init(&msg);
  146. k_xfers = kcalloc(n_xfers, sizeof(*k_tmp), GFP_KERNEL);
  147. if (k_xfers == NULL)
  148. return -ENOMEM;
  149. /* Construct spi_message, copying any tx data to bounce buffer.
  150. * We walk the array of user-provided transfers, using each one
  151. * to initialize a kernel version of the same transfer.
  152. */
  153. tx_buf = spidev->tx_buffer;
  154. rx_buf = spidev->rx_buffer;
  155. total = 0;
  156. tx_total = 0;
  157. rx_total = 0;
  158. for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
  159. n;
  160. n--, k_tmp++, u_tmp++) {
  161. k_tmp->len = u_tmp->len;
  162. total += k_tmp->len;
  163. /* Since the function returns the total length of transfers
  164. * on success, restrict the total to positive int values to
  165. * avoid the return value looking like an error. Also check
  166. * each transfer length to avoid arithmetic overflow.
  167. */
  168. if (total > INT_MAX || k_tmp->len > INT_MAX) {
  169. status = -EMSGSIZE;
  170. goto done;
  171. }
  172. if (u_tmp->rx_buf) {
  173. /* this transfer needs space in RX bounce buffer */
  174. rx_total += k_tmp->len;
  175. if (rx_total > bufsiz) {
  176. status = -EMSGSIZE;
  177. goto done;
  178. }
  179. k_tmp->rx_buf = rx_buf;
  180. if (!access_ok(VERIFY_WRITE, (u8 __user *)
  181. (uintptr_t) u_tmp->rx_buf,
  182. u_tmp->len))
  183. goto done;
  184. rx_buf += k_tmp->len;
  185. }
  186. if (u_tmp->tx_buf) {
  187. /* this transfer needs space in TX bounce buffer */
  188. tx_total += k_tmp->len;
  189. if (tx_total > bufsiz) {
  190. status = -EMSGSIZE;
  191. goto done;
  192. }
  193. k_tmp->tx_buf = tx_buf;
  194. if (copy_from_user(tx_buf, (const u8 __user *)
  195. (uintptr_t) u_tmp->tx_buf,
  196. u_tmp->len))
  197. goto done;
  198. tx_buf += k_tmp->len;
  199. }
  200. k_tmp->cs_change = !!u_tmp->cs_change;
  201. k_tmp->tx_nbits = u_tmp->tx_nbits;
  202. k_tmp->rx_nbits = u_tmp->rx_nbits;
  203. k_tmp->bits_per_word = u_tmp->bits_per_word;
  204. k_tmp->delay_usecs = u_tmp->delay_usecs;
  205. k_tmp->speed_hz = u_tmp->speed_hz;
  206. if (!k_tmp->speed_hz)
  207. k_tmp->speed_hz = spidev->speed_hz;
  208. #ifdef VERBOSE
  209. dev_dbg(&spidev->spi->dev,
  210. " xfer len %u %s%s%s%dbits %u usec %uHz\n",
  211. u_tmp->len,
  212. u_tmp->rx_buf ? "rx " : "",
  213. u_tmp->tx_buf ? "tx " : "",
  214. u_tmp->cs_change ? "cs " : "",
  215. u_tmp->bits_per_word ? : spidev->spi->bits_per_word,
  216. u_tmp->delay_usecs,
  217. u_tmp->speed_hz ? : spidev->spi->max_speed_hz);
  218. #endif
  219. spi_message_add_tail(k_tmp, &msg);
  220. }
  221. status = spidev_sync(spidev, &msg);
  222. if (status < 0)
  223. goto done;
  224. /* copy any rx data out of bounce buffer */
  225. rx_buf = spidev->rx_buffer;
  226. for (n = n_xfers, u_tmp = u_xfers; n; n--, u_tmp++) {
  227. if (u_tmp->rx_buf) {
  228. if (__copy_to_user((u8 __user *)
  229. (uintptr_t) u_tmp->rx_buf, rx_buf,
  230. u_tmp->len)) {
  231. status = -EFAULT;
  232. goto done;
  233. }
  234. rx_buf += u_tmp->len;
  235. }
  236. }
  237. status = total;
  238. done:
  239. kfree(k_xfers);
  240. return status;
  241. }
  242. /*------------------------获取用户空间的ioc消息体-----------------------------*/
  243. static struct spi_ioc_transfer *
  244. spidev_get_ioc_message(unsigned int cmd, struct spi_ioc_transfer __user *u_ioc,
  245. unsigned *n_ioc)
  246. {
  247. struct spi_ioc_transfer *ioc;
  248. u32 tmp;
  249. /* Check type, command number and direction */
  250. if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC
  251. || _IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0))
  252. || _IOC_DIR(cmd) != _IOC_WRITE)
  253. return ERR_PTR(-ENOTTY);
  254. tmp = _IOC_SIZE(cmd);
  255. if ((tmp % sizeof(struct spi_ioc_transfer)) != 0)
  256. return ERR_PTR(-EINVAL);
  257. *n_ioc = tmp / sizeof(struct spi_ioc_transfer);
  258. if (*n_ioc == 0)
  259. return NULL;
  260. /* copy into scratch area */
  261. ioc = kmalloc(tmp, GFP_KERNEL);
  262. if (!ioc)
  263. return ERR_PTR(-ENOMEM);
  264. if (__copy_from_user(ioc, u_ioc, tmp)) {
  265. kfree(ioc);
  266. return ERR_PTR(-EFAULT);
  267. }
  268. return ioc;
  269. }
  270. /*------------------------spi_ioctl函数,对应于用户空间的ioctl函数-----------------------------*/
  271. static long
  272. spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
  273. {
  274. int err = 0;
  275. int retval = 0;
  276. struct spidev_data *spidev;
  277. struct spi_device *spi;
  278. u32 tmp;
  279. unsigned n_ioc;
  280. struct spi_ioc_transfer *ioc;
  281. /* Check type and command number */
  282. if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC)
  283. return -ENOTTY;
  284. /* Check access direction once here; don't repeat below.
  285. * IOC_DIR is from the user perspective, while access_ok is
  286. * from the kernel perspective; so they look reversed.
  287. */
  288. if (_IOC_DIR(cmd) & _IOC_READ)
  289. err = !access_ok(VERIFY_WRITE,
  290. (void __user *)arg, _IOC_SIZE(cmd));
  291. if (err == 0 && _IOC_DIR(cmd) & _IOC_WRITE)
  292. err = !access_ok(VERIFY_READ,
  293. (void __user *)arg, _IOC_SIZE(cmd));
  294. if (err)
  295. return -EFAULT;
  296. /* guard against device removal before, or while,
  297. * we issue this ioctl.
  298. */
  299. spidev = filp->private_data;
  300. spin_lock_irq(&spidev->spi_lock);
  301. spi = spi_dev_get(spidev->spi);
  302. spin_unlock_irq(&spidev->spi_lock);
  303. if (spi == NULL)
  304. return -ESHUTDOWN;
  305. /* use the buffer lock here for triple duty:
  306. * - prevent I/O (from us) so calling spi_setup() is safe;
  307. * - prevent concurrent SPI_IOC_WR_* from morphing
  308. * data fields while SPI_IOC_RD_* reads them;
  309. * - SPI_IOC_MESSAGE needs the buffer locked "normally".
  310. */
  311. mutex_lock(&spidev->buf_lock);
  312. switch (cmd) { /*判断ioctl传入的命令*/
  313. /* read requests */
  314. case SPI_IOC_RD_MODE:
  315. retval = __put_user(spi->mode & SPI_MODE_MASK,
  316. (__u8 __user *)arg);
  317. break;
  318. case SPI_IOC_RD_MODE32:
  319. retval = __put_user(spi->mode & SPI_MODE_MASK,
  320. (__u32 __user *)arg);
  321. break;
  322. case SPI_IOC_RD_LSB_FIRST:
  323. retval = __put_user((spi->mode & SPI_LSB_FIRST) ? 1 : 0,
  324. (__u8 __user *)arg);
  325. break;
  326. case SPI_IOC_RD_BITS_PER_WORD:
  327. retval = __put_user(spi->bits_per_word, (__u8 __user *)arg);
  328. break;
  329. case SPI_IOC_RD_MAX_SPEED_HZ:
  330. retval = __put_user(spidev->speed_hz, (__u32 __user *)arg);
  331. break;
  332. /* write requests */
  333. case SPI_IOC_WR_MODE:
  334. case SPI_IOC_WR_MODE32:
  335. if (cmd == SPI_IOC_WR_MODE)
  336. retval = __get_user(tmp, (u8 __user *)arg);
  337. else
  338. retval = __get_user(tmp, (u32 __user *)arg);
  339. if (retval == 0) {
  340. u32 save = spi->mode;
  341. if (tmp & ~SPI_MODE_MASK) {
  342. retval = -EINVAL;
  343. break;
  344. }
  345. tmp |= spi->mode & ~SPI_MODE_MASK;
  346. spi->mode = (u16)tmp;
  347. retval = spi_setup(spi);
  348. if (retval < 0)
  349. spi->mode = save;
  350. else
  351. dev_dbg(&spi->dev, "spi mode %x\n", tmp);
  352. }
  353. break;
  354. case SPI_IOC_WR_LSB_FIRST:
  355. retval = __get_user(tmp, (__u8 __user *)arg);
  356. if (retval == 0) {
  357. u32 save = spi->mode;
  358. if (tmp)
  359. spi->mode |= SPI_LSB_FIRST;
  360. else
  361. spi->mode &= ~SPI_LSB_FIRST;
  362. retval = spi_setup(spi);
  363. if (retval < 0)
  364. spi->mode = save;
  365. else
  366. dev_dbg(&spi->dev, "%csb first\n",
  367. tmp ? 'l' : 'm');
  368. }
  369. break;
  370. case SPI_IOC_WR_BITS_PER_WORD:
  371. retval = __get_user(tmp, (__u8 __user *)arg);
  372. if (retval == 0) {
  373. u8 save = spi->bits_per_word;
  374. spi->bits_per_word = tmp;
  375. retval = spi_setup(spi);
  376. if (retval < 0)
  377. spi->bits_per_word = save;
  378. else
  379. dev_dbg(&spi->dev, "%d bits per word\n", tmp);
  380. }
  381. break;
  382. case SPI_IOC_WR_MAX_SPEED_HZ:
  383. retval = __get_user(tmp, (__u32 __user *)arg);
  384. if (retval == 0) {
  385. u32 save = spi->max_speed_hz;
  386. spi->max_speed_hz = tmp;
  387. retval = spi_setup(spi);
  388. if (retval >= 0)
  389. spidev->speed_hz = tmp;
  390. else
  391. dev_dbg(&spi->dev, "%d Hz (max)\n", tmp);
  392. spi->max_speed_hz = save;
  393. }
  394. break;
  395. default: /*执行一次发送*/
  396. /* segmented and/or full-duplex I/O request */
  397. /* Check message and copy into scratch area */
  398. ioc = spidev_get_ioc_message(cmd,
  399. (struct spi_ioc_transfer __user *)arg, &n_ioc);
  400. if (IS_ERR(ioc)) {
  401. retval = PTR_ERR(ioc);
  402. break;
  403. }
  404. if (!ioc)
  405. break; /* n_ioc is also 0 */
  406. /* translate to spi_message, execute */
  407. retval = spidev_message(spidev, ioc, n_ioc);
  408. kfree(ioc);
  409. break;
  410. }
  411. mutex_unlock(&spidev->buf_lock);
  412. spi_dev_put(spi);
  413. return retval;
  414. }
  415. #ifdef CONFIG_COMPAT
  416. static long
  417. spidev_compat_ioc_message(struct file *filp, unsigned int cmd,
  418. unsigned long arg)
  419. {
  420. struct spi_ioc_transfer __user *u_ioc;
  421. int retval = 0;
  422. struct spidev_data *spidev;
  423. struct spi_device *spi;
  424. unsigned n_ioc, n;
  425. struct spi_ioc_transfer *ioc;
  426. u_ioc = (struct spi_ioc_transfer __user *) compat_ptr(arg);
  427. if (!access_ok(VERIFY_READ, u_ioc, _IOC_SIZE(cmd)))
  428. return -EFAULT;
  429. /* guard against device removal before, or while,
  430. * we issue this ioctl.
  431. */
  432. spidev = filp->private_data;
  433. spin_lock_irq(&spidev->spi_lock);
  434. spi = spi_dev_get(spidev->spi);
  435. spin_unlock_irq(&spidev->spi_lock);
  436. if (spi == NULL)
  437. return -ESHUTDOWN;
  438. /* SPI_IOC_MESSAGE needs the buffer locked "normally" */
  439. mutex_lock(&spidev->buf_lock);
  440. /* Check message and copy into scratch area */
  441. ioc = spidev_get_ioc_message(cmd, u_ioc, &n_ioc);
  442. if (IS_ERR(ioc)) {
  443. retval = PTR_ERR(ioc);
  444. goto done;
  445. }
  446. if (!ioc)
  447. goto done; /* n_ioc is also 0 */
  448. /* Convert buffer pointers */
  449. for (n = 0; n < n_ioc; n++) {
  450. ioc[n].rx_buf = (uintptr_t) compat_ptr(ioc[n].rx_buf);
  451. ioc[n].tx_buf = (uintptr_t) compat_ptr(ioc[n].tx_buf);
  452. }
  453. /* translate to spi_message, execute */
  454. retval = spidev_message(spidev, ioc, n_ioc);
  455. kfree(ioc);
  456. done:
  457. mutex_unlock(&spidev->buf_lock);
  458. spi_dev_put(spi);
  459. return retval;
  460. }
  461. static long
  462. spidev_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
  463. {
  464. if (_IOC_TYPE(cmd) == SPI_IOC_MAGIC
  465. && _IOC_NR(cmd) == _IOC_NR(SPI_IOC_MESSAGE(0))
  466. && _IOC_DIR(cmd) == _IOC_WRITE)
  467. return spidev_compat_ioc_message(filp, cmd, arg);
  468. return spidev_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
  469. }
  470. #else
  471. #define spidev_compat_ioctl NULL
  472. #endif /* CONFIG_COMPAT */
  473. /*------------------------打开spidev设备-----------------------------*/
  474. static int spidev_open(struct inode *inode, struct file *filp)
  475. {
  476. struct spidev_data *spidev;
  477. int status = -ENXIO;
  478. mutex_lock(&device_list_lock);
  479. list_for_each_entry(spidev, &device_list, device_entry) {
  480. if (spidev->devt == inode->i_rdev) {
  481. status = 0;
  482. break;
  483. }
  484. }
  485. if (status) {
  486. pr_debug("spidev: nothing for minor %d\n", iminor(inode));
  487. goto err_find_dev;
  488. }
  489. if (!spidev->tx_buffer) {
  490. spidev->tx_buffer = kmalloc(bufsiz, GFP_KERNEL);/*从内核中分配一块内存给tx_buffer*/
  491. if (!spidev->tx_buffer) {
  492. dev_dbg(&spidev->spi->dev, "open/ENOMEM\n");
  493. status = -ENOMEM;
  494. goto err_find_dev;
  495. }
  496. }
  497. if (!spidev->rx_buffer) {
  498. spidev->rx_buffer = kmalloc(bufsiz, GFP_KERNEL);/*从内核中分配一块内存给rx_buffer*/
  499. if (!spidev->rx_buffer) {
  500. dev_dbg(&spidev->spi->dev, "open/ENOMEM\n");
  501. status = -ENOMEM;
  502. goto err_alloc_rx_buf;
  503. }
  504. }
  505. spidev->users++;
  506. filp->private_data = spidev;
  507. nonseekable_open(inode, filp); /*不需要可搜索文件描述符的子系统使用它*/
  508. mutex_unlock(&device_list_lock);
  509. return 0;
  510. err_alloc_rx_buf:
  511. kfree(spidev->tx_buffer);
  512. spidev->tx_buffer = NULL;
  513. err_find_dev:
  514. mutex_unlock(&device_list_lock);
  515. return status;
  516. }
  517. /*------------------------释放spidev设备-----------------------------*/
  518. static int spidev_release(struct inode *inode, struct file *filp)
  519. {
  520. struct spidev_data *spidev;
  521. mutex_lock(&device_list_lock);
  522. spidev = filp->private_data;
  523. filp->private_data = NULL;
  524. /* last close? */
  525. spidev->users--;
  526. if (!spidev->users) {
  527. int dofree;
  528. kfree(spidev->tx_buffer);
  529. spidev->tx_buffer = NULL;
  530. kfree(spidev->rx_buffer);
  531. spidev->rx_buffer = NULL;
  532. spin_lock_irq(&spidev->spi_lock);
  533. if (spidev->spi)
  534. spidev->speed_hz = spidev->spi->max_speed_hz;
  535. /* ... after we unbound from the underlying device? */
  536. dofree = (spidev->spi == NULL);
  537. spin_unlock_irq(&spidev->spi_lock);
  538. if (dofree)
  539. kfree(spidev);
  540. }
  541. mutex_unlock(&device_list_lock);
  542. return 0;
  543. }
  544. /*-------------------------------------构造file_operation结构体------------------------------------*/
  545. static const struct file_operations spidev_fops = {
  546. .owner = THIS_MODULE,
  547. /* REVISIT switch to aio primitives, so that userspace
  548. * gets more complete API coverage. It'll simplify things
  549. * too, except for the locking.
  550. */
  551. .write = spidev_write,
  552. .read = spidev_read,
  553. .unlocked_ioctl = spidev_ioctl,
  554. .compat_ioctl = spidev_compat_ioctl,
  555. .open = spidev_open,
  556. .release = spidev_release,
  557. .llseek = no_llseek,
  558. };
  559. /*-------------------------------------------------------------------------*/
  560. /* The main reason to have this class is to make mdev/udev create the
  561. * /dev/spidevB.C character device nodes exposing our userspace API.
  562. * It also simplifies memory management.
  563. */
  564. static struct class *spidev_class;
  565. #ifdef CONFIG_OF
  566. static const struct of_device_id spidev_dt_ids[] = { //驱动程序的可匹配的设备列表
  567. { .compatible = "rohm,dh2228fv" },
  568. { .compatible = "lineartechnology,ltc2488" },
  569. { .compatible = "foocorp,modem" },
  570. {},
  571. };
  572. MODULE_DEVICE_TABLE(of, spidev_dt_ids);
  573. #endif
  574. #ifdef CONFIG_ACPI
  575. /* Dummy SPI devices not to be used in production systems */
  576. #define SPIDEV_ACPI_DUMMY 1
  577. static const struct acpi_device_id spidev_acpi_ids[] = {
  578. /*
  579. * The ACPI SPT000* devices are only meant for development and
  580. * testing. Systems used in production should have a proper ACPI
  581. * description of the connected peripheral and they should also use
  582. * a proper driver instead of poking directly to the SPI bus.
  583. */
  584. { "SPT0001", SPIDEV_ACPI_DUMMY },
  585. { "SPT0002", SPIDEV_ACPI_DUMMY },
  586. { "SPT0003", SPIDEV_ACPI_DUMMY },
  587. {},
  588. };
  589. MODULE_DEVICE_TABLE(acpi, spidev_acpi_ids);
  590. static void spidev_probe_acpi(struct spi_device *spi)
  591. {
  592. const struct acpi_device_id *id;
  593. if (!has_acpi_companion(&spi->dev))
  594. return;
  595. id = acpi_match_device(spidev_acpi_ids, &spi->dev);
  596. if (WARN_ON(!id))
  597. return;
  598. if (id->driver_data == SPIDEV_ACPI_DUMMY)
  599. dev_warn(&spi->dev, "do not use this driver in production systems!\n");
  600. }
  601. #else
  602. static inline void spidev_probe_acpi(struct spi_device *spi) {}
  603. #endif
  604. /*-------------------------------------------------------------------------*/
  605. static int spidev_probe(struct spi_device *spi) /*spidev初始化函数*/
  606. {
  607. struct spidev_data *spidev;
  608. int status;
  609. unsigned long minor;
  610. /*
  611. * spidev should never be referenced in DT without a specific
  612. * compatible string, it is a Linux implementation thing
  613. * rather than a description of the hardware.
  614. */
  615. if (spi->dev.of_node && !of_match_device(spidev_dt_ids, &spi->dev)) { /*判断设备树中有没有匹配的字符串*/
  616. dev_err(&spi->dev, "buggy DT: spidev listed directly in DT\n");
  617. WARN_ON(spi->dev.of_node &&
  618. !of_match_device(spidev_dt_ids, &spi->dev));
  619. }
  620. spidev_probe_acpi(spi); /*高级配置和电源管理接口*/
  621. /* Allocate driver data */
  622. spidev = kzalloc(sizeof(*spidev), GFP_KERNEL); /*从内核中分配一个spidev_data结构体*/
  623. if (!spidev)
  624. return -ENOMEM;
  625. /* Initialize the driver data */
  626. spidev->spi = spi;
  627. spin_lock_init(&spidev->spi_lock);
  628. mutex_init(&spidev->buf_lock);
  629. INIT_LIST_HEAD(&spidev->device_entry);
  630. /* If we can allocate a minor number, hook up this device.
  631. * Reusing minors is fine so long as udev or mdev is working.
  632. */
  633. mutex_lock(&device_list_lock);
  634. minor = find_first_zero_bit(minors, N_SPI_MINORS); /*查找一个可用的次设备号*/
  635. if (minor < N_SPI_MINORS) {
  636. struct device *dev;
  637. spidev->devt = MKDEV(SPIDEV_MAJOR, minor);
  638. dev = device_create(spidev_class, &spi->dev, spidev->devt, /*创建spidev设备*/
  639. spidev, "spidev%d.%d",
  640. spi->master->bus_num, spi->chip_select);
  641. status = PTR_ERR_OR_ZERO(dev);
  642. } else {
  643. dev_dbg(&spi->dev, "no minor number available!\n");
  644. status = -ENODEV;
  645. }
  646. if (status == 0) {
  647. set_bit(minor, minors);
  648. list_add(&spidev->device_entry, &device_list);
  649. }
  650. mutex_unlock(&device_list_lock);
  651. spidev->speed_hz = spi->max_speed_hz;
  652. if (status == 0)
  653. spi_set_drvdata(spi, spidev);
  654. else
  655. kfree(spidev);
  656. return status;
  657. }
  658. static int spidev_remove(struct spi_device *spi) /*spidev移除函数*/
  659. {
  660. struct spidev_data *spidev = spi_get_drvdata(spi);
  661. /* make sure ops on existing fds can abort cleanly */
  662. spin_lock_irq(&spidev->spi_lock);
  663. spidev->spi = NULL;
  664. spin_unlock_irq(&spidev->spi_lock);
  665. /* prevent new opens */
  666. mutex_lock(&device_list_lock);
  667. list_del(&spidev->device_entry);
  668. device_destroy(spidev_class, spidev->devt); /*从spidev_class删除spidev*/
  669. clear_bit(MINOR(spidev->devt), minors); /*清除当前spidev的次设备号*/
  670. if (spidev->users == 0)
  671. kfree(spidev);
  672. mutex_unlock(&device_list_lock);
  673. return 0;
  674. }
  675. static struct spi_driver spidev_spi_driver = {
  676. .driver = {
  677. .name = "spidev",
  678. .of_match_table = of_match_ptr(spidev_dt_ids),
  679. .acpi_match_table = ACPI_PTR(spidev_acpi_ids),
  680. },
  681. .probe = spidev_probe,
  682. .remove = spidev_remove,
  683. /* NOTE: suspend/resume methods are not necessary here.
  684. * We don't do anything except pass the requests to/from
  685. * the underlying controller. The refrigerator handles
  686. * most issues; the controller driver handles the rest.
  687. */
  688. };
  689. /*-------------------------------------------------------------------------*/
  690. static int __init spidev_init(void)
  691. {
  692. int status;
  693. /* Claim our 256 reserved device numbers. Then register a class
  694. * that will key udev/mdev to add/remove /dev nodes. Last, register
  695. * the driver which manages those device numbers.
  696. */
  697. BUILD_BUG_ON(N_SPI_MINORS > 256);
  698. status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops);/*注册spidev字符设备*/
  699. if (status < 0)
  700. return status;
  701. spidev_class = class_create(THIS_MODULE, "spidev"); /*创建spidev_class,并将spidev注册到内核中*/
  702. if (IS_ERR(spidev_class)) {
  703. unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
  704. return PTR_ERR(spidev_class);
  705. }
  706. status = spi_register_driver(&spidev_spi_driver); /*注册spi驱动*/
  707. if (status < 0) {
  708. class_destroy(spidev_class);
  709. unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
  710. }
  711. return status;
  712. }
  713. module_init(spidev_init); //作为模块加载进内核
  714. static void __exit spidev_exit(void)
  715. {
  716. spi_unregister_driver(&spidev_spi_driver);
  717. class_destroy(spidev_class);
  718. unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
  719. }
  720. module_exit(spidev_exit); //从内核卸载该模块
  721. MODULE_AUTHOR("Andrea Paterniani, <a.paterniani@swapp-eng.it>");//模块声明
  722. MODULE_DESCRIPTION("User mode SPI device interface");
  723. MODULE_LICENSE("GPL");
  724. MODULE_ALIAS("spi:spidev");

        spidev.c文件中包含有841行代码,那么我们应该怎么看这个代码呢?其实要想初步了解下各个函数的意思还是比较简单的,我们顺着内核模块加载的思路去分析下代码。

       当驱动编译好要insmod进内核时,执行的就是module_init(spidev_init),有加载必然有卸载函数,卸载时就执行module_exit(spidev_exit)。那么我们从module_init(spidev_init)来分析:

下面我们看看spi-cadence.c

  1. /*
  2. * Cadence SPI controller driver (master mode only)
  3. *
  4. * Copyright (C) 2008 - 2014 Xilinx, Inc.
  5. *
  6. * based on Blackfin On-Chip SPI Driver (spi_bfin5xx.c)
  7. *
  8. * This program is free software; you can redistribute it and/or modify it under
  9. * the terms of the GNU General Public License version 2 as published by the
  10. * Free Software Foundation; either version 2 of the License, or (at your
  11. * option) any later version.
  12. */
  13. #include <linux/clk.h>
  14. #include <linux/delay.h>
  15. #include <linux/interrupt.h>
  16. #include <linux/io.h>
  17. #include <linux/module.h>
  18. #include <linux/of_irq.h>
  19. #include <linux/of_address.h>
  20. #include <linux/platform_device.h>
  21. #include <linux/pm_runtime.h>
  22. #include <linux/spi/spi.h>
  23. /* Name of this driver */
  24. #define CDNS_SPI_NAME "cdns-spi"
  25. /* Register offset definitions */
  26. #define CDNS_SPI_CR 0x00 /* Configuration Register, RW */
  27. #define CDNS_SPI_ISR 0x04 /* Interrupt Status Register, RO */
  28. #define CDNS_SPI_IER 0x08 /* Interrupt Enable Register, WO */
  29. #define CDNS_SPI_IDR 0x0c /* Interrupt Disable Register, WO */
  30. #define CDNS_SPI_IMR 0x10 /* Interrupt Enabled Mask Register, RO */
  31. #define CDNS_SPI_ER 0x14 /* Enable/Disable Register, RW */
  32. #define CDNS_SPI_DR 0x18 /* Delay Register, RW */
  33. #define CDNS_SPI_TXD 0x1C /* Data Transmit Register, WO */
  34. #define CDNS_SPI_RXD 0x20 /* Data Receive Register, RO */
  35. #define CDNS_SPI_SICR 0x24 /* Slave Idle Count Register, RW */
  36. #define CDNS_SPI_THLD 0x28 /* Transmit FIFO Watermark Register,RW */
  37. #define SPI_AUTOSUSPEND_TIMEOUT 3000
  38. /*
  39. * SPI Configuration Register bit Masks
  40. *
  41. * This register contains various control bits that affect the operation
  42. * of the SPI controller
  43. */
  44. #define CDNS_SPI_CR_MANSTRT 0x00010000 /* Manual TX Start */
  45. #define CDNS_SPI_CR_CPHA 0x00000004 /* Clock Phase Control */
  46. #define CDNS_SPI_CR_CPOL 0x00000002 /* Clock Polarity Control */
  47. #define CDNS_SPI_CR_SSCTRL 0x00003C00 /* Slave Select Mask */
  48. #define CDNS_SPI_CR_PERI_SEL 0x00000200 /* Peripheral Select Decode */
  49. #define CDNS_SPI_CR_BAUD_DIV 0x00000038 /* Baud Rate Divisor Mask */
  50. #define CDNS_SPI_CR_MSTREN 0x00000001 /* Master Enable Mask */
  51. #define CDNS_SPI_CR_MANSTRTEN 0x00008000 /* Manual TX Enable Mask */
  52. #define CDNS_SPI_CR_SSFORCE 0x00004000 /* Manual SS Enable Mask */
  53. #define CDNS_SPI_CR_BAUD_DIV_4 0x00000008 /* Default Baud Div Mask */
  54. #define CDNS_SPI_CR_DEFAULT (CDNS_SPI_CR_MSTREN | \
  55. CDNS_SPI_CR_SSCTRL | \
  56. CDNS_SPI_CR_BAUD_DIV_4)
  57. // CDNS_SPI_CR_SSFORCE | \
  58. /*
  59. * SPI Configuration Register - Baud rate and slave select
  60. *
  61. * These are the values used in the calculation of baud rate divisor and
  62. * setting the slave select.
  63. */
  64. #define CDNS_SPI_BAUD_DIV_MAX 7 /* Baud rate divisor maximum */
  65. #define CDNS_SPI_BAUD_DIV_MIN 1 /* Baud rate divisor minimum */
  66. #define CDNS_SPI_BAUD_DIV_SHIFT 3 /* Baud rate divisor shift in CR */
  67. #define CDNS_SPI_SS_SHIFT 10 /* Slave Select field shift in CR */
  68. #define CDNS_SPI_SS0 0x1 /* Slave Select zero */
  69. /*
  70. * SPI Interrupt Registers bit Masks
  71. *
  72. * All the four interrupt registers (Status/Mask/Enable/Disable) have the same
  73. * bit definitions.
  74. */
  75. #define CDNS_SPI_IXR_TXOW 0x00000004 /* SPI TX FIFO Overwater */
  76. #define CDNS_SPI_IXR_MODF 0x00000002 /* SPI Mode Fault */
  77. #define CDNS_SPI_IXR_RXNEMTY 0x00000010 /* SPI RX FIFO Not Empty */
  78. #define CDNS_SPI_IXR_DEFAULT (CDNS_SPI_IXR_TXOW | \
  79. CDNS_SPI_IXR_MODF)
  80. #define CDNS_SPI_IXR_TXFULL 0x00000008 /* SPI TX Full */
  81. #define CDNS_SPI_IXR_ALL 0x0000007F /* SPI all interrupts */
  82. /*
  83. * SPI Enable Register bit Masks
  84. *
  85. * This register is used to enable or disable the SPI controller
  86. */
  87. #define CDNS_SPI_ER_ENABLE 0x00000001 /* SPI Enable Bit Mask */
  88. #define CDNS_SPI_ER_DISABLE 0x0 /* SPI Disable Bit Mask */
  89. /* SPI FIFO depth in bytes */
  90. #define CDNS_SPI_FIFO_DEPTH 128
  91. /* Default number of chip select lines */
  92. #define CDNS_SPI_DEFAULT_NUM_CS 4
  93. /**
  94. * struct cdns_spi - This definition defines spi driver instance
  95. * @regs: Virtual address of the SPI controller registers
  96. * @ref_clk: Pointer to the peripheral clock
  97. * @pclk: Pointer to the APB clock
  98. * @speed_hz: Current SPI bus clock speed in Hz
  99. * @txbuf: Pointer to the TX buffer
  100. * @rxbuf: Pointer to the RX buffer
  101. * @tx_bytes: Number of bytes left to transfer
  102. * @rx_bytes: Number of bytes requested
  103. * @dev_busy: Device busy flag
  104. * @is_decoded_cs: Flag for decoder property set or not
  105. */
  106. struct cdns_spi { /*定义cadence_spi驱动结构体,一个结构体就是一个对象*/
  107. void __iomem *regs;
  108. struct clk *ref_clk;
  109. struct clk *pclk;
  110. u32 speed_hz;
  111. const u8 *txbuf;
  112. u8 *rxbuf;
  113. int tx_bytes;
  114. int rx_bytes;
  115. u8 dev_busy;
  116. u32 is_decoded_cs;
  117. };
  118. /* Macros for the SPI controller read/write */
  119. static inline u32 cdns_spi_read(struct cdns_spi *xspi, u32 offset)/*cadence_spi读寄存器*/
  120. {
  121. return readl_relaxed(xspi->regs + offset);
  122. }
  123. static inline void cdns_spi_write(struct cdns_spi *xspi, u32 offset, u32 val)/*cadence_spi写寄存器*/
  124. {
  125. writel_relaxed(val, xspi->regs + offset);
  126. }
  127. /**
  128. * cdns_spi_init_hw - Initialize the hardware and configure the SPI controller
  129. * @xspi: Pointer to the cdns_spi structure
  130. *
  131. * On reset the SPI controller is configured to be in master mode, baud rate
  132. * divisor is set to 4, threshold value for TX FIFO not full interrupt is set
  133. * to 1 and size of the word to be transferred as 8 bit.
  134. * This function initializes the SPI controller to disable and clear all the
  135. * interrupts, enable manual slave select and manual start, deselect all the
  136. * chip select lines, and enable the SPI controller.
  137. */
  138. static void cdns_spi_init_hw(struct cdns_spi *xspi)/*初始化cadence spi控制器*/
  139. {
  140. u32 ctrl_reg = CDNS_SPI_CR_DEFAULT; /*控制寄存器默认为:主机模式使能、无外设被片选、手动片选使能、4分频*/
  141. if (xspi->is_decoded_cs)
  142. ctrl_reg |= CDNS_SPI_CR_PERI_SEL; /*外设片选3-8译码*/
  143. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_DISABLE); /*SPI模块去使能*/
  144. cdns_spi_write(xspi, CDNS_SPI_IDR, CDNS_SPI_IXR_ALL); /*去使能中断寄存器*/
  145. /* Clear the RX FIFO */
  146. while (cdns_spi_read(xspi, CDNS_SPI_ISR) & CDNS_SPI_IXR_RXNEMTY) /*等待中断状态寄存器和rx_fifo被清空*/
  147. cdns_spi_read(xspi, CDNS_SPI_RXD);
  148. cdns_spi_write(xspi, CDNS_SPI_ISR, CDNS_SPI_IXR_ALL); /*清空spi中断控制器的状态*/
  149. cdns_spi_write(xspi, CDNS_SPI_CR, ctrl_reg); /*配置控制寄存器*/
  150. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_ENABLE); /*使能SPI*/
  151. }
  152. /**
  153. * cdns_spi_chipselect - Select or deselect the chip select line
  154. * @spi: Pointer to the spi_device structure
  155. * @is_high: Select(0) or deselect (1) the chip select line
  156. */
  157. static void cdns_spi_chipselect(struct spi_device *spi, bool is_high)/*片选操作*/
  158. {
  159. struct cdns_spi *xspi = spi_master_get_devdata(spi->master); /*获取spi->master的相关信息*/
  160. u32 ctrl_reg;
  161. ctrl_reg = cdns_spi_read(xspi, CDNS_SPI_CR); /*读spi控制寄存器的值*/
  162. if (is_high) {
  163. /* Deselect the slave */
  164. ctrl_reg |= CDNS_SPI_CR_SSCTRL; /*不选择该从机*/
  165. } else {
  166. /* Select the slave */
  167. ctrl_reg &= ~CDNS_SPI_CR_SSCTRL;
  168. if (!(xspi->is_decoded_cs)) /*是否用3-8译码器来片选*/
  169. ctrl_reg |= ((~(CDNS_SPI_SS0 << spi->chip_select)) <<
  170. CDNS_SPI_SS_SHIFT) &
  171. CDNS_SPI_CR_SSCTRL;
  172. else
  173. ctrl_reg |= (spi->chip_select << CDNS_SPI_SS_SHIFT) &
  174. CDNS_SPI_CR_SSCTRL;
  175. }
  176. cdns_spi_write(xspi, CDNS_SPI_CR, ctrl_reg); /*重新写控制寄存器的片选位*/
  177. }
  178. /**
  179. * cdns_spi_config_clock_mode - Sets clock polarity and phase
  180. * @spi: Pointer to the spi_device structure
  181. *
  182. * Sets the requested clock polarity and phase.
  183. */
  184. static void cdns_spi_config_clock_mode(struct spi_device *spi)/*配置时钟相位和极性*/
  185. {
  186. struct cdns_spi *xspi = spi_master_get_devdata(spi->master);/*获取spi->master的相关信息*/
  187. u32 ctrl_reg, new_ctrl_reg;
  188. new_ctrl_reg = cdns_spi_read(xspi, CDNS_SPI_CR);
  189. ctrl_reg = new_ctrl_reg;
  190. /* Set the SPI clock phase and clock polarity */
  191. new_ctrl_reg &= ~(CDNS_SPI_CR_CPHA | CDNS_SPI_CR_CPOL);
  192. if (spi->mode & SPI_CPHA)
  193. new_ctrl_reg |= CDNS_SPI_CR_CPHA;
  194. if (spi->mode & SPI_CPOL)
  195. new_ctrl_reg |= CDNS_SPI_CR_CPOL;
  196. if (new_ctrl_reg != ctrl_reg) {
  197. /*
  198. * Just writing the CR register does not seem to apply the clock
  199. * setting changes. This is problematic when changing the clock
  200. * polarity as it will cause the SPI slave to see spurious clock
  201. * transitions. To workaround the issue toggle the ER register.
  202. */
  203. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_DISABLE);
  204. cdns_spi_write(xspi, CDNS_SPI_CR, new_ctrl_reg); /*重新写控制寄存器的时钟模式*/
  205. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_ENABLE);
  206. }
  207. }
  208. /**
  209. * cdns_spi_config_clock_freq - Sets clock frequency
  210. * @spi: Pointer to the spi_device structure
  211. * @transfer: Pointer to the spi_transfer structure which provides
  212. * information about next transfer setup parameters
  213. *
  214. * Sets the requested clock frequency.
  215. * Note: If the requested frequency is not an exact match with what can be
  216. * obtained using the prescalar value the driver sets the clock frequency which
  217. * is lower than the requested frequency (maximum lower) for the transfer. If
  218. * the requested frequency is higher or lower than that is supported by the SPI
  219. * controller the driver will set the highest or lowest frequency supported by
  220. * controller.
  221. */
  222. static void cdns_spi_config_clock_freq(struct spi_device *spi,/*设置SPI时钟频率*/
  223. struct spi_transfer *transfer)
  224. {
  225. struct cdns_spi *xspi = spi_master_get_devdata(spi->master);
  226. u32 ctrl_reg, baud_rate_val;
  227. unsigned long frequency;
  228. frequency = clk_get_rate(xspi->ref_clk);
  229. ctrl_reg = cdns_spi_read(xspi, CDNS_SPI_CR);
  230. /* Set the clock frequency */
  231. if (xspi->speed_hz != transfer->speed_hz) {
  232. /* first valid value is 1 */
  233. baud_rate_val = CDNS_SPI_BAUD_DIV_MIN;
  234. while ((baud_rate_val < CDNS_SPI_BAUD_DIV_MAX) &&
  235. (frequency / (2 << baud_rate_val)) > transfer->speed_hz)
  236. baud_rate_val++;
  237. ctrl_reg &= ~CDNS_SPI_CR_BAUD_DIV;
  238. ctrl_reg |= baud_rate_val << CDNS_SPI_BAUD_DIV_SHIFT;
  239. xspi->speed_hz = frequency / (2 << baud_rate_val);
  240. }
  241. cdns_spi_write(xspi, CDNS_SPI_CR, ctrl_reg);
  242. }
  243. /**
  244. * cdns_spi_setup_transfer - Configure SPI controller for specified transfer
  245. * @spi: Pointer to the spi_device structure
  246. * @transfer: Pointer to the spi_transfer structure which provides
  247. * information about next transfer setup parameters
  248. *
  249. * Sets the operational mode of SPI controller for the next SPI transfer and
  250. * sets the requested clock frequency.
  251. *
  252. * Return: Always 0
  253. */
  254. static int cdns_spi_setup_transfer(struct spi_device *spi,/*为指定的发送配置SPI控制器*/
  255. struct spi_transfer *transfer)
  256. {
  257. struct cdns_spi *xspi = spi_master_get_devdata(spi->master);
  258. cdns_spi_config_clock_freq(spi, transfer);
  259. dev_dbg(&spi->dev, "%s, mode %d, %u bits/w, %u clock speed\n",
  260. __func__, spi->mode, spi->bits_per_word,
  261. xspi->speed_hz);
  262. return 0;
  263. }
  264. /**
  265. * cdns_spi_fill_tx_fifo - Fills the TX FIFO with as many bytes as possible
  266. * @xspi: Pointer to the cdns_spi structure
  267. */
  268. static void cdns_spi_fill_tx_fifo(struct cdns_spi *xspi)/*向tx_buf中填充数据*/
  269. {
  270. unsigned long trans_cnt = 0;
  271. while ((trans_cnt < CDNS_SPI_FIFO_DEPTH) &&
  272. (xspi->tx_bytes > 0)) {
  273. if (xspi->txbuf)
  274. cdns_spi_write(xspi, CDNS_SPI_TXD, *xspi->txbuf++);
  275. else
  276. cdns_spi_write(xspi, CDNS_SPI_TXD, 0);
  277. xspi->tx_bytes--;
  278. trans_cnt++;
  279. }
  280. }
  281. /**
  282. * cdns_spi_irq - Interrupt service routine of the SPI controller
  283. * @irq: IRQ number
  284. * @dev_id: Pointer to the xspi structure
  285. *
  286. * This function handles TX empty and Mode Fault interrupts only.
  287. * On TX empty interrupt this function reads the received data from RX FIFO and
  288. * fills the TX FIFO if there is any data remaining to be transferred.
  289. * On Mode Fault interrupt this function indicates that transfer is completed,
  290. * the SPI subsystem will identify the error as the remaining bytes to be
  291. * transferred is non-zero.
  292. *
  293. * Return: IRQ_HANDLED when handled; IRQ_NONE otherwise.
  294. */
  295. static irqreturn_t cdns_spi_irq(int irq, void *dev_id)/*SPI控制器中断服务*/
  296. {
  297. struct spi_master *master = dev_id;
  298. struct cdns_spi *xspi = spi_master_get_devdata(master);
  299. u32 intr_status, status;
  300. status = IRQ_NONE;
  301. intr_status = cdns_spi_read(xspi, CDNS_SPI_ISR);
  302. cdns_spi_write(xspi, CDNS_SPI_ISR, intr_status);
  303. if (intr_status & CDNS_SPI_IXR_MODF) {
  304. /* Indicate that transfer is completed, the SPI subsystem will
  305. * identify the error as the remaining bytes to be
  306. * transferred is non-zero
  307. */
  308. cdns_spi_write(xspi, CDNS_SPI_IDR, CDNS_SPI_IXR_DEFAULT);
  309. spi_finalize_current_transfer(master);
  310. status = IRQ_HANDLED;
  311. } else if (intr_status & CDNS_SPI_IXR_TXOW) {
  312. unsigned long trans_cnt;
  313. trans_cnt = xspi->rx_bytes - xspi->tx_bytes;
  314. /* Read out the data from the RX FIFO */
  315. while (trans_cnt) {
  316. u8 data;
  317. data = cdns_spi_read(xspi, CDNS_SPI_RXD);
  318. if (xspi->rxbuf)
  319. *xspi->rxbuf++ = data;
  320. xspi->rx_bytes--;
  321. trans_cnt--;
  322. }
  323. if (xspi->tx_bytes) {
  324. /* There is more data to send */
  325. cdns_spi_fill_tx_fifo(xspi);
  326. } else {
  327. /* Transfer is completed */
  328. cdns_spi_write(xspi, CDNS_SPI_IDR,
  329. CDNS_SPI_IXR_DEFAULT);
  330. spi_finalize_current_transfer(master);
  331. }
  332. status = IRQ_HANDLED;
  333. }
  334. return status;
  335. }
  336. static int cdns_prepare_message(struct spi_master *master,/*准备发送*/
  337. struct spi_message *msg)
  338. {
  339. cdns_spi_config_clock_mode(msg->spi);
  340. return 0;
  341. }
  342. /**
  343. * cdns_transfer_one - Initiates the SPI transfer
  344. * @master: Pointer to spi_master structure
  345. * @spi: Pointer to the spi_device structure
  346. * @transfer: Pointer to the spi_transfer structure which provides
  347. * information about next transfer parameters
  348. *
  349. * This function fills the TX FIFO, starts the SPI transfer and
  350. * returns a positive transfer count so that core will wait for completion.
  351. *
  352. * Return: Number of bytes transferred in the last transfer
  353. */
  354. static int cdns_transfer_one(struct spi_master *master,/*初始化SPI发送*/
  355. struct spi_device *spi,
  356. struct spi_transfer *transfer)
  357. {
  358. struct cdns_spi *xspi = spi_master_get_devdata(master);
  359. xspi->txbuf = transfer->tx_buf;
  360. xspi->rxbuf = transfer->rx_buf;
  361. xspi->tx_bytes = transfer->len;
  362. xspi->rx_bytes = transfer->len;
  363. cdns_spi_setup_transfer(spi, transfer);/*设置SPI时钟频率*/
  364. cdns_spi_fill_tx_fifo(xspi);/*向tx_buf中填充数据*/
  365. cdns_spi_write(xspi, CDNS_SPI_IER, CDNS_SPI_IXR_DEFAULT);
  366. return transfer->len;
  367. }
  368. /**
  369. * cdns_prepare_transfer_hardware - Prepares hardware for transfer.
  370. * @master: Pointer to the spi_master structure which provides
  371. * information about the controller.
  372. *
  373. * This function enables SPI master controller.
  374. *
  375. * Return: 0 always
  376. */
  377. static int cdns_prepare_transfer_hardware(struct spi_master *master)/*准备硬件去发送*/
  378. {
  379. struct cdns_spi *xspi = spi_master_get_devdata(master);
  380. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_ENABLE);
  381. return 0;
  382. }
  383. /**
  384. * cdns_unprepare_transfer_hardware - Relaxes hardware after transfer
  385. * @master: Pointer to the spi_master structure which provides
  386. * information about the controller.
  387. *
  388. * This function disables the SPI master controller.
  389. *
  390. * Return: 0 always
  391. */
  392. static int cdns_unprepare_transfer_hardware(struct spi_master *master)/*发送完成后释放硬件*/
  393. {
  394. struct cdns_spi *xspi = spi_master_get_devdata(master);
  395. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_DISABLE);
  396. return 0;
  397. }
  398. /**
  399. * cdns_spi_probe - Probe method for the SPI driver
  400. * @pdev: Pointer to the platform_device structure
  401. *
  402. * This function initializes the driver data structures and the hardware.
  403. *
  404. * Return: 0 on success and error value on error
  405. */
  406. static int cdns_spi_probe(struct platform_device *pdev)/*cadence_spi驱动探针函数*/
  407. {
  408. int ret = 0, irq;
  409. struct spi_master *master;
  410. struct cdns_spi *xspi;
  411. struct resource *res;
  412. u32 num_cs;
  413. master = spi_alloc_master(&pdev->dev, sizeof(*xspi));//分配一个SPI主机控制器
  414. if (!master)
  415. return -ENOMEM;
  416. xspi = spi_master_get_devdata(master);
  417. master->dev.of_node = pdev->dev.of_node;
  418. platform_set_drvdata(pdev, master);
  419. res = platform_get_resource(pdev, IORESOURCE_MEM, 0); //获取设备树中SPI的IO资源
  420. xspi->regs = devm_ioremap_resource(&pdev->dev, res); //对寄存器进行映射
  421. if (IS_ERR(xspi->regs)) {
  422. ret = PTR_ERR(xspi->regs);
  423. goto remove_master;
  424. }
  425. xspi->pclk = devm_clk_get(&pdev->dev, "pclk"); //获取ARB时钟,用作配置寄存器
  426. if (IS_ERR(xspi->pclk)) {
  427. dev_err(&pdev->dev, "pclk clock not found.\n");
  428. ret = PTR_ERR(xspi->pclk);
  429. goto remove_master;
  430. }
  431. xspi->ref_clk = devm_clk_get(&pdev->dev, "ref_clk"); //获取参考时钟,用作波特率
  432. if (IS_ERR(xspi->ref_clk)) {
  433. dev_err(&pdev->dev, "ref_clk clock not found.\n");
  434. ret = PTR_ERR(xspi->ref_clk);
  435. goto remove_master;
  436. }
  437. ret = clk_prepare_enable(xspi->pclk); //使能APB时钟
  438. if (ret) {
  439. dev_err(&pdev->dev, "Unable to enable APB clock.\n");
  440. goto remove_master;
  441. }
  442. ret = clk_prepare_enable(xspi->ref_clk); //使能参考时钟
  443. if (ret) {
  444. dev_err(&pdev->dev, "Unable to enable device clock.\n");
  445. goto clk_dis_apb;
  446. }
  447. pm_runtime_use_autosuspend(&pdev->dev);
  448. pm_runtime_set_autosuspend_delay(&pdev->dev, SPI_AUTOSUSPEND_TIMEOUT);
  449. pm_runtime_set_active(&pdev->dev);
  450. pm_runtime_enable(&pdev->dev);
  451. ret = of_property_read_u32(pdev->dev.of_node, "num-cs", &num_cs);//获取设备树中num-cs资源
  452. if (ret < 0)
  453. master->num_chipselect = CDNS_SPI_DEFAULT_NUM_CS;
  454. else
  455. master->num_chipselect = num_cs;
  456. ret = of_property_read_u32(pdev->dev.of_node, "is-decoded-cs",//获取设备树中is-decoded-cs资源
  457. &xspi->is_decoded_cs);
  458. if (ret < 0)
  459. xspi->is_decoded_cs = 0;
  460. /* SPI controller initializations */
  461. cdns_spi_init_hw(xspi);
  462. pm_runtime_mark_last_busy(&pdev->dev);
  463. pm_runtime_put_autosuspend(&pdev->dev);
  464. irq = platform_get_irq(pdev, 0);//获取设备树中中断资源
  465. if (irq <= 0) {
  466. ret = -ENXIO;
  467. dev_err(&pdev->dev, "irq number is invalid\n");
  468. goto clk_dis_all;
  469. }
  470. ret = devm_request_irq(&pdev->dev, irq, cdns_spi_irq,//向系统申请中断
  471. 0, pdev->name, master);
  472. if (ret != 0) {
  473. ret = -ENXIO;
  474. dev_err(&pdev->dev, "request_irq failed\n");
  475. goto clk_dis_all;
  476. }
  477. master->prepare_transfer_hardware = cdns_prepare_transfer_hardware; //使能SPI寄存器
  478. master->prepare_message = cdns_prepare_message; //设置SPI的时钟和相位
  479. master->transfer_one = cdns_transfer_one; //设置波特率
  480. master->unprepare_transfer_hardware = cdns_unprepare_transfer_hardware; //关闭SPI寄存器
  481. master->set_cs = cdns_spi_chipselect; //片选
  482. master->auto_runtime_pm = true;
  483. master->mode_bits = SPI_CPOL | SPI_CPHA;
  484. /* Set to default valid value */
  485. master->max_speed_hz = clk_get_rate(xspi->ref_clk) / 4; // 设置波特率、字长默认值
  486. xspi->speed_hz = master->max_speed_hz;
  487. master->bits_per_word_mask = SPI_BPW_MASK(8);
  488. ret = spi_register_master(master); //向系统注册SPI主机控制器
  489. if (ret) {
  490. dev_err(&pdev->dev, "spi_register_master failed\n");
  491. goto clk_dis_all;
  492. }
  493. return ret;
  494. clk_dis_all:
  495. pm_runtime_set_suspended(&pdev->dev);
  496. pm_runtime_disable(&pdev->dev);
  497. clk_disable_unprepare(xspi->ref_clk);
  498. clk_dis_apb:
  499. clk_disable_unprepare(xspi->pclk);
  500. remove_master:
  501. spi_master_put(master);
  502. return ret;
  503. }
  504. /**
  505. * cdns_spi_remove - Remove method for the SPI driver
  506. * @pdev: Pointer to the platform_device structure
  507. *
  508. * This function is called if a device is physically removed from the system or
  509. * if the driver module is being unloaded. It frees all resources allocated to
  510. * the device.
  511. *
  512. * Return: 0 on success and error value on error
  513. */
  514. static int cdns_spi_remove(struct platform_device *pdev)/*cadence_spi驱动移除*/
  515. {
  516. struct spi_master *master = platform_get_drvdata(pdev);
  517. struct cdns_spi *xspi = spi_master_get_devdata(master);
  518. cdns_spi_write(xspi, CDNS_SPI_ER, CDNS_SPI_ER_DISABLE);
  519. clk_disable_unprepare(xspi->ref_clk);
  520. clk_disable_unprepare(xspi->pclk);
  521. pm_runtime_set_suspended(&pdev->dev);
  522. pm_runtime_disable(&pdev->dev);
  523. spi_unregister_master(master);
  524. return 0;
  525. }
  526. /**
  527. * cdns_spi_suspend - Suspend method for the SPI driver
  528. * @dev: Address of the platform_device structure
  529. *
  530. * This function disables the SPI controller and
  531. * changes the driver state to "suspend"
  532. *
  533. * Return: 0 on success and error value on error
  534. */
  535. static int __maybe_unused cdns_spi_suspend(struct device *dev)/*cadence_spi驱动暂停*/
  536. {
  537. struct platform_device *pdev = to_platform_device(dev);
  538. struct spi_master *master = platform_get_drvdata(pdev);
  539. return spi_master_suspend(master);
  540. }
  541. /**
  542. * cdns_spi_resume - Resume method for the SPI driver
  543. * @dev: Address of the platform_device structure
  544. *
  545. * This function changes the driver state to "ready"
  546. *
  547. * Return: 0 on success and error value on error
  548. */
  549. static int __maybe_unused cdns_spi_resume(struct device *dev)/*cadence_spi驱动恢复*/
  550. {
  551. struct platform_device *pdev = to_platform_device(dev);
  552. struct spi_master *master = platform_get_drvdata(pdev);
  553. struct cdns_spi *xspi = spi_master_get_devdata(master);
  554. cdns_spi_init_hw(xspi);
  555. return spi_master_resume(master);
  556. }
  557. /**
  558. * cdns_spi_runtime_resume - Runtime resume method for the SPI driver
  559. * @dev: Address of the platform_device structure
  560. *
  561. * This function enables the clocks
  562. *
  563. * Return: 0 on success and error value on error
  564. */
  565. static int __maybe_unused cnds_runtime_resume(struct device *dev)/*SPI驱动程序的运行时恢复*/
  566. {
  567. struct spi_master *master = dev_get_drvdata(dev);
  568. struct cdns_spi *xspi = spi_master_get_devdata(master);
  569. int ret;
  570. ret = clk_prepare_enable(xspi->pclk);
  571. if (ret) {
  572. dev_err(dev, "Cannot enable APB clock.\n");
  573. return ret;
  574. }
  575. ret = clk_prepare_enable(xspi->ref_clk);
  576. if (ret) {
  577. dev_err(dev, "Cannot enable device clock.\n");
  578. clk_disable(xspi->pclk);
  579. return ret;
  580. }
  581. return 0;
  582. }
  583. /**
  584. * cdns_spi_runtime_suspend - Runtime suspend method for the SPI driver
  585. * @dev: Address of the platform_device structure
  586. *
  587. * This function disables the clocks
  588. *
  589. * Return: Always 0
  590. */
  591. static int __maybe_unused cnds_runtime_suspend(struct device *dev)/*SPI驱动程序的运行时挂起*/
  592. {
  593. struct spi_master *master = dev_get_drvdata(dev);
  594. struct cdns_spi *xspi = spi_master_get_devdata(master);
  595. clk_disable_unprepare(xspi->ref_clk);
  596. clk_disable_unprepare(xspi->pclk);
  597. return 0;
  598. }
  599. static const struct dev_pm_ops cdns_spi_dev_pm_ops = {
  600. SET_RUNTIME_PM_OPS(cnds_runtime_suspend,
  601. cnds_runtime_resume, NULL)
  602. SET_SYSTEM_SLEEP_PM_OPS(cdns_spi_suspend, cdns_spi_resume)
  603. };
  604. static const struct of_device_id cdns_spi_of_match[] = {
  605. { .compatible = "xlnx,zynq-spi-r1p6" },
  606. { .compatible = "cdns,spi-r1p6" },
  607. { /* end of table */ }
  608. };
  609. MODULE_DEVICE_TABLE(of, cdns_spi_of_match);
  610. /* cdns_spi_driver - This structure defines the SPI subsystem platform driver */
  611. static struct platform_driver cdns_spi_driver = {
  612. .probe = cdns_spi_probe,
  613. .remove = cdns_spi_remove,
  614. .driver = {
  615. .name = CDNS_SPI_NAME,
  616. .of_match_table = cdns_spi_of_match,
  617. .pm = &cdns_spi_dev_pm_ops,
  618. },
  619. };
  620. module_platform_driver(cdns_spi_driver);
  621. MODULE_AUTHOR("Xilinx, Inc.");
  622. MODULE_DESCRIPTION("Cadence SPI driver");
  623. MODULE_LICENSE("GPL");

spi-cadence.c文件中包含有548行代码,主要作用就是配置SPI主机控制器的,我们可以顺着module_platform_driver(cdns_spi_driver)往下看:

       在我们看完上面两个c文件后,明显能看到这两个文件并没有直接调用或者交互的关系,但都跟spi.c有调用关系,所以很显然,spi.c的作用就是让spidev和spi-cadence能够关联起来。

       我们可以想一想,这个spi.c需要做哪些工作呢?

spidev.c注册了SPI设备,构造了file_operation结构体
spi-cadence.c注册了主机控制器,初始化了主机控制器的硬件
spi.c???

       联想下平台系统驱动的框架:设备-驱动-总线模型,因为SPI总线也是由平台总线派生出来的,所以必然也会遵循这个架构。那么是不是就可以猜测spi.c的作用就是注册SPI总线呢?当然spi.c还有一个作用就是怎么将spidev和spi-cadence连接起来,我们来看看spi.c到底干了啥?

  1. static int __init spi_init(void)
  2. {
  3. int status;
  4. buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
  5. if (!buf) {
  6. status = -ENOMEM;
  7. goto err0;
  8. }
  9. status = bus_register(&spi_bus_type); /*注册spi总线*/
  10. if (status < 0)
  11. goto err1;
  12. status = class_register(&spi_master_class); /*将spi_master注册到内核中*/
  13. if (status < 0)
  14. goto err2;
  15. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  16. WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
  17. if (IS_ENABLED(CONFIG_ACPI))
  18. WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
  19. return 0;
  20. err2:
  21. bus_unregister(&spi_bus_type);
  22. err1:
  23. kfree(buf);
  24. buf = NULL;
  25. err0:
  26. return status;
  27. }
  28. /* board_info is normally registered in arch_initcall(),
  29. * but even essential drivers wait till later
  30. *
  31. * REVISIT only boardinfo really needs static linking. the rest (device and
  32. * driver registration) _could_ be dynamically linked (modular) ... costs
  33. * include needing to have boardinfo data structures be much more public.
  34. */
  35. postcore_initcall(spi_init);//在moudule_init之前加载

        上面这段代码的作用就是向内核注册SPI总线,以及向内核注册spi的主机控制器,只有在spi.c中先注册了主机控制器,在spi-cadence.c中才可以向内核申请一个SPI主机控制器,以及向内核注册;显然,spi-cadence.c与spi.c的联系就建立起来了。而spidev.c与spi.c的联系比较复杂,这块内容留着后面再分析吧。

那么,在我们看完这三个文件后,基本上可以梳理下SPI的驱动是怎么实现的了。

第一步:向内核注册SPI总线以及SPI主机控制器;

第二步:向内核申请一个SPI主机控制器的空间,注册我们要用的主机控制器;

第三步:向内核注册SPI设备,以及构造file_operation结构体;

有了这三步,用户空间就可以通过open、write、read、ioctl函数来操作字符设备spidev了。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/979657
推荐阅读
相关标签
  

闽ICP备14008679号