1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Simple synchronous userspace interface to SPI devices
5 * Copyright (C) 2006 SWAPP
6 * Andrea Paterniani <a.paterniani@swapp-eng.it>
7 * Copyright (C) 2007 David Brownell (simplification, cleanup)
10 #include <linux/init.h>
11 #include <linux/ioctl.h>
13 #include <linux/device.h>
14 #include <linux/err.h>
15 #include <linux/list.h>
16 #include <linux/errno.h>
17 #include <linux/mod_devicetable.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/property.h>
21 #include <linux/slab.h>
22 #include <linux/compat.h>
24 #include <linux/spi/spi.h>
25 #include <linux/spi/spidev.h>
27 #include <linux/uaccess.h>
31 * This supports access to SPI devices using normal userspace I/O calls.
32 * Note that while traditional UNIX/POSIX I/O semantics are half duplex,
33 * and often mask message boundaries, full SPI support requires full duplex
34 * transfers. There are several kinds of internal message boundaries to
35 * handle chipselect management and other protocol options.
37 * SPI has a character major number assigned. We allocate minor numbers
38 * dynamically using a bitmask. You must use hotplug tools, such as udev
39 * (or mdev with busybox) to create and destroy the /dev/spidevB.C device
40 * nodes, since there is no fixed association of minor numbers with any
41 * particular SPI bus or device.
43 #define SPIDEV_MAJOR 153 /* assigned */
44 #define N_SPI_MINORS 32 /* ... up to 256 */
46 static DECLARE_BITMAP(minors, N_SPI_MINORS);
48 static_assert(N_SPI_MINORS > 0 && N_SPI_MINORS <= 256);
50 /* Bit masks for spi_device.mode management. Note that incorrect
51 * settings for some settings can cause *lots* of trouble for other
52 * devices on a shared bus:
54 * - CS_HIGH ... this device will be active when it shouldn't be
55 * - 3WIRE ... when active, it won't behave as it should
56 * - NO_CS ... there will be no explicit message boundaries; this
57 * is completely incompatible with the shared bus model
58 * - READY ... transfers may proceed when they shouldn't.
60 * REVISIT should changing those flags be privileged?
62 #define SPI_MODE_MASK (SPI_MODE_X_MASK | SPI_CS_HIGH \
63 | SPI_LSB_FIRST | SPI_3WIRE | SPI_LOOP \
64 | SPI_NO_CS | SPI_READY | SPI_TX_DUAL \
65 | SPI_TX_QUAD | SPI_TX_OCTAL | SPI_RX_DUAL \
66 | SPI_RX_QUAD | SPI_RX_OCTAL \
72 struct spi_device *spi;
73 struct list_head device_entry;
75 /* TX/RX buffers are NULL unless this device is open (users > 0) */
76 struct mutex buf_lock;
83 static LIST_HEAD(device_list);
84 static DEFINE_MUTEX(device_list_lock);
86 static unsigned bufsiz = 4096;
87 module_param(bufsiz, uint, S_IRUGO);
88 MODULE_PARM_DESC(bufsiz, "data bytes in biggest supported SPI message");
90 /*-------------------------------------------------------------------------*/
93 spidev_sync(struct spidev_data *spidev, struct spi_message *message)
96 struct spi_device *spi;
98 spin_lock_irq(&spidev->spi_lock);
100 spin_unlock_irq(&spidev->spi_lock);
105 status = spi_sync(spi, message);
108 status = message->actual_length;
113 static inline ssize_t
114 spidev_sync_write(struct spidev_data *spidev, size_t len)
116 struct spi_transfer t = {
117 .tx_buf = spidev->tx_buffer,
119 .speed_hz = spidev->speed_hz,
121 struct spi_message m;
123 spi_message_init(&m);
124 spi_message_add_tail(&t, &m);
125 return spidev_sync(spidev, &m);
128 static inline ssize_t
129 spidev_sync_read(struct spidev_data *spidev, size_t len)
131 struct spi_transfer t = {
132 .rx_buf = spidev->rx_buffer,
134 .speed_hz = spidev->speed_hz,
136 struct spi_message m;
138 spi_message_init(&m);
139 spi_message_add_tail(&t, &m);
140 return spidev_sync(spidev, &m);
143 /*-------------------------------------------------------------------------*/
145 /* Read-only message with current device setup */
147 spidev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
149 struct spidev_data *spidev;
152 /* chipselect only toggles at start or end of operation */
156 spidev = filp->private_data;
158 mutex_lock(&spidev->buf_lock);
159 status = spidev_sync_read(spidev, count);
161 unsigned long missing;
163 missing = copy_to_user(buf, spidev->rx_buffer, status);
164 if (missing == status)
167 status = status - missing;
169 mutex_unlock(&spidev->buf_lock);
174 /* Write-only message with current device setup */
176 spidev_write(struct file *filp, const char __user *buf,
177 size_t count, loff_t *f_pos)
179 struct spidev_data *spidev;
181 unsigned long missing;
183 /* chipselect only toggles at start or end of operation */
187 spidev = filp->private_data;
189 mutex_lock(&spidev->buf_lock);
190 missing = copy_from_user(spidev->tx_buffer, buf, count);
192 status = spidev_sync_write(spidev, count);
195 mutex_unlock(&spidev->buf_lock);
200 static int spidev_message(struct spidev_data *spidev,
201 struct spi_ioc_transfer *u_xfers, unsigned n_xfers)
203 struct spi_message msg;
204 struct spi_transfer *k_xfers;
205 struct spi_transfer *k_tmp;
206 struct spi_ioc_transfer *u_tmp;
207 unsigned n, total, tx_total, rx_total;
209 int status = -EFAULT;
211 spi_message_init(&msg);
212 k_xfers = kcalloc(n_xfers, sizeof(*k_tmp), GFP_KERNEL);
216 /* Construct spi_message, copying any tx data to bounce buffer.
217 * We walk the array of user-provided transfers, using each one
218 * to initialize a kernel version of the same transfer.
220 tx_buf = spidev->tx_buffer;
221 rx_buf = spidev->rx_buffer;
225 for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
227 n--, k_tmp++, u_tmp++) {
228 /* Ensure that also following allocations from rx_buf/tx_buf will meet
229 * DMA alignment requirements.
231 unsigned int len_aligned = ALIGN(u_tmp->len, ARCH_KMALLOC_MINALIGN);
233 k_tmp->len = u_tmp->len;
236 /* Since the function returns the total length of transfers
237 * on success, restrict the total to positive int values to
238 * avoid the return value looking like an error. Also check
239 * each transfer length to avoid arithmetic overflow.
241 if (total > INT_MAX || k_tmp->len > INT_MAX) {
247 /* this transfer needs space in RX bounce buffer */
248 rx_total += len_aligned;
249 if (rx_total > bufsiz) {
253 k_tmp->rx_buf = rx_buf;
254 rx_buf += len_aligned;
257 /* this transfer needs space in TX bounce buffer */
258 tx_total += len_aligned;
259 if (tx_total > bufsiz) {
263 k_tmp->tx_buf = tx_buf;
264 if (copy_from_user(tx_buf, (const u8 __user *)
265 (uintptr_t) u_tmp->tx_buf,
268 tx_buf += len_aligned;
271 k_tmp->cs_change = !!u_tmp->cs_change;
272 k_tmp->tx_nbits = u_tmp->tx_nbits;
273 k_tmp->rx_nbits = u_tmp->rx_nbits;
274 k_tmp->bits_per_word = u_tmp->bits_per_word;
275 k_tmp->delay.value = u_tmp->delay_usecs;
276 k_tmp->delay.unit = SPI_DELAY_UNIT_USECS;
277 k_tmp->speed_hz = u_tmp->speed_hz;
278 k_tmp->word_delay.value = u_tmp->word_delay_usecs;
279 k_tmp->word_delay.unit = SPI_DELAY_UNIT_USECS;
280 if (!k_tmp->speed_hz)
281 k_tmp->speed_hz = spidev->speed_hz;
283 dev_dbg(&spidev->spi->dev,
284 " xfer len %u %s%s%s%dbits %u usec %u usec %uHz\n",
286 k_tmp->rx_buf ? "rx " : "",
287 k_tmp->tx_buf ? "tx " : "",
288 k_tmp->cs_change ? "cs " : "",
289 k_tmp->bits_per_word ? : spidev->spi->bits_per_word,
291 k_tmp->word_delay.value,
292 k_tmp->speed_hz ? : spidev->spi->max_speed_hz);
294 spi_message_add_tail(k_tmp, &msg);
297 status = spidev_sync(spidev, &msg);
301 /* copy any rx data out of bounce buffer */
302 for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
304 n--, k_tmp++, u_tmp++) {
306 if (copy_to_user((u8 __user *)
307 (uintptr_t) u_tmp->rx_buf, k_tmp->rx_buf,
321 static struct spi_ioc_transfer *
322 spidev_get_ioc_message(unsigned int cmd, struct spi_ioc_transfer __user *u_ioc,
327 /* Check type, command number and direction */
328 if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC
329 || _IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0))
330 || _IOC_DIR(cmd) != _IOC_WRITE)
331 return ERR_PTR(-ENOTTY);
333 tmp = _IOC_SIZE(cmd);
334 if ((tmp % sizeof(struct spi_ioc_transfer)) != 0)
335 return ERR_PTR(-EINVAL);
336 *n_ioc = tmp / sizeof(struct spi_ioc_transfer);
340 /* copy into scratch area */
341 return memdup_user(u_ioc, tmp);
345 spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
348 struct spidev_data *spidev;
349 struct spi_device *spi;
352 struct spi_ioc_transfer *ioc;
354 /* Check type and command number */
355 if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC)
358 /* guard against device removal before, or while,
359 * we issue this ioctl.
361 spidev = filp->private_data;
362 spin_lock_irq(&spidev->spi_lock);
363 spi = spi_dev_get(spidev->spi);
364 spin_unlock_irq(&spidev->spi_lock);
369 /* use the buffer lock here for triple duty:
370 * - prevent I/O (from us) so calling spi_setup() is safe;
371 * - prevent concurrent SPI_IOC_WR_* from morphing
372 * data fields while SPI_IOC_RD_* reads them;
373 * - SPI_IOC_MESSAGE needs the buffer locked "normally".
375 mutex_lock(&spidev->buf_lock);
379 case SPI_IOC_RD_MODE:
380 retval = put_user(spi->mode & SPI_MODE_MASK,
383 case SPI_IOC_RD_MODE32:
384 retval = put_user(spi->mode & SPI_MODE_MASK,
385 (__u32 __user *)arg);
387 case SPI_IOC_RD_LSB_FIRST:
388 retval = put_user((spi->mode & SPI_LSB_FIRST) ? 1 : 0,
391 case SPI_IOC_RD_BITS_PER_WORD:
392 retval = put_user(spi->bits_per_word, (__u8 __user *)arg);
394 case SPI_IOC_RD_MAX_SPEED_HZ:
395 retval = put_user(spidev->speed_hz, (__u32 __user *)arg);
399 case SPI_IOC_WR_MODE:
400 case SPI_IOC_WR_MODE32:
401 if (cmd == SPI_IOC_WR_MODE)
402 retval = get_user(tmp, (u8 __user *)arg);
404 retval = get_user(tmp, (u32 __user *)arg);
406 struct spi_controller *ctlr = spi->controller;
407 u32 save = spi->mode;
409 if (tmp & ~SPI_MODE_MASK) {
414 if (ctlr->use_gpio_descriptors && ctlr->cs_gpiods &&
415 ctlr->cs_gpiods[spi->chip_select])
418 tmp |= spi->mode & ~SPI_MODE_MASK;
419 spi->mode = tmp & SPI_MODE_USER_MASK;
420 retval = spi_setup(spi);
424 dev_dbg(&spi->dev, "spi mode %x\n", tmp);
427 case SPI_IOC_WR_LSB_FIRST:
428 retval = get_user(tmp, (__u8 __user *)arg);
430 u32 save = spi->mode;
433 spi->mode |= SPI_LSB_FIRST;
435 spi->mode &= ~SPI_LSB_FIRST;
436 retval = spi_setup(spi);
440 dev_dbg(&spi->dev, "%csb first\n",
444 case SPI_IOC_WR_BITS_PER_WORD:
445 retval = get_user(tmp, (__u8 __user *)arg);
447 u8 save = spi->bits_per_word;
449 spi->bits_per_word = tmp;
450 retval = spi_setup(spi);
452 spi->bits_per_word = save;
454 dev_dbg(&spi->dev, "%d bits per word\n", tmp);
457 case SPI_IOC_WR_MAX_SPEED_HZ: {
460 retval = get_user(tmp, (__u32 __user *)arg);
468 save = spi->max_speed_hz;
470 spi->max_speed_hz = tmp;
471 retval = spi_setup(spi);
473 spidev->speed_hz = tmp;
474 dev_dbg(&spi->dev, "%d Hz (max)\n", spidev->speed_hz);
477 spi->max_speed_hz = save;
481 /* segmented and/or full-duplex I/O request */
482 /* Check message and copy into scratch area */
483 ioc = spidev_get_ioc_message(cmd,
484 (struct spi_ioc_transfer __user *)arg, &n_ioc);
486 retval = PTR_ERR(ioc);
490 break; /* n_ioc is also 0 */
492 /* translate to spi_message, execute */
493 retval = spidev_message(spidev, ioc, n_ioc);
498 mutex_unlock(&spidev->buf_lock);
505 spidev_compat_ioc_message(struct file *filp, unsigned int cmd,
508 struct spi_ioc_transfer __user *u_ioc;
510 struct spidev_data *spidev;
511 struct spi_device *spi;
513 struct spi_ioc_transfer *ioc;
515 u_ioc = (struct spi_ioc_transfer __user *) compat_ptr(arg);
517 /* guard against device removal before, or while,
518 * we issue this ioctl.
520 spidev = filp->private_data;
521 spin_lock_irq(&spidev->spi_lock);
522 spi = spi_dev_get(spidev->spi);
523 spin_unlock_irq(&spidev->spi_lock);
528 /* SPI_IOC_MESSAGE needs the buffer locked "normally" */
529 mutex_lock(&spidev->buf_lock);
531 /* Check message and copy into scratch area */
532 ioc = spidev_get_ioc_message(cmd, u_ioc, &n_ioc);
534 retval = PTR_ERR(ioc);
538 goto done; /* n_ioc is also 0 */
540 /* Convert buffer pointers */
541 for (n = 0; n < n_ioc; n++) {
542 ioc[n].rx_buf = (uintptr_t) compat_ptr(ioc[n].rx_buf);
543 ioc[n].tx_buf = (uintptr_t) compat_ptr(ioc[n].tx_buf);
546 /* translate to spi_message, execute */
547 retval = spidev_message(spidev, ioc, n_ioc);
551 mutex_unlock(&spidev->buf_lock);
557 spidev_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
559 if (_IOC_TYPE(cmd) == SPI_IOC_MAGIC
560 && _IOC_NR(cmd) == _IOC_NR(SPI_IOC_MESSAGE(0))
561 && _IOC_DIR(cmd) == _IOC_WRITE)
562 return spidev_compat_ioc_message(filp, cmd, arg);
564 return spidev_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
567 #define spidev_compat_ioctl NULL
568 #endif /* CONFIG_COMPAT */
570 static int spidev_open(struct inode *inode, struct file *filp)
572 struct spidev_data *spidev = NULL, *iter;
575 mutex_lock(&device_list_lock);
577 list_for_each_entry(iter, &device_list, device_entry) {
578 if (iter->devt == inode->i_rdev) {
586 pr_debug("spidev: nothing for minor %d\n", iminor(inode));
590 if (!spidev->tx_buffer) {
591 spidev->tx_buffer = kmalloc(bufsiz, GFP_KERNEL);
592 if (!spidev->tx_buffer) {
593 dev_dbg(&spidev->spi->dev, "open/ENOMEM\n");
599 if (!spidev->rx_buffer) {
600 spidev->rx_buffer = kmalloc(bufsiz, GFP_KERNEL);
601 if (!spidev->rx_buffer) {
602 dev_dbg(&spidev->spi->dev, "open/ENOMEM\n");
604 goto err_alloc_rx_buf;
609 filp->private_data = spidev;
610 stream_open(inode, filp);
612 mutex_unlock(&device_list_lock);
616 kfree(spidev->tx_buffer);
617 spidev->tx_buffer = NULL;
619 mutex_unlock(&device_list_lock);
623 static int spidev_release(struct inode *inode, struct file *filp)
625 struct spidev_data *spidev;
628 mutex_lock(&device_list_lock);
629 spidev = filp->private_data;
630 filp->private_data = NULL;
632 spin_lock_irq(&spidev->spi_lock);
633 /* ... after we unbound from the underlying device? */
634 dofree = (spidev->spi == NULL);
635 spin_unlock_irq(&spidev->spi_lock);
639 if (!spidev->users) {
641 kfree(spidev->tx_buffer);
642 spidev->tx_buffer = NULL;
644 kfree(spidev->rx_buffer);
645 spidev->rx_buffer = NULL;
650 spidev->speed_hz = spidev->spi->max_speed_hz;
652 #ifdef CONFIG_SPI_SLAVE
654 spi_slave_abort(spidev->spi);
656 mutex_unlock(&device_list_lock);
661 static const struct file_operations spidev_fops = {
662 .owner = THIS_MODULE,
663 /* REVISIT switch to aio primitives, so that userspace
664 * gets more complete API coverage. It'll simplify things
665 * too, except for the locking.
667 .write = spidev_write,
669 .unlocked_ioctl = spidev_ioctl,
670 .compat_ioctl = spidev_compat_ioctl,
672 .release = spidev_release,
676 /*-------------------------------------------------------------------------*/
678 /* The main reason to have this class is to make mdev/udev create the
679 * /dev/spidevB.C character device nodes exposing our userspace API.
680 * It also simplifies memory management.
683 static struct class *spidev_class;
685 static const struct spi_device_id spidev_spi_ids[] = {
686 { .name = "dh2228fv" },
687 { .name = "ltc2488" },
688 { .name = "sx1301" },
690 { .name = "dhcom-board" },
691 { .name = "m53cpld" },
692 { .name = "spi-petra" },
693 { .name = "spi-authenta" },
696 MODULE_DEVICE_TABLE(spi, spidev_spi_ids);
699 * spidev should never be referenced in DT without a specific compatible string,
700 * it is a Linux implementation thing rather than a description of the hardware.
702 static int spidev_of_check(struct device *dev)
704 if (device_property_match_string(dev, "compatible", "spidev") < 0)
707 dev_err(dev, "spidev listed directly in DT is not supported\n");
711 static const struct of_device_id spidev_dt_ids[] = {
712 { .compatible = "rohm,dh2228fv", .data = &spidev_of_check },
713 { .compatible = "lineartechnology,ltc2488", .data = &spidev_of_check },
714 { .compatible = "semtech,sx1301", .data = &spidev_of_check },
715 { .compatible = "lwn,bk4", .data = &spidev_of_check },
716 { .compatible = "dh,dhcom-board", .data = &spidev_of_check },
717 { .compatible = "menlo,m53cpld", .data = &spidev_of_check },
718 { .compatible = "cisco,spi-petra", .data = &spidev_of_check },
719 { .compatible = "micron,spi-authenta", .data = &spidev_of_check },
722 MODULE_DEVICE_TABLE(of, spidev_dt_ids);
724 /* Dummy SPI devices not to be used in production systems */
725 static int spidev_acpi_check(struct device *dev)
727 dev_warn(dev, "do not use this driver in production systems!\n");
731 static const struct acpi_device_id spidev_acpi_ids[] = {
733 * The ACPI SPT000* devices are only meant for development and
734 * testing. Systems used in production should have a proper ACPI
735 * description of the connected peripheral and they should also use
736 * a proper driver instead of poking directly to the SPI bus.
738 { "SPT0001", (kernel_ulong_t)&spidev_acpi_check },
739 { "SPT0002", (kernel_ulong_t)&spidev_acpi_check },
740 { "SPT0003", (kernel_ulong_t)&spidev_acpi_check },
743 MODULE_DEVICE_TABLE(acpi, spidev_acpi_ids);
745 /*-------------------------------------------------------------------------*/
747 static int spidev_probe(struct spi_device *spi)
749 int (*match)(struct device *dev);
750 struct spidev_data *spidev;
754 match = device_get_match_data(&spi->dev);
756 status = match(&spi->dev);
761 /* Allocate driver data */
762 spidev = kzalloc(sizeof(*spidev), GFP_KERNEL);
766 /* Initialize the driver data */
768 spin_lock_init(&spidev->spi_lock);
769 mutex_init(&spidev->buf_lock);
771 INIT_LIST_HEAD(&spidev->device_entry);
773 /* If we can allocate a minor number, hook up this device.
774 * Reusing minors is fine so long as udev or mdev is working.
776 mutex_lock(&device_list_lock);
777 minor = find_first_zero_bit(minors, N_SPI_MINORS);
778 if (minor < N_SPI_MINORS) {
781 spidev->devt = MKDEV(SPIDEV_MAJOR, minor);
782 dev = device_create(spidev_class, &spi->dev, spidev->devt,
783 spidev, "spidev%d.%d",
784 spi->master->bus_num, spi->chip_select);
785 status = PTR_ERR_OR_ZERO(dev);
787 dev_dbg(&spi->dev, "no minor number available!\n");
791 set_bit(minor, minors);
792 list_add(&spidev->device_entry, &device_list);
794 mutex_unlock(&device_list_lock);
796 spidev->speed_hz = spi->max_speed_hz;
799 spi_set_drvdata(spi, spidev);
806 static void spidev_remove(struct spi_device *spi)
808 struct spidev_data *spidev = spi_get_drvdata(spi);
810 /* prevent new opens */
811 mutex_lock(&device_list_lock);
812 /* make sure ops on existing fds can abort cleanly */
813 spin_lock_irq(&spidev->spi_lock);
815 spin_unlock_irq(&spidev->spi_lock);
817 list_del(&spidev->device_entry);
818 device_destroy(spidev_class, spidev->devt);
819 clear_bit(MINOR(spidev->devt), minors);
820 if (spidev->users == 0)
822 mutex_unlock(&device_list_lock);
825 static struct spi_driver spidev_spi_driver = {
828 .of_match_table = spidev_dt_ids,
829 .acpi_match_table = spidev_acpi_ids,
831 .probe = spidev_probe,
832 .remove = spidev_remove,
833 .id_table = spidev_spi_ids,
835 /* NOTE: suspend/resume methods are not necessary here.
836 * We don't do anything except pass the requests to/from
837 * the underlying controller. The refrigerator handles
838 * most issues; the controller driver handles the rest.
842 /*-------------------------------------------------------------------------*/
844 static int __init spidev_init(void)
848 /* Claim our 256 reserved device numbers. Then register a class
849 * that will key udev/mdev to add/remove /dev nodes. Last, register
850 * the driver which manages those device numbers.
852 status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops);
856 spidev_class = class_create(THIS_MODULE, "spidev");
857 if (IS_ERR(spidev_class)) {
858 unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
859 return PTR_ERR(spidev_class);
862 status = spi_register_driver(&spidev_spi_driver);
864 class_destroy(spidev_class);
865 unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
869 module_init(spidev_init);
871 static void __exit spidev_exit(void)
873 spi_unregister_driver(&spidev_spi_driver);
874 class_destroy(spidev_class);
875 unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
877 module_exit(spidev_exit);
879 MODULE_AUTHOR("Andrea Paterniani, <a.paterniani@swapp-eng.it>");
880 MODULE_DESCRIPTION("User mode SPI device interface");
881 MODULE_LICENSE("GPL");
882 MODULE_ALIAS("spi:spidev");