blob: a93bdab9704950a5a2e60fc512f2718f3f391f9e [file] [log] [blame]
yuezonghe824eb0c2024-06-27 02:32:26 -07001/*
2 * Simple synchronous userspace interface to SPI devices
3 *
4 * Copyright (C) 2006 SWAPP
5 * Andrea Paterniani <a.paterniani@swapp-eng.it>
6 * Copyright (C) 2007 David Brownell (simplification, cleanup)
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23#include <linux/init.h>
24#include <linux/module.h>
25#include <linux/ioctl.h>
26#include <linux/fs.h>
27#include <linux/device.h>
28#include <linux/err.h>
29#include <linux/list.h>
30#include <linux/errno.h>
31#include <linux/mutex.h>
32#include <linux/slab.h>
33#include <linux/compat.h>
34
35#include <linux/spi/spi.h>
36#include <linux/spi/spidev.h>
37
38#include <asm/uaccess.h>
39
40
41/*
42 * This supports access to SPI devices using normal userspace I/O calls.
43 * Note that while traditional UNIX/POSIX I/O semantics are half duplex,
44 * and often mask message boundaries, full SPI support requires full duplex
45 * transfers. There are several kinds of internal message boundaries to
46 * handle chipselect management and other protocol options.
47 *
48 * SPI has a character major number assigned. We allocate minor numbers
49 * dynamically using a bitmask. You must use hotplug tools, such as udev
50 * (or mdev with busybox) to create and destroy the /dev/spidevB.C device
51 * nodes, since there is no fixed association of minor numbers with any
52 * particular SPI bus or device.
53 */
54#define SPIDEV_MAJOR 153 /* assigned */
55#define N_SPI_MINORS 32 /* ... up to 256 */
56
57static DECLARE_BITMAP(minors, N_SPI_MINORS);
58
59
60/* Bit masks for spi_device.mode management. Note that incorrect
61 * settings for some settings can cause *lots* of trouble for other
62 * devices on a shared bus:
63 *
64 * - CS_HIGH ... this device will be active when it shouldn't be
65 * - 3WIRE ... when active, it won't behave as it should
66 * - NO_CS ... there will be no explicit message boundaries; this
67 * is completely incompatible with the shared bus model
68 * - READY ... transfers may proceed when they shouldn't.
69 *
70 * REVISIT should changing those flags be privileged?
71 */
72#define SPI_MODE_MASK (SPI_CPHA | SPI_CPOL | SPI_CS_HIGH \
73 | SPI_LSB_FIRST | SPI_3WIRE | SPI_LOOP \
74 | SPI_NO_CS | SPI_READY)
75
76struct spidev_data {
77 dev_t devt;
78 spinlock_t spi_lock;
79 struct spi_device *spi;
80 struct list_head device_entry;
81
82 /* buffer is NULL unless this device is open (users > 0) */
83 struct mutex buf_lock;
84 unsigned users;
85 u8 *buffer;
86};
87
88static LIST_HEAD(device_list);
89static DEFINE_MUTEX(device_list_lock);
90
91static unsigned bufsiz = 4096;
92module_param(bufsiz, uint, S_IRUGO);
93MODULE_PARM_DESC(bufsiz, "data bytes in biggest supported SPI message");
94
95/*-------------------------------------------------------------------------*/
96
97/*
98 * We can't use the standard synchronous wrappers for file I/O; we
99 * need to protect against async removal of the underlying spi_device.
100 */
101static void spidev_complete(void *arg)
102{
103 complete(arg);
104}
105
106static ssize_t
107spidev_sync(struct spidev_data *spidev, struct spi_message *message)
108{
109 DECLARE_COMPLETION_ONSTACK(done);
110 int status;
111
112 message->complete = spidev_complete;
113 message->context = &done;
114
115 spin_lock_irq(&spidev->spi_lock);
116 if (spidev->spi == NULL)
117 status = -ESHUTDOWN;
118 else
119 status = spi_async(spidev->spi, message);
120 spin_unlock_irq(&spidev->spi_lock);
121
122 if (status == 0) {
123 wait_for_completion(&done);
124 status = message->status;
125 if (status == 0)
126 status = message->actual_length;
127 }
128 message->context = NULL;
129 return status;
130}
131
132static inline ssize_t
133spidev_sync_write(struct spidev_data *spidev, size_t len)
134{
135 struct spi_transfer t = {
136 .tx_buf = spidev->buffer,
137 .len = len,
138 };
139 struct spi_message m;
140
141 spi_message_init(&m);
142 spi_message_add_tail(&t, &m);
143 return spidev_sync(spidev, &m);
144}
145
146static inline ssize_t
147spidev_sync_read(struct spidev_data *spidev, size_t len)
148{
149 struct spi_transfer t = {
150 .rx_buf = spidev->buffer,
151 .len = len,
152 };
153 struct spi_message m;
154
155 spi_message_init(&m);
156 spi_message_add_tail(&t, &m);
157 return spidev_sync(spidev, &m);
158}
159
160/*-------------------------------------------------------------------------*/
161
162/* Read-only message with current device setup */
163static ssize_t
164spidev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
165{
166 struct spidev_data *spidev;
167 ssize_t status = 0;
168
169 /* chipselect only toggles at start or end of operation */
170 if (count > bufsiz)
171 return -EMSGSIZE;
172
173 spidev = filp->private_data;
174
175 mutex_lock(&spidev->buf_lock);
176 status = spidev_sync_read(spidev, count);
177 if (status > 0) {
178 unsigned long missing;
179
180 missing = copy_to_user(buf, spidev->buffer, status);
181 if (missing == status)
182 status = -EFAULT;
183 else
184 status = status - missing;
185 }
186 mutex_unlock(&spidev->buf_lock);
187
188 return status;
189}
190
191/* Write-only message with current device setup */
192static ssize_t
193spidev_write(struct file *filp, const char __user *buf,
194 size_t count, loff_t *f_pos)
195{
196 struct spidev_data *spidev;
197 ssize_t status = 0;
198 unsigned long missing;
199
200 /* chipselect only toggles at start or end of operation */
201 if (count > bufsiz)
202 return -EMSGSIZE;
203
204 spidev = filp->private_data;
205
206 mutex_lock(&spidev->buf_lock);
207 missing = copy_from_user(spidev->buffer, buf, count);
208 if (missing == 0) {
209 status = spidev_sync_write(spidev, count);
210 } else
211 status = -EFAULT;
212 mutex_unlock(&spidev->buf_lock);
213
214 return status;
215}
216
217static int spidev_message(struct spidev_data *spidev,
218 struct spi_ioc_transfer *u_xfers, unsigned n_xfers)
219{
220 struct spi_message msg;
221 struct spi_transfer *k_xfers;
222 struct spi_transfer *k_tmp;
223 struct spi_ioc_transfer *u_tmp;
224 unsigned n, total;
225 u8 *buf;
226 int status = -EFAULT;
227
228 if (!n_xfers)
229 return 0;
230
231 spi_message_init(&msg);
232 k_xfers = kcalloc(n_xfers, sizeof(*k_tmp), GFP_KERNEL);
233 if (k_xfers == NULL)
234 return -ENOMEM;
235
236 /* Construct spi_message, copying any tx data to bounce buffer.
237 * We walk the array of user-provided transfers, using each one
238 * to initialize a kernel version of the same transfer.
239 */
240 buf = spidev->buffer;
241 total = 0;
242 for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers;
243 n;
244 n--, k_tmp++, u_tmp++) {
245 k_tmp->len = u_tmp->len;
246
247 total += k_tmp->len;
248 /* Check total length of transfers. Also check each
249 * transfer length to avoid arithmetic overflow.
250 */
251 if (total > bufsiz || k_tmp->len > bufsiz) {
252 status = -EMSGSIZE;
253 goto done;
254 }
255
256 if (u_tmp->rx_buf) {
257 k_tmp->rx_buf = buf;
258 if (!access_ok(VERIFY_WRITE, (u8 __user *)
259 (uintptr_t) u_tmp->rx_buf,
260 u_tmp->len))
261 goto done;
262 }
263 if (u_tmp->tx_buf) {
264 k_tmp->tx_buf = buf;
265 if (copy_from_user(buf, (const u8 __user *)
266 (uintptr_t) u_tmp->tx_buf,
267 u_tmp->len))
268 goto done;
269 }
270 buf += k_tmp->len;
271
272 k_tmp->cs_change = !!u_tmp->cs_change;
273 k_tmp->bits_per_word = u_tmp->bits_per_word;
274 k_tmp->delay_usecs = u_tmp->delay_usecs;
275 k_tmp->speed_hz = u_tmp->speed_hz;
276#ifdef VERBOSE
277 dev_dbg(&spidev->spi->dev,
278 " xfer len %zd %s%s%s%dbits %u usec %uHz\n",
279 u_tmp->len,
280 u_tmp->rx_buf ? "rx " : "",
281 u_tmp->tx_buf ? "tx " : "",
282 u_tmp->cs_change ? "cs " : "",
283 u_tmp->bits_per_word ? : spidev->spi->bits_per_word,
284 u_tmp->delay_usecs,
285 u_tmp->speed_hz ? : spidev->spi->max_speed_hz);
286#endif
287 spi_message_add_tail(k_tmp, &msg);
288 }
289
290 status = spidev_sync(spidev, &msg);
291 if (status < 0)
292 goto done;
293
294 /* copy any rx data out of bounce buffer */
295 buf = spidev->buffer;
296 for (n = n_xfers, u_tmp = u_xfers; n; n--, u_tmp++) {
297 if (u_tmp->rx_buf) {
298 if (__copy_to_user((u8 __user *)
299 (uintptr_t) u_tmp->rx_buf, buf,
300 u_tmp->len)) {
301 status = -EFAULT;
302 goto done;
303 }
304 }
305 buf += u_tmp->len;
306 }
307 status = total;
308
309done:
310 kfree(k_xfers);
311 return status;
312}
313
314static long
315spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
316{
317 int err = 0;
318 int retval = 0;
319 struct spidev_data *spidev;
320 struct spi_device *spi;
321 u32 tmp;
322 unsigned n_ioc;
323 struct spi_ioc_transfer *ioc;
324
325 /* Check type and command number */
326 if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC)
327 return -ENOTTY;
328
329 /* Check access direction once here; don't repeat below.
330 * IOC_DIR is from the user perspective, while access_ok is
331 * from the kernel perspective; so they look reversed.
332 */
333 if (_IOC_DIR(cmd) & _IOC_READ)
334 err = !access_ok(VERIFY_WRITE,
335 (void __user *)arg, _IOC_SIZE(cmd));
336 if (err == 0 && _IOC_DIR(cmd) & _IOC_WRITE)
337 err = !access_ok(VERIFY_READ,
338 (void __user *)arg, _IOC_SIZE(cmd));
339 if (err)
340 return -EFAULT;
341
342 /* guard against device removal before, or while,
343 * we issue this ioctl.
344 */
345 spidev = filp->private_data;
346 spin_lock_irq(&spidev->spi_lock);
347 spi = spi_dev_get(spidev->spi);
348 spin_unlock_irq(&spidev->spi_lock);
349
350 if (spi == NULL)
351 return -ESHUTDOWN;
352
353 /* use the buffer lock here for triple duty:
354 * - prevent I/O (from us) so calling spi_setup() is safe;
355 * - prevent concurrent SPI_IOC_WR_* from morphing
356 * data fields while SPI_IOC_RD_* reads them;
357 * - SPI_IOC_MESSAGE needs the buffer locked "normally".
358 */
359 mutex_lock(&spidev->buf_lock);
360
361 switch (cmd) {
362 /* read requests */
363 case SPI_IOC_RD_MODE:
364 retval = __put_user(spi->mode & SPI_MODE_MASK,
365 (__u8 __user *)arg);
366 break;
367 case SPI_IOC_RD_LSB_FIRST:
368 retval = __put_user((spi->mode & SPI_LSB_FIRST) ? 1 : 0,
369 (__u8 __user *)arg);
370 break;
371 case SPI_IOC_RD_BITS_PER_WORD:
372 retval = __put_user(spi->bits_per_word, (__u8 __user *)arg);
373 break;
374 case SPI_IOC_RD_MAX_SPEED_HZ:
375 retval = __put_user(spi->max_speed_hz, (__u32 __user *)arg);
376 break;
377
378 /* write requests */
379 case SPI_IOC_WR_MODE:
380 retval = __get_user(tmp, (u8 __user *)arg);
381 if (retval == 0) {
382 u8 save = spi->mode;
383
384 if (tmp & ~SPI_MODE_MASK) {
385 retval = -EINVAL;
386 break;
387 }
388
389 tmp |= spi->mode & ~SPI_MODE_MASK;
390 spi->mode = (u8)tmp;
391 retval = spi_setup(spi);
392 if (retval < 0)
393 spi->mode = save;
394 else
395 dev_dbg(&spi->dev, "spi mode %02x\n", tmp);
396 }
397 break;
398 case SPI_IOC_WR_LSB_FIRST:
399 retval = __get_user(tmp, (__u8 __user *)arg);
400 if (retval == 0) {
401 u8 save = spi->mode;
402
403 if (tmp)
404 spi->mode |= SPI_LSB_FIRST;
405 else
406 spi->mode &= ~SPI_LSB_FIRST;
407 retval = spi_setup(spi);
408 if (retval < 0)
409 spi->mode = save;
410 else
411 dev_dbg(&spi->dev, "%csb first\n",
412 tmp ? 'l' : 'm');
413 }
414 break;
415 case SPI_IOC_WR_BITS_PER_WORD:
416 retval = __get_user(tmp, (__u8 __user *)arg);
417 if (retval == 0) {
418 u8 save = spi->bits_per_word;
419
420 spi->bits_per_word = tmp;
421 retval = spi_setup(spi);
422 if (retval < 0)
423 spi->bits_per_word = save;
424 else
425 dev_dbg(&spi->dev, "%d bits per word\n", tmp);
426 }
427 break;
428 case SPI_IOC_WR_MAX_SPEED_HZ:
429 retval = __get_user(tmp, (__u32 __user *)arg);
430 if (retval == 0) {
431 u32 save = spi->max_speed_hz;
432
433 spi->max_speed_hz = tmp;
434 retval = spi_setup(spi);
435 if (retval < 0)
436 spi->max_speed_hz = save;
437 else
438 dev_dbg(&spi->dev, "%d Hz (max)\n", tmp);
439 }
440 break;
441
442 default:
443 /* segmented and/or full-duplex I/O request */
444 if (_IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0))
445 || _IOC_DIR(cmd) != _IOC_WRITE) {
446 retval = -ENOTTY;
447 break;
448 }
449
450 tmp = _IOC_SIZE(cmd);
451 if ((tmp % sizeof(struct spi_ioc_transfer)) != 0) {
452 retval = -EINVAL;
453 break;
454 }
455 n_ioc = tmp / sizeof(struct spi_ioc_transfer);
456 if (n_ioc == 0)
457 break;
458
459 /* copy into scratch area */
460 ioc = kmalloc(tmp, GFP_KERNEL);
461 if (!ioc) {
462 retval = -ENOMEM;
463 break;
464 }
465 if (__copy_from_user(ioc, (void __user *)arg, tmp)) {
466 kfree(ioc);
467 retval = -EFAULT;
468 break;
469 }
470
471 /* translate to spi_message, execute */
472 retval = spidev_message(spidev, ioc, n_ioc);
473 kfree(ioc);
474 break;
475 }
476
477 mutex_unlock(&spidev->buf_lock);
478 spi_dev_put(spi);
479 return retval;
480}
481
482#ifdef CONFIG_COMPAT
483static long
484spidev_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
485{
486 return spidev_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
487}
488#else
489#define spidev_compat_ioctl NULL
490#endif /* CONFIG_COMPAT */
491
492static int spidev_open(struct inode *inode, struct file *filp)
493{
494 struct spidev_data *spidev;
495 int status = -ENXIO;
496
497 mutex_lock(&device_list_lock);
498
499 list_for_each_entry(spidev, &device_list, device_entry) {
500 if (spidev->devt == inode->i_rdev) {
501 status = 0;
502 break;
503 }
504 }
505 if (status == 0) {
506 if (!spidev->buffer) {
507 spidev->buffer = kmalloc(bufsiz, GFP_KERNEL);
508 if (!spidev->buffer) {
509 dev_dbg(&spidev->spi->dev, "open/ENOMEM\n");
510 status = -ENOMEM;
511 }
512 }
513 if (status == 0) {
514 spidev->users++;
515 filp->private_data = spidev;
516 nonseekable_open(inode, filp);
517 }
518 } else
519 pr_debug("spidev: nothing for minor %d\n", iminor(inode));
520
521 mutex_unlock(&device_list_lock);
522 return status;
523}
524
525static int spidev_release(struct inode *inode, struct file *filp)
526{
527 struct spidev_data *spidev;
528 int status = 0;
529
530 mutex_lock(&device_list_lock);
531 spidev = filp->private_data;
532 filp->private_data = NULL;
533
534 /* last close? */
535 spidev->users--;
536 if (!spidev->users) {
537 int dofree;
538
539 kfree(spidev->buffer);
540 spidev->buffer = NULL;
541
542 /* ... after we unbound from the underlying device? */
543 spin_lock_irq(&spidev->spi_lock);
544 dofree = (spidev->spi == NULL);
545 spin_unlock_irq(&spidev->spi_lock);
546
547 if (dofree)
548 kfree(spidev);
549 }
550 mutex_unlock(&device_list_lock);
551
552 return status;
553}
554
555static const struct file_operations spidev_fops = {
556 .owner = THIS_MODULE,
557 /* REVISIT switch to aio primitives, so that userspace
558 * gets more complete API coverage. It'll simplify things
559 * too, except for the locking.
560 */
561 .write = spidev_write,
562 .read = spidev_read,
563 .unlocked_ioctl = spidev_ioctl,
564 .compat_ioctl = spidev_compat_ioctl,
565 .open = spidev_open,
566 .release = spidev_release,
567 .llseek = no_llseek,
568};
569
570/*-------------------------------------------------------------------------*/
571
572/* The main reason to have this class is to make mdev/udev create the
573 * /dev/spidevB.C character device nodes exposing our userspace API.
574 * It also simplifies memory management.
575 */
576
577static struct class *spidev_class;
578
579/*-------------------------------------------------------------------------*/
580
581static int __devinit spidev_probe(struct spi_device *spi)
582{
583 struct spidev_data *spidev;
584 int status;
585 unsigned long minor;
586
587 /* Allocate driver data */
588 spidev = kzalloc(sizeof(*spidev), GFP_KERNEL);
589 if (!spidev)
590 return -ENOMEM;
591
592 /* Initialize the driver data */
593 spidev->spi = spi;
594 spin_lock_init(&spidev->spi_lock);
595 mutex_init(&spidev->buf_lock);
596
597 INIT_LIST_HEAD(&spidev->device_entry);
598
599 /* If we can allocate a minor number, hook up this device.
600 * Reusing minors is fine so long as udev or mdev is working.
601 */
602 mutex_lock(&device_list_lock);
603 minor = find_first_zero_bit(minors, N_SPI_MINORS);
604 if (minor < N_SPI_MINORS) {
605 struct device *dev;
606
607 spidev->devt = MKDEV(SPIDEV_MAJOR, minor);
608 dev = device_create(spidev_class, &spi->dev, spidev->devt,
609 spidev, "spidev%d.%d",
610 spi->master->bus_num, spi->chip_select);
611 status = IS_ERR(dev) ? PTR_ERR(dev) : 0;
612 } else {
613 dev_dbg(&spi->dev, "no minor number available!\n");
614 status = -ENODEV;
615 }
616 if (status == 0) {
617 set_bit(minor, minors);
618 list_add(&spidev->device_entry, &device_list);
619 }
620 mutex_unlock(&device_list_lock);
621
622 if (status == 0)
623 spi_set_drvdata(spi, spidev);
624 else
625 kfree(spidev);
626
627 return status;
628}
629
630static int __devexit spidev_remove(struct spi_device *spi)
631{
632 struct spidev_data *spidev = spi_get_drvdata(spi);
633
634 if(!spidev)
635 return -EINVAL;
636
637 /* make sure ops on existing fds can abort cleanly */
638 spin_lock_irq(&spidev->spi_lock);
639 spidev->spi = NULL;
640 spi_set_drvdata(spi, NULL);
641 spin_unlock_irq(&spidev->spi_lock);
642
643 /* prevent new opens */
644 mutex_lock(&device_list_lock);
645 list_del(&spidev->device_entry);
646 device_destroy(spidev_class, spidev->devt);
647 clear_bit(MINOR(spidev->devt), minors);
648 if (spidev->users == 0)
649 kfree(spidev);
650 mutex_unlock(&device_list_lock);
651
652 return 0;
653}
654
655static struct spi_driver spidev_spi_driver = {
656 .driver = {
657 .name = "spidev",
658 .owner = THIS_MODULE,
659 },
660 .probe = spidev_probe,
661 .remove = __devexit_p(spidev_remove),
662
663 /* NOTE: suspend/resume methods are not necessary here.
664 * We don't do anything except pass the requests to/from
665 * the underlying controller. The refrigerator handles
666 * most issues; the controller driver handles the rest.
667 */
668};
669
670/*-------------------------------------------------------------------------*/
671
672static int __init spidev_init(void)
673{
674 int status;
675
676 /* Claim our 256 reserved device numbers. Then register a class
677 * that will key udev/mdev to add/remove /dev nodes. Last, register
678 * the driver which manages those device numbers.
679 */
680 BUILD_BUG_ON(N_SPI_MINORS > 256);
681 status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops);
682 if (status < 0)
683 return status;
684
685 spidev_class = class_create(THIS_MODULE, "spidev");
686 if (IS_ERR(spidev_class)) {
687 unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
688 return PTR_ERR(spidev_class);
689 }
690
691 status = spi_register_driver(&spidev_spi_driver);
692 if (status < 0) {
693 class_destroy(spidev_class);
694 unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
695 }
696 return status;
697}
698module_init(spidev_init);
699
700static void __exit spidev_exit(void)
701{
702 spi_unregister_driver(&spidev_spi_driver);
703 class_destroy(spidev_class);
704 unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name);
705}
706module_exit(spidev_exit);
707
708MODULE_AUTHOR("Andrea Paterniani, <a.paterniani@swapp-eng.it>");
709MODULE_DESCRIPTION("User mode SPI device interface");
710MODULE_LICENSE("GPL");
711MODULE_ALIAS("spi:spidev");