4 * Copyright (C) 2005 David Brownell
5 * Copyright (C) 2008 Secret Lab Technologies Ltd.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
18 #include <linux/kernel.h>
19 #include <linux/device.h>
20 #include <linux/init.h>
21 #include <linux/cache.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/dmaengine.h>
24 #include <linux/mutex.h>
25 #include <linux/of_device.h>
26 #include <linux/of_irq.h>
27 #include <linux/clk/clk-conf.h>
28 #include <linux/slab.h>
29 #include <linux/mod_devicetable.h>
30 #include <linux/spi/spi.h>
31 #include <linux/of_gpio.h>
32 #include <linux/pm_runtime.h>
33 #include <linux/pm_domain.h>
34 #include <linux/export.h>
35 #include <linux/sched/rt.h>
36 #include <linux/delay.h>
37 #include <linux/kthread.h>
38 #include <linux/ioport.h>
39 #include <linux/acpi.h>
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/spi.h>
44 static void spidev_release(struct device *dev)
46 struct spi_device *spi = to_spi_device(dev);
48 /* spi masters may cleanup for released devices */
49 if (spi->master->cleanup)
50 spi->master->cleanup(spi);
52 spi_master_put(spi->master);
57 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
59 const struct spi_device *spi = to_spi_device(dev);
62 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
66 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
68 static DEVICE_ATTR_RO(modalias);
70 #define SPI_STATISTICS_ATTRS(field, file) \
71 static ssize_t spi_master_##field##_show(struct device *dev, \
72 struct device_attribute *attr, \
75 struct spi_master *master = container_of(dev, \
76 struct spi_master, dev); \
77 return spi_statistics_##field##_show(&master->statistics, buf); \
79 static struct device_attribute dev_attr_spi_master_##field = { \
80 .attr = { .name = file, .mode = S_IRUGO }, \
81 .show = spi_master_##field##_show, \
83 static ssize_t spi_device_##field##_show(struct device *dev, \
84 struct device_attribute *attr, \
87 struct spi_device *spi = container_of(dev, \
88 struct spi_device, dev); \
89 return spi_statistics_##field##_show(&spi->statistics, buf); \
91 static struct device_attribute dev_attr_spi_device_##field = { \
92 .attr = { .name = file, .mode = S_IRUGO }, \
93 .show = spi_device_##field##_show, \
96 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
97 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
100 unsigned long flags; \
102 spin_lock_irqsave(&stat->lock, flags); \
103 len = sprintf(buf, format_string, stat->field); \
104 spin_unlock_irqrestore(&stat->lock, flags); \
107 SPI_STATISTICS_ATTRS(name, file)
109 #define SPI_STATISTICS_SHOW(field, format_string) \
110 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
111 field, format_string)
113 SPI_STATISTICS_SHOW(messages, "%lu");
114 SPI_STATISTICS_SHOW(transfers, "%lu");
115 SPI_STATISTICS_SHOW(errors, "%lu");
116 SPI_STATISTICS_SHOW(timedout, "%lu");
118 SPI_STATISTICS_SHOW(spi_sync, "%lu");
119 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
120 SPI_STATISTICS_SHOW(spi_async, "%lu");
122 SPI_STATISTICS_SHOW(bytes, "%llu");
123 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
124 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
126 static struct attribute *spi_dev_attrs[] = {
127 &dev_attr_modalias.attr,
131 static const struct attribute_group spi_dev_group = {
132 .attrs = spi_dev_attrs,
135 static struct attribute *spi_device_statistics_attrs[] = {
136 &dev_attr_spi_device_messages.attr,
137 &dev_attr_spi_device_transfers.attr,
138 &dev_attr_spi_device_errors.attr,
139 &dev_attr_spi_device_timedout.attr,
140 &dev_attr_spi_device_spi_sync.attr,
141 &dev_attr_spi_device_spi_sync_immediate.attr,
142 &dev_attr_spi_device_spi_async.attr,
143 &dev_attr_spi_device_bytes.attr,
144 &dev_attr_spi_device_bytes_rx.attr,
145 &dev_attr_spi_device_bytes_tx.attr,
149 static const struct attribute_group spi_device_statistics_group = {
150 .name = "statistics",
151 .attrs = spi_device_statistics_attrs,
154 static const struct attribute_group *spi_dev_groups[] = {
156 &spi_device_statistics_group,
160 static struct attribute *spi_master_statistics_attrs[] = {
161 &dev_attr_spi_master_messages.attr,
162 &dev_attr_spi_master_transfers.attr,
163 &dev_attr_spi_master_errors.attr,
164 &dev_attr_spi_master_timedout.attr,
165 &dev_attr_spi_master_spi_sync.attr,
166 &dev_attr_spi_master_spi_sync_immediate.attr,
167 &dev_attr_spi_master_spi_async.attr,
168 &dev_attr_spi_master_bytes.attr,
169 &dev_attr_spi_master_bytes_rx.attr,
170 &dev_attr_spi_master_bytes_tx.attr,
174 static const struct attribute_group spi_master_statistics_group = {
175 .name = "statistics",
176 .attrs = spi_master_statistics_attrs,
179 static const struct attribute_group *spi_master_groups[] = {
180 &spi_master_statistics_group,
184 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
185 struct spi_transfer *xfer,
186 struct spi_master *master)
190 spin_lock_irqsave(&stats->lock, flags);
194 stats->bytes += xfer->len;
195 if ((xfer->tx_buf) &&
196 (xfer->tx_buf != master->dummy_tx))
197 stats->bytes_tx += xfer->len;
198 if ((xfer->rx_buf) &&
199 (xfer->rx_buf != master->dummy_rx))
200 stats->bytes_rx += xfer->len;
202 spin_unlock_irqrestore(&stats->lock, flags);
204 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
206 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
207 * and the sysfs version makes coldplug work too.
210 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
211 const struct spi_device *sdev)
213 while (id->name[0]) {
214 if (!strcmp(sdev->modalias, id->name))
221 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
223 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
225 return spi_match_id(sdrv->id_table, sdev);
227 EXPORT_SYMBOL_GPL(spi_get_device_id);
229 static int spi_match_device(struct device *dev, struct device_driver *drv)
231 const struct spi_device *spi = to_spi_device(dev);
232 const struct spi_driver *sdrv = to_spi_driver(drv);
234 /* Attempt an OF style match */
235 if (of_driver_match_device(dev, drv))
239 if (acpi_driver_match_device(dev, drv))
243 return !!spi_match_id(sdrv->id_table, spi);
245 return strcmp(spi->modalias, drv->name) == 0;
248 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
250 const struct spi_device *spi = to_spi_device(dev);
253 rc = acpi_device_uevent_modalias(dev, env);
257 add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
261 struct bus_type spi_bus_type = {
263 .dev_groups = spi_dev_groups,
264 .match = spi_match_device,
265 .uevent = spi_uevent,
267 EXPORT_SYMBOL_GPL(spi_bus_type);
270 static int spi_drv_probe(struct device *dev)
272 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
273 struct spi_device *spi = to_spi_device(dev);
276 ret = of_clk_set_defaults(dev->of_node, false);
281 spi->irq = of_irq_get(dev->of_node, 0);
282 if (spi->irq == -EPROBE_DEFER)
283 return -EPROBE_DEFER;
288 ret = dev_pm_domain_attach(dev, true);
289 if (ret != -EPROBE_DEFER) {
290 ret = sdrv->probe(spi);
292 dev_pm_domain_detach(dev, true);
298 static int spi_drv_remove(struct device *dev)
300 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
303 ret = sdrv->remove(to_spi_device(dev));
304 dev_pm_domain_detach(dev, true);
309 static void spi_drv_shutdown(struct device *dev)
311 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
313 sdrv->shutdown(to_spi_device(dev));
317 * spi_register_driver - register a SPI driver
318 * @sdrv: the driver to register
321 int spi_register_driver(struct spi_driver *sdrv)
323 sdrv->driver.bus = &spi_bus_type;
325 sdrv->driver.probe = spi_drv_probe;
327 sdrv->driver.remove = spi_drv_remove;
329 sdrv->driver.shutdown = spi_drv_shutdown;
330 return driver_register(&sdrv->driver);
332 EXPORT_SYMBOL_GPL(spi_register_driver);
334 /*-------------------------------------------------------------------------*/
336 /* SPI devices should normally not be created by SPI device drivers; that
337 * would make them board-specific. Similarly with SPI master drivers.
338 * Device registration normally goes into like arch/.../mach.../board-YYY.c
339 * with other readonly (flashable) information about mainboard devices.
343 struct list_head list;
344 struct spi_board_info board_info;
347 static LIST_HEAD(board_list);
348 static LIST_HEAD(spi_master_list);
351 * Used to protect add/del opertion for board_info list and
352 * spi_master list, and their matching process
354 static DEFINE_MUTEX(board_lock);
357 * spi_alloc_device - Allocate a new SPI device
358 * @master: Controller to which device is connected
361 * Allows a driver to allocate and initialize a spi_device without
362 * registering it immediately. This allows a driver to directly
363 * fill the spi_device with device parameters before calling
364 * spi_add_device() on it.
366 * Caller is responsible to call spi_add_device() on the returned
367 * spi_device structure to add it to the SPI master. If the caller
368 * needs to discard the spi_device without adding it, then it should
369 * call spi_dev_put() on it.
371 * Returns a pointer to the new device, or NULL.
373 struct spi_device *spi_alloc_device(struct spi_master *master)
375 struct spi_device *spi;
377 if (!spi_master_get(master))
380 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
382 spi_master_put(master);
386 spi->master = master;
387 spi->dev.parent = &master->dev;
388 spi->dev.bus = &spi_bus_type;
389 spi->dev.release = spidev_release;
390 spi->cs_gpio = -ENOENT;
392 spin_lock_init(&spi->statistics.lock);
394 device_initialize(&spi->dev);
397 EXPORT_SYMBOL_GPL(spi_alloc_device);
399 static void spi_dev_set_name(struct spi_device *spi)
401 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
404 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
408 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->master->dev),
412 static int spi_dev_check(struct device *dev, void *data)
414 struct spi_device *spi = to_spi_device(dev);
415 struct spi_device *new_spi = data;
417 if (spi->master == new_spi->master &&
418 spi->chip_select == new_spi->chip_select)
424 * spi_add_device - Add spi_device allocated with spi_alloc_device
425 * @spi: spi_device to register
427 * Companion function to spi_alloc_device. Devices allocated with
428 * spi_alloc_device can be added onto the spi bus with this function.
430 * Returns 0 on success; negative errno on failure
432 int spi_add_device(struct spi_device *spi)
434 static DEFINE_MUTEX(spi_add_lock);
435 struct spi_master *master = spi->master;
436 struct device *dev = master->dev.parent;
439 /* Chipselects are numbered 0..max; validate. */
440 if (spi->chip_select >= master->num_chipselect) {
441 dev_err(dev, "cs%d >= max %d\n",
443 master->num_chipselect);
447 /* Set the bus ID string */
448 spi_dev_set_name(spi);
450 /* We need to make sure there's no other device with this
451 * chipselect **BEFORE** we call setup(), else we'll trash
452 * its configuration. Lock against concurrent add() calls.
454 mutex_lock(&spi_add_lock);
456 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
458 dev_err(dev, "chipselect %d already in use\n",
463 if (master->cs_gpios)
464 spi->cs_gpio = master->cs_gpios[spi->chip_select];
466 /* Drivers may modify this initial i/o setup, but will
467 * normally rely on the device being setup. Devices
468 * using SPI_CS_HIGH can't coexist well otherwise...
470 status = spi_setup(spi);
472 dev_err(dev, "can't setup %s, status %d\n",
473 dev_name(&spi->dev), status);
477 /* Device may be bound to an active driver when this returns */
478 status = device_add(&spi->dev);
480 dev_err(dev, "can't add %s, status %d\n",
481 dev_name(&spi->dev), status);
483 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
486 mutex_unlock(&spi_add_lock);
489 EXPORT_SYMBOL_GPL(spi_add_device);
492 * spi_new_device - instantiate one new SPI device
493 * @master: Controller to which device is connected
494 * @chip: Describes the SPI device
497 * On typical mainboards, this is purely internal; and it's not needed
498 * after board init creates the hard-wired devices. Some development
499 * platforms may not be able to use spi_register_board_info though, and
500 * this is exported so that for example a USB or parport based adapter
501 * driver could add devices (which it would learn about out-of-band).
503 * Returns the new device, or NULL.
505 struct spi_device *spi_new_device(struct spi_master *master,
506 struct spi_board_info *chip)
508 struct spi_device *proxy;
511 /* NOTE: caller did any chip->bus_num checks necessary.
513 * Also, unless we change the return value convention to use
514 * error-or-pointer (not NULL-or-pointer), troubleshootability
515 * suggests syslogged diagnostics are best here (ugh).
518 proxy = spi_alloc_device(master);
522 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
524 proxy->chip_select = chip->chip_select;
525 proxy->max_speed_hz = chip->max_speed_hz;
526 proxy->mode = chip->mode;
527 proxy->irq = chip->irq;
528 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
529 proxy->dev.platform_data = (void *) chip->platform_data;
530 proxy->controller_data = chip->controller_data;
531 proxy->controller_state = NULL;
533 status = spi_add_device(proxy);
541 EXPORT_SYMBOL_GPL(spi_new_device);
543 static void spi_match_master_to_boardinfo(struct spi_master *master,
544 struct spi_board_info *bi)
546 struct spi_device *dev;
548 if (master->bus_num != bi->bus_num)
551 dev = spi_new_device(master, bi);
553 dev_err(master->dev.parent, "can't create new device for %s\n",
558 * spi_register_board_info - register SPI devices for a given board
559 * @info: array of chip descriptors
560 * @n: how many descriptors are provided
563 * Board-specific early init code calls this (probably during arch_initcall)
564 * with segments of the SPI device table. Any device nodes are created later,
565 * after the relevant parent SPI controller (bus_num) is defined. We keep
566 * this table of devices forever, so that reloading a controller driver will
567 * not make Linux forget about these hard-wired devices.
569 * Other code can also call this, e.g. a particular add-on board might provide
570 * SPI devices through its expansion connector, so code initializing that board
571 * would naturally declare its SPI devices.
573 * The board info passed can safely be __initdata ... but be careful of
574 * any embedded pointers (platform_data, etc), they're copied as-is.
576 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
578 struct boardinfo *bi;
584 bi = kzalloc(n * sizeof(*bi), GFP_KERNEL);
588 for (i = 0; i < n; i++, bi++, info++) {
589 struct spi_master *master;
591 memcpy(&bi->board_info, info, sizeof(*info));
592 mutex_lock(&board_lock);
593 list_add_tail(&bi->list, &board_list);
594 list_for_each_entry(master, &spi_master_list, list)
595 spi_match_master_to_boardinfo(master, &bi->board_info);
596 mutex_unlock(&board_lock);
602 /*-------------------------------------------------------------------------*/
604 static void spi_set_cs(struct spi_device *spi, bool enable)
606 if (spi->mode & SPI_CS_HIGH)
609 if (gpio_is_valid(spi->cs_gpio))
610 gpio_set_value(spi->cs_gpio, !enable);
611 else if (spi->master->set_cs)
612 spi->master->set_cs(spi, !enable);
615 #ifdef CONFIG_HAS_DMA
616 static int spi_map_buf(struct spi_master *master, struct device *dev,
617 struct sg_table *sgt, void *buf, size_t len,
618 enum dma_data_direction dir)
620 const bool vmalloced_buf = is_vmalloc_addr(buf);
623 struct page *vm_page;
629 desc_len = PAGE_SIZE;
630 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
632 desc_len = master->max_dma_len;
633 sgs = DIV_ROUND_UP(len, desc_len);
636 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
640 for (i = 0; i < sgs; i++) {
644 len, desc_len - offset_in_page(buf));
645 vm_page = vmalloc_to_page(buf);
650 sg_set_page(&sgt->sgl[i], vm_page,
651 min, offset_in_page(buf));
653 min = min_t(size_t, len, desc_len);
655 sg_set_buf(&sgt->sgl[i], sg_buf, min);
663 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
676 static void spi_unmap_buf(struct spi_master *master, struct device *dev,
677 struct sg_table *sgt, enum dma_data_direction dir)
679 if (sgt->orig_nents) {
680 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
685 static int __spi_map_msg(struct spi_master *master, struct spi_message *msg)
687 struct device *tx_dev, *rx_dev;
688 struct spi_transfer *xfer;
691 if (!master->can_dma)
695 tx_dev = master->dma_tx->device->dev;
697 tx_dev = &master->dev;
700 rx_dev = master->dma_rx->device->dev;
702 rx_dev = &master->dev;
704 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
705 if (!master->can_dma(master, msg->spi, xfer))
708 if (xfer->tx_buf != NULL) {
709 ret = spi_map_buf(master, tx_dev, &xfer->tx_sg,
710 (void *)xfer->tx_buf, xfer->len,
716 if (xfer->rx_buf != NULL) {
717 ret = spi_map_buf(master, rx_dev, &xfer->rx_sg,
718 xfer->rx_buf, xfer->len,
721 spi_unmap_buf(master, tx_dev, &xfer->tx_sg,
728 master->cur_msg_mapped = true;
733 static int __spi_unmap_msg(struct spi_master *master, struct spi_message *msg)
735 struct spi_transfer *xfer;
736 struct device *tx_dev, *rx_dev;
738 if (!master->cur_msg_mapped || !master->can_dma)
742 tx_dev = master->dma_tx->device->dev;
744 tx_dev = &master->dev;
747 rx_dev = master->dma_rx->device->dev;
749 rx_dev = &master->dev;
751 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
752 if (!master->can_dma(master, msg->spi, xfer))
755 spi_unmap_buf(master, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
756 spi_unmap_buf(master, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
761 #else /* !CONFIG_HAS_DMA */
762 static inline int __spi_map_msg(struct spi_master *master,
763 struct spi_message *msg)
768 static inline int __spi_unmap_msg(struct spi_master *master,
769 struct spi_message *msg)
773 #endif /* !CONFIG_HAS_DMA */
775 static inline int spi_unmap_msg(struct spi_master *master,
776 struct spi_message *msg)
778 struct spi_transfer *xfer;
780 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
782 * Restore the original value of tx_buf or rx_buf if they are
785 if (xfer->tx_buf == master->dummy_tx)
787 if (xfer->rx_buf == master->dummy_rx)
791 return __spi_unmap_msg(master, msg);
794 static int spi_map_msg(struct spi_master *master, struct spi_message *msg)
796 struct spi_transfer *xfer;
798 unsigned int max_tx, max_rx;
800 if (master->flags & (SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX)) {
804 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
805 if ((master->flags & SPI_MASTER_MUST_TX) &&
807 max_tx = max(xfer->len, max_tx);
808 if ((master->flags & SPI_MASTER_MUST_RX) &&
810 max_rx = max(xfer->len, max_rx);
814 tmp = krealloc(master->dummy_tx, max_tx,
815 GFP_KERNEL | GFP_DMA);
818 master->dummy_tx = tmp;
819 memset(tmp, 0, max_tx);
823 tmp = krealloc(master->dummy_rx, max_rx,
824 GFP_KERNEL | GFP_DMA);
827 master->dummy_rx = tmp;
830 if (max_tx || max_rx) {
831 list_for_each_entry(xfer, &msg->transfers,
834 xfer->tx_buf = master->dummy_tx;
836 xfer->rx_buf = master->dummy_rx;
841 return __spi_map_msg(master, msg);
845 * spi_transfer_one_message - Default implementation of transfer_one_message()
847 * This is a standard implementation of transfer_one_message() for
848 * drivers which impelment a transfer_one() operation. It provides
849 * standard handling of delays and chip select management.
851 static int spi_transfer_one_message(struct spi_master *master,
852 struct spi_message *msg)
854 struct spi_transfer *xfer;
855 bool keep_cs = false;
857 unsigned long ms = 1;
858 struct spi_statistics *statm = &master->statistics;
859 struct spi_statistics *stats = &msg->spi->statistics;
861 spi_set_cs(msg->spi, true);
863 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
864 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
866 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
867 trace_spi_transfer_start(msg, xfer);
869 spi_statistics_add_transfer_stats(statm, xfer, master);
870 spi_statistics_add_transfer_stats(stats, xfer, master);
872 if (xfer->tx_buf || xfer->rx_buf) {
873 reinit_completion(&master->xfer_completion);
875 ret = master->transfer_one(master, msg->spi, xfer);
877 SPI_STATISTICS_INCREMENT_FIELD(statm,
879 SPI_STATISTICS_INCREMENT_FIELD(stats,
881 dev_err(&msg->spi->dev,
882 "SPI transfer failed: %d\n", ret);
888 ms = xfer->len * 8 * 1000 / xfer->speed_hz;
889 ms += ms + 100; /* some tolerance */
891 ms = wait_for_completion_timeout(&master->xfer_completion,
892 msecs_to_jiffies(ms));
896 SPI_STATISTICS_INCREMENT_FIELD(statm,
898 SPI_STATISTICS_INCREMENT_FIELD(stats,
900 dev_err(&msg->spi->dev,
901 "SPI transfer timed out\n");
902 msg->status = -ETIMEDOUT;
906 dev_err(&msg->spi->dev,
907 "Bufferless transfer has length %u\n",
911 trace_spi_transfer_stop(msg, xfer);
913 if (msg->status != -EINPROGRESS)
916 if (xfer->delay_usecs)
917 udelay(xfer->delay_usecs);
919 if (xfer->cs_change) {
920 if (list_is_last(&xfer->transfer_list,
924 spi_set_cs(msg->spi, false);
926 spi_set_cs(msg->spi, true);
930 msg->actual_length += xfer->len;
934 if (ret != 0 || !keep_cs)
935 spi_set_cs(msg->spi, false);
937 if (msg->status == -EINPROGRESS)
940 if (msg->status && master->handle_err)
941 master->handle_err(master, msg);
943 spi_finalize_current_message(master);
949 * spi_finalize_current_transfer - report completion of a transfer
950 * @master: the master reporting completion
952 * Called by SPI drivers using the core transfer_one_message()
953 * implementation to notify it that the current interrupt driven
954 * transfer has finished and the next one may be scheduled.
956 void spi_finalize_current_transfer(struct spi_master *master)
958 complete(&master->xfer_completion);
960 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
963 * __spi_pump_messages - function which processes spi message queue
964 * @master: master to process queue for
965 * @in_kthread: true if we are in the context of the message pump thread
967 * This function checks if there is any spi message in the queue that
968 * needs processing and if so call out to the driver to initialize hardware
969 * and transfer each message.
971 * Note that it is called both from the kthread itself and also from
972 * inside spi_sync(); the queue extraction handling at the top of the
973 * function should deal with this safely.
975 static void __spi_pump_messages(struct spi_master *master, bool in_kthread)
978 bool was_busy = false;
982 spin_lock_irqsave(&master->queue_lock, flags);
984 /* Make sure we are not already running a message */
985 if (master->cur_msg) {
986 spin_unlock_irqrestore(&master->queue_lock, flags);
990 /* If another context is idling the device then defer */
991 if (master->idling) {
992 queue_kthread_work(&master->kworker, &master->pump_messages);
993 spin_unlock_irqrestore(&master->queue_lock, flags);
997 /* Check if the queue is idle */
998 if (list_empty(&master->queue) || !master->running) {
1000 spin_unlock_irqrestore(&master->queue_lock, flags);
1004 /* Only do teardown in the thread */
1006 queue_kthread_work(&master->kworker,
1007 &master->pump_messages);
1008 spin_unlock_irqrestore(&master->queue_lock, flags);
1012 master->busy = false;
1013 master->idling = true;
1014 spin_unlock_irqrestore(&master->queue_lock, flags);
1016 kfree(master->dummy_rx);
1017 master->dummy_rx = NULL;
1018 kfree(master->dummy_tx);
1019 master->dummy_tx = NULL;
1020 if (master->unprepare_transfer_hardware &&
1021 master->unprepare_transfer_hardware(master))
1022 dev_err(&master->dev,
1023 "failed to unprepare transfer hardware\n");
1024 if (master->auto_runtime_pm) {
1025 pm_runtime_mark_last_busy(master->dev.parent);
1026 pm_runtime_put_autosuspend(master->dev.parent);
1028 trace_spi_master_idle(master);
1030 spin_lock_irqsave(&master->queue_lock, flags);
1031 master->idling = false;
1032 spin_unlock_irqrestore(&master->queue_lock, flags);
1036 /* Extract head of queue */
1038 list_first_entry(&master->queue, struct spi_message, queue);
1040 list_del_init(&master->cur_msg->queue);
1044 master->busy = true;
1045 spin_unlock_irqrestore(&master->queue_lock, flags);
1047 if (!was_busy && master->auto_runtime_pm) {
1048 ret = pm_runtime_get_sync(master->dev.parent);
1050 dev_err(&master->dev, "Failed to power device: %d\n",
1057 trace_spi_master_busy(master);
1059 if (!was_busy && master->prepare_transfer_hardware) {
1060 ret = master->prepare_transfer_hardware(master);
1062 dev_err(&master->dev,
1063 "failed to prepare transfer hardware\n");
1065 if (master->auto_runtime_pm)
1066 pm_runtime_put(master->dev.parent);
1071 trace_spi_message_start(master->cur_msg);
1073 if (master->prepare_message) {
1074 ret = master->prepare_message(master, master->cur_msg);
1076 dev_err(&master->dev,
1077 "failed to prepare message: %d\n", ret);
1078 master->cur_msg->status = ret;
1079 spi_finalize_current_message(master);
1082 master->cur_msg_prepared = true;
1085 ret = spi_map_msg(master, master->cur_msg);
1087 master->cur_msg->status = ret;
1088 spi_finalize_current_message(master);
1092 ret = master->transfer_one_message(master, master->cur_msg);
1094 dev_err(&master->dev,
1095 "failed to transfer one message from queue\n");
1101 * spi_pump_messages - kthread work function which processes spi message queue
1102 * @work: pointer to kthread work struct contained in the master struct
1104 static void spi_pump_messages(struct kthread_work *work)
1106 struct spi_master *master =
1107 container_of(work, struct spi_master, pump_messages);
1109 __spi_pump_messages(master, true);
1112 static int spi_init_queue(struct spi_master *master)
1114 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1116 master->running = false;
1117 master->busy = false;
1119 init_kthread_worker(&master->kworker);
1120 master->kworker_task = kthread_run(kthread_worker_fn,
1121 &master->kworker, "%s",
1122 dev_name(&master->dev));
1123 if (IS_ERR(master->kworker_task)) {
1124 dev_err(&master->dev, "failed to create message pump task\n");
1125 return PTR_ERR(master->kworker_task);
1127 init_kthread_work(&master->pump_messages, spi_pump_messages);
1130 * Master config will indicate if this controller should run the
1131 * message pump with high (realtime) priority to reduce the transfer
1132 * latency on the bus by minimising the delay between a transfer
1133 * request and the scheduling of the message pump thread. Without this
1134 * setting the message pump thread will remain at default priority.
1137 dev_info(&master->dev,
1138 "will run message pump with realtime priority\n");
1139 sched_setscheduler(master->kworker_task, SCHED_FIFO, ¶m);
1146 * spi_get_next_queued_message() - called by driver to check for queued
1148 * @master: the master to check for queued messages
1150 * If there are more messages in the queue, the next message is returned from
1153 struct spi_message *spi_get_next_queued_message(struct spi_master *master)
1155 struct spi_message *next;
1156 unsigned long flags;
1158 /* get a pointer to the next message, if any */
1159 spin_lock_irqsave(&master->queue_lock, flags);
1160 next = list_first_entry_or_null(&master->queue, struct spi_message,
1162 spin_unlock_irqrestore(&master->queue_lock, flags);
1166 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1169 * spi_finalize_current_message() - the current message is complete
1170 * @master: the master to return the message to
1172 * Called by the driver to notify the core that the message in the front of the
1173 * queue is complete and can be removed from the queue.
1175 void spi_finalize_current_message(struct spi_master *master)
1177 struct spi_message *mesg;
1178 unsigned long flags;
1181 spin_lock_irqsave(&master->queue_lock, flags);
1182 mesg = master->cur_msg;
1183 spin_unlock_irqrestore(&master->queue_lock, flags);
1185 spi_unmap_msg(master, mesg);
1187 if (master->cur_msg_prepared && master->unprepare_message) {
1188 ret = master->unprepare_message(master, mesg);
1190 dev_err(&master->dev,
1191 "failed to unprepare message: %d\n", ret);
1195 spin_lock_irqsave(&master->queue_lock, flags);
1196 master->cur_msg = NULL;
1197 master->cur_msg_prepared = false;
1198 queue_kthread_work(&master->kworker, &master->pump_messages);
1199 spin_unlock_irqrestore(&master->queue_lock, flags);
1201 trace_spi_message_done(mesg);
1205 mesg->complete(mesg->context);
1207 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1209 static int spi_start_queue(struct spi_master *master)
1211 unsigned long flags;
1213 spin_lock_irqsave(&master->queue_lock, flags);
1215 if (master->running || master->busy) {
1216 spin_unlock_irqrestore(&master->queue_lock, flags);
1220 master->running = true;
1221 master->cur_msg = NULL;
1222 spin_unlock_irqrestore(&master->queue_lock, flags);
1224 queue_kthread_work(&master->kworker, &master->pump_messages);
1229 static int spi_stop_queue(struct spi_master *master)
1231 unsigned long flags;
1232 unsigned limit = 500;
1235 spin_lock_irqsave(&master->queue_lock, flags);
1238 * This is a bit lame, but is optimized for the common execution path.
1239 * A wait_queue on the master->busy could be used, but then the common
1240 * execution path (pump_messages) would be required to call wake_up or
1241 * friends on every SPI message. Do this instead.
1243 while ((!list_empty(&master->queue) || master->busy) && limit--) {
1244 spin_unlock_irqrestore(&master->queue_lock, flags);
1245 usleep_range(10000, 11000);
1246 spin_lock_irqsave(&master->queue_lock, flags);
1249 if (!list_empty(&master->queue) || master->busy)
1252 master->running = false;
1254 spin_unlock_irqrestore(&master->queue_lock, flags);
1257 dev_warn(&master->dev,
1258 "could not stop message queue\n");
1264 static int spi_destroy_queue(struct spi_master *master)
1268 ret = spi_stop_queue(master);
1271 * flush_kthread_worker will block until all work is done.
1272 * If the reason that stop_queue timed out is that the work will never
1273 * finish, then it does no good to call flush/stop thread, so
1277 dev_err(&master->dev, "problem destroying queue\n");
1281 flush_kthread_worker(&master->kworker);
1282 kthread_stop(master->kworker_task);
1287 static int __spi_queued_transfer(struct spi_device *spi,
1288 struct spi_message *msg,
1291 struct spi_master *master = spi->master;
1292 unsigned long flags;
1294 spin_lock_irqsave(&master->queue_lock, flags);
1296 if (!master->running) {
1297 spin_unlock_irqrestore(&master->queue_lock, flags);
1300 msg->actual_length = 0;
1301 msg->status = -EINPROGRESS;
1303 list_add_tail(&msg->queue, &master->queue);
1304 if (!master->busy && need_pump)
1305 queue_kthread_work(&master->kworker, &master->pump_messages);
1307 spin_unlock_irqrestore(&master->queue_lock, flags);
1312 * spi_queued_transfer - transfer function for queued transfers
1313 * @spi: spi device which is requesting transfer
1314 * @msg: spi message which is to handled is queued to driver queue
1316 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1318 return __spi_queued_transfer(spi, msg, true);
1321 static int spi_master_initialize_queue(struct spi_master *master)
1325 master->transfer = spi_queued_transfer;
1326 if (!master->transfer_one_message)
1327 master->transfer_one_message = spi_transfer_one_message;
1329 /* Initialize and start queue */
1330 ret = spi_init_queue(master);
1332 dev_err(&master->dev, "problem initializing queue\n");
1333 goto err_init_queue;
1335 master->queued = true;
1336 ret = spi_start_queue(master);
1338 dev_err(&master->dev, "problem starting queue\n");
1339 goto err_start_queue;
1345 spi_destroy_queue(master);
1350 /*-------------------------------------------------------------------------*/
1352 #if defined(CONFIG_OF)
1353 static struct spi_device *
1354 of_register_spi_device(struct spi_master *master, struct device_node *nc)
1356 struct spi_device *spi;
1360 /* Alloc an spi_device */
1361 spi = spi_alloc_device(master);
1363 dev_err(&master->dev, "spi_device alloc error for %s\n",
1369 /* Select device driver */
1370 rc = of_modalias_node(nc, spi->modalias,
1371 sizeof(spi->modalias));
1373 dev_err(&master->dev, "cannot find modalias for %s\n",
1378 /* Device address */
1379 rc = of_property_read_u32(nc, "reg", &value);
1381 dev_err(&master->dev, "%s has no valid 'reg' property (%d)\n",
1385 spi->chip_select = value;
1387 /* Mode (clock phase/polarity/etc.) */
1388 if (of_find_property(nc, "spi-cpha", NULL))
1389 spi->mode |= SPI_CPHA;
1390 if (of_find_property(nc, "spi-cpol", NULL))
1391 spi->mode |= SPI_CPOL;
1392 if (of_find_property(nc, "spi-cs-high", NULL))
1393 spi->mode |= SPI_CS_HIGH;
1394 if (of_find_property(nc, "spi-3wire", NULL))
1395 spi->mode |= SPI_3WIRE;
1396 if (of_find_property(nc, "spi-lsb-first", NULL))
1397 spi->mode |= SPI_LSB_FIRST;
1399 /* Device DUAL/QUAD mode */
1400 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1405 spi->mode |= SPI_TX_DUAL;
1408 spi->mode |= SPI_TX_QUAD;
1411 dev_warn(&master->dev,
1412 "spi-tx-bus-width %d not supported\n",
1418 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1423 spi->mode |= SPI_RX_DUAL;
1426 spi->mode |= SPI_RX_QUAD;
1429 dev_warn(&master->dev,
1430 "spi-rx-bus-width %d not supported\n",
1437 rc = of_property_read_u32(nc, "spi-max-frequency", &value);
1439 dev_err(&master->dev, "%s has no valid 'spi-max-frequency' property (%d)\n",
1443 spi->max_speed_hz = value;
1445 /* Store a pointer to the node in the device structure */
1447 spi->dev.of_node = nc;
1449 /* Register the new device */
1450 rc = spi_add_device(spi);
1452 dev_err(&master->dev, "spi_device register error %s\n",
1465 * of_register_spi_devices() - Register child devices onto the SPI bus
1466 * @master: Pointer to spi_master device
1468 * Registers an spi_device for each child node of master node which has a 'reg'
1471 static void of_register_spi_devices(struct spi_master *master)
1473 struct spi_device *spi;
1474 struct device_node *nc;
1476 if (!master->dev.of_node)
1479 for_each_available_child_of_node(master->dev.of_node, nc) {
1480 spi = of_register_spi_device(master, nc);
1482 dev_warn(&master->dev, "Failed to create SPI device for %s\n",
1487 static void of_register_spi_devices(struct spi_master *master) { }
1491 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
1493 struct spi_device *spi = data;
1495 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
1496 struct acpi_resource_spi_serialbus *sb;
1498 sb = &ares->data.spi_serial_bus;
1499 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
1500 spi->chip_select = sb->device_selection;
1501 spi->max_speed_hz = sb->connection_speed;
1503 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
1504 spi->mode |= SPI_CPHA;
1505 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
1506 spi->mode |= SPI_CPOL;
1507 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
1508 spi->mode |= SPI_CS_HIGH;
1510 } else if (spi->irq < 0) {
1513 if (acpi_dev_resource_interrupt(ares, 0, &r))
1517 /* Always tell the ACPI core to skip this resource */
1521 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
1522 void *data, void **return_value)
1524 struct spi_master *master = data;
1525 struct list_head resource_list;
1526 struct acpi_device *adev;
1527 struct spi_device *spi;
1530 if (acpi_bus_get_device(handle, &adev))
1532 if (acpi_bus_get_status(adev) || !adev->status.present)
1535 spi = spi_alloc_device(master);
1537 dev_err(&master->dev, "failed to allocate SPI device for %s\n",
1538 dev_name(&adev->dev));
1539 return AE_NO_MEMORY;
1542 ACPI_COMPANION_SET(&spi->dev, adev);
1545 INIT_LIST_HEAD(&resource_list);
1546 ret = acpi_dev_get_resources(adev, &resource_list,
1547 acpi_spi_add_resource, spi);
1548 acpi_dev_free_resource_list(&resource_list);
1550 if (ret < 0 || !spi->max_speed_hz) {
1555 adev->power.flags.ignore_parent = true;
1556 strlcpy(spi->modalias, acpi_device_hid(adev), sizeof(spi->modalias));
1557 if (spi_add_device(spi)) {
1558 adev->power.flags.ignore_parent = false;
1559 dev_err(&master->dev, "failed to add SPI device %s from ACPI\n",
1560 dev_name(&adev->dev));
1567 static void acpi_register_spi_devices(struct spi_master *master)
1572 handle = ACPI_HANDLE(master->dev.parent);
1576 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
1577 acpi_spi_add_device, NULL,
1579 if (ACPI_FAILURE(status))
1580 dev_warn(&master->dev, "failed to enumerate SPI slaves\n");
1583 static inline void acpi_register_spi_devices(struct spi_master *master) {}
1584 #endif /* CONFIG_ACPI */
1586 static void spi_master_release(struct device *dev)
1588 struct spi_master *master;
1590 master = container_of(dev, struct spi_master, dev);
1594 static struct class spi_master_class = {
1595 .name = "spi_master",
1596 .owner = THIS_MODULE,
1597 .dev_release = spi_master_release,
1598 .dev_groups = spi_master_groups,
1603 * spi_alloc_master - allocate SPI master controller
1604 * @dev: the controller, possibly using the platform_bus
1605 * @size: how much zeroed driver-private data to allocate; the pointer to this
1606 * memory is in the driver_data field of the returned device,
1607 * accessible with spi_master_get_devdata().
1608 * Context: can sleep
1610 * This call is used only by SPI master controller drivers, which are the
1611 * only ones directly touching chip registers. It's how they allocate
1612 * an spi_master structure, prior to calling spi_register_master().
1614 * This must be called from context that can sleep. It returns the SPI
1615 * master structure on success, else NULL.
1617 * The caller is responsible for assigning the bus number and initializing
1618 * the master's methods before calling spi_register_master(); and (after errors
1619 * adding the device) calling spi_master_put() to prevent a memory leak.
1621 struct spi_master *spi_alloc_master(struct device *dev, unsigned size)
1623 struct spi_master *master;
1628 master = kzalloc(size + sizeof(*master), GFP_KERNEL);
1632 device_initialize(&master->dev);
1633 master->bus_num = -1;
1634 master->num_chipselect = 1;
1635 master->dev.class = &spi_master_class;
1636 master->dev.parent = get_device(dev);
1637 spi_master_set_devdata(master, &master[1]);
1641 EXPORT_SYMBOL_GPL(spi_alloc_master);
1644 static int of_spi_register_master(struct spi_master *master)
1647 struct device_node *np = master->dev.of_node;
1652 nb = of_gpio_named_count(np, "cs-gpios");
1653 master->num_chipselect = max_t(int, nb, master->num_chipselect);
1655 /* Return error only for an incorrectly formed cs-gpios property */
1656 if (nb == 0 || nb == -ENOENT)
1661 cs = devm_kzalloc(&master->dev,
1662 sizeof(int) * master->num_chipselect,
1664 master->cs_gpios = cs;
1666 if (!master->cs_gpios)
1669 for (i = 0; i < master->num_chipselect; i++)
1672 for (i = 0; i < nb; i++)
1673 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
1678 static int of_spi_register_master(struct spi_master *master)
1685 * spi_register_master - register SPI master controller
1686 * @master: initialized master, originally from spi_alloc_master()
1687 * Context: can sleep
1689 * SPI master controllers connect to their drivers using some non-SPI bus,
1690 * such as the platform bus. The final stage of probe() in that code
1691 * includes calling spi_register_master() to hook up to this SPI bus glue.
1693 * SPI controllers use board specific (often SOC specific) bus numbers,
1694 * and board-specific addressing for SPI devices combines those numbers
1695 * with chip select numbers. Since SPI does not directly support dynamic
1696 * device identification, boards need configuration tables telling which
1697 * chip is at which address.
1699 * This must be called from context that can sleep. It returns zero on
1700 * success, else a negative error code (dropping the master's refcount).
1701 * After a successful return, the caller is responsible for calling
1702 * spi_unregister_master().
1704 int spi_register_master(struct spi_master *master)
1706 static atomic_t dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
1707 struct device *dev = master->dev.parent;
1708 struct boardinfo *bi;
1709 int status = -ENODEV;
1715 status = of_spi_register_master(master);
1719 /* even if it's just one always-selected device, there must
1720 * be at least one chipselect
1722 if (master->num_chipselect == 0)
1725 if ((master->bus_num < 0) && master->dev.of_node)
1726 master->bus_num = of_alias_get_id(master->dev.of_node, "spi");
1728 /* convention: dynamically assigned bus IDs count down from the max */
1729 if (master->bus_num < 0) {
1730 /* FIXME switch to an IDR based scheme, something like
1731 * I2C now uses, so we can't run out of "dynamic" IDs
1733 master->bus_num = atomic_dec_return(&dyn_bus_id);
1737 INIT_LIST_HEAD(&master->queue);
1738 spin_lock_init(&master->queue_lock);
1739 spin_lock_init(&master->bus_lock_spinlock);
1740 mutex_init(&master->bus_lock_mutex);
1741 master->bus_lock_flag = 0;
1742 init_completion(&master->xfer_completion);
1743 if (!master->max_dma_len)
1744 master->max_dma_len = INT_MAX;
1746 /* register the device, then userspace will see it.
1747 * registration fails if the bus ID is in use.
1749 dev_set_name(&master->dev, "spi%u", master->bus_num);
1750 status = device_add(&master->dev);
1753 dev_dbg(dev, "registered master %s%s\n", dev_name(&master->dev),
1754 dynamic ? " (dynamic)" : "");
1756 /* If we're using a queued driver, start the queue */
1757 if (master->transfer)
1758 dev_info(dev, "master is unqueued, this is deprecated\n");
1760 status = spi_master_initialize_queue(master);
1762 device_del(&master->dev);
1766 /* add statistics */
1767 spin_lock_init(&master->statistics.lock);
1769 mutex_lock(&board_lock);
1770 list_add_tail(&master->list, &spi_master_list);
1771 list_for_each_entry(bi, &board_list, list)
1772 spi_match_master_to_boardinfo(master, &bi->board_info);
1773 mutex_unlock(&board_lock);
1775 /* Register devices from the device tree and ACPI */
1776 of_register_spi_devices(master);
1777 acpi_register_spi_devices(master);
1781 EXPORT_SYMBOL_GPL(spi_register_master);
1783 static void devm_spi_unregister(struct device *dev, void *res)
1785 spi_unregister_master(*(struct spi_master **)res);
1789 * dev_spi_register_master - register managed SPI master controller
1790 * @dev: device managing SPI master
1791 * @master: initialized master, originally from spi_alloc_master()
1792 * Context: can sleep
1794 * Register a SPI device as with spi_register_master() which will
1795 * automatically be unregister
1797 int devm_spi_register_master(struct device *dev, struct spi_master *master)
1799 struct spi_master **ptr;
1802 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
1806 ret = spi_register_master(master);
1809 devres_add(dev, ptr);
1816 EXPORT_SYMBOL_GPL(devm_spi_register_master);
1818 static int __unregister(struct device *dev, void *null)
1820 spi_unregister_device(to_spi_device(dev));
1825 * spi_unregister_master - unregister SPI master controller
1826 * @master: the master being unregistered
1827 * Context: can sleep
1829 * This call is used only by SPI master controller drivers, which are the
1830 * only ones directly touching chip registers.
1832 * This must be called from context that can sleep.
1834 void spi_unregister_master(struct spi_master *master)
1838 if (master->queued) {
1839 if (spi_destroy_queue(master))
1840 dev_err(&master->dev, "queue remove failed\n");
1843 mutex_lock(&board_lock);
1844 list_del(&master->list);
1845 mutex_unlock(&board_lock);
1847 dummy = device_for_each_child(&master->dev, NULL, __unregister);
1848 device_unregister(&master->dev);
1850 EXPORT_SYMBOL_GPL(spi_unregister_master);
1852 int spi_master_suspend(struct spi_master *master)
1856 /* Basically no-ops for non-queued masters */
1857 if (!master->queued)
1860 ret = spi_stop_queue(master);
1862 dev_err(&master->dev, "queue stop failed\n");
1866 EXPORT_SYMBOL_GPL(spi_master_suspend);
1868 int spi_master_resume(struct spi_master *master)
1872 if (!master->queued)
1875 ret = spi_start_queue(master);
1877 dev_err(&master->dev, "queue restart failed\n");
1881 EXPORT_SYMBOL_GPL(spi_master_resume);
1883 static int __spi_master_match(struct device *dev, const void *data)
1885 struct spi_master *m;
1886 const u16 *bus_num = data;
1888 m = container_of(dev, struct spi_master, dev);
1889 return m->bus_num == *bus_num;
1893 * spi_busnum_to_master - look up master associated with bus_num
1894 * @bus_num: the master's bus number
1895 * Context: can sleep
1897 * This call may be used with devices that are registered after
1898 * arch init time. It returns a refcounted pointer to the relevant
1899 * spi_master (which the caller must release), or NULL if there is
1900 * no such master registered.
1902 struct spi_master *spi_busnum_to_master(u16 bus_num)
1905 struct spi_master *master = NULL;
1907 dev = class_find_device(&spi_master_class, NULL, &bus_num,
1908 __spi_master_match);
1910 master = container_of(dev, struct spi_master, dev);
1911 /* reference got in class_find_device */
1914 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
1917 /*-------------------------------------------------------------------------*/
1919 /* Core methods for SPI master protocol drivers. Some of the
1920 * other core methods are currently defined as inline functions.
1923 static int __spi_validate_bits_per_word(struct spi_master *master, u8 bits_per_word)
1925 if (master->bits_per_word_mask) {
1926 /* Only 32 bits fit in the mask */
1927 if (bits_per_word > 32)
1929 if (!(master->bits_per_word_mask &
1930 SPI_BPW_MASK(bits_per_word)))
1938 * spi_setup - setup SPI mode and clock rate
1939 * @spi: the device whose settings are being modified
1940 * Context: can sleep, and no requests are queued to the device
1942 * SPI protocol drivers may need to update the transfer mode if the
1943 * device doesn't work with its default. They may likewise need
1944 * to update clock rates or word sizes from initial values. This function
1945 * changes those settings, and must be called from a context that can sleep.
1946 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
1947 * effect the next time the device is selected and data is transferred to
1948 * or from it. When this function returns, the spi device is deselected.
1950 * Note that this call will fail if the protocol driver specifies an option
1951 * that the underlying controller or its driver does not support. For
1952 * example, not all hardware supports wire transfers using nine bit words,
1953 * LSB-first wire encoding, or active-high chipselects.
1955 int spi_setup(struct spi_device *spi)
1957 unsigned bad_bits, ugly_bits;
1960 /* check mode to prevent that DUAL and QUAD set at the same time
1962 if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
1963 ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
1965 "setup: can not select dual and quad at the same time\n");
1968 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
1970 if ((spi->mode & SPI_3WIRE) && (spi->mode &
1971 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
1973 /* help drivers fail *cleanly* when they need options
1974 * that aren't supported with their current master
1976 bad_bits = spi->mode & ~spi->master->mode_bits;
1977 ugly_bits = bad_bits &
1978 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD);
1981 "setup: ignoring unsupported mode bits %x\n",
1983 spi->mode &= ~ugly_bits;
1984 bad_bits &= ~ugly_bits;
1987 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
1992 if (!spi->bits_per_word)
1993 spi->bits_per_word = 8;
1995 status = __spi_validate_bits_per_word(spi->master, spi->bits_per_word);
1999 if (!spi->max_speed_hz)
2000 spi->max_speed_hz = spi->master->max_speed_hz;
2002 if (spi->master->setup)
2003 status = spi->master->setup(spi);
2005 spi_set_cs(spi, false);
2007 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
2008 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
2009 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
2010 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
2011 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
2012 (spi->mode & SPI_LOOP) ? "loopback, " : "",
2013 spi->bits_per_word, spi->max_speed_hz,
2018 EXPORT_SYMBOL_GPL(spi_setup);
2020 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
2022 struct spi_master *master = spi->master;
2023 struct spi_transfer *xfer;
2026 if (list_empty(&message->transfers))
2029 /* Half-duplex links include original MicroWire, and ones with
2030 * only one data pin like SPI_3WIRE (switches direction) or where
2031 * either MOSI or MISO is missing. They can also be caused by
2032 * software limitations.
2034 if ((master->flags & SPI_MASTER_HALF_DUPLEX)
2035 || (spi->mode & SPI_3WIRE)) {
2036 unsigned flags = master->flags;
2038 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2039 if (xfer->rx_buf && xfer->tx_buf)
2041 if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
2043 if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
2049 * Set transfer bits_per_word and max speed as spi device default if
2050 * it is not set for this transfer.
2051 * Set transfer tx_nbits and rx_nbits as single transfer default
2052 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
2054 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2055 message->frame_length += xfer->len;
2056 if (!xfer->bits_per_word)
2057 xfer->bits_per_word = spi->bits_per_word;
2059 if (!xfer->speed_hz)
2060 xfer->speed_hz = spi->max_speed_hz;
2061 if (!xfer->speed_hz)
2062 xfer->speed_hz = master->max_speed_hz;
2064 if (master->max_speed_hz &&
2065 xfer->speed_hz > master->max_speed_hz)
2066 xfer->speed_hz = master->max_speed_hz;
2068 if (__spi_validate_bits_per_word(master, xfer->bits_per_word))
2072 * SPI transfer length should be multiple of SPI word size
2073 * where SPI word size should be power-of-two multiple
2075 if (xfer->bits_per_word <= 8)
2077 else if (xfer->bits_per_word <= 16)
2082 /* No partial transfers accepted */
2083 if (xfer->len % w_size)
2086 if (xfer->speed_hz && master->min_speed_hz &&
2087 xfer->speed_hz < master->min_speed_hz)
2090 if (xfer->tx_buf && !xfer->tx_nbits)
2091 xfer->tx_nbits = SPI_NBITS_SINGLE;
2092 if (xfer->rx_buf && !xfer->rx_nbits)
2093 xfer->rx_nbits = SPI_NBITS_SINGLE;
2094 /* check transfer tx/rx_nbits:
2095 * 1. check the value matches one of single, dual and quad
2096 * 2. check tx/rx_nbits match the mode in spi_device
2099 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
2100 xfer->tx_nbits != SPI_NBITS_DUAL &&
2101 xfer->tx_nbits != SPI_NBITS_QUAD)
2103 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
2104 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
2106 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
2107 !(spi->mode & SPI_TX_QUAD))
2110 /* check transfer rx_nbits */
2112 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
2113 xfer->rx_nbits != SPI_NBITS_DUAL &&
2114 xfer->rx_nbits != SPI_NBITS_QUAD)
2116 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
2117 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
2119 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
2120 !(spi->mode & SPI_RX_QUAD))
2125 message->status = -EINPROGRESS;
2130 static int __spi_async(struct spi_device *spi, struct spi_message *message)
2132 struct spi_master *master = spi->master;
2136 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics, spi_async);
2137 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
2139 trace_spi_message_submit(message);
2141 return master->transfer(spi, message);
2145 * spi_async - asynchronous SPI transfer
2146 * @spi: device with which data will be exchanged
2147 * @message: describes the data transfers, including completion callback
2148 * Context: any (irqs may be blocked, etc)
2150 * This call may be used in_irq and other contexts which can't sleep,
2151 * as well as from task contexts which can sleep.
2153 * The completion callback is invoked in a context which can't sleep.
2154 * Before that invocation, the value of message->status is undefined.
2155 * When the callback is issued, message->status holds either zero (to
2156 * indicate complete success) or a negative error code. After that
2157 * callback returns, the driver which issued the transfer request may
2158 * deallocate the associated memory; it's no longer in use by any SPI
2159 * core or controller driver code.
2161 * Note that although all messages to a spi_device are handled in
2162 * FIFO order, messages may go to different devices in other orders.
2163 * Some device might be higher priority, or have various "hard" access
2164 * time requirements, for example.
2166 * On detection of any fault during the transfer, processing of
2167 * the entire message is aborted, and the device is deselected.
2168 * Until returning from the associated message completion callback,
2169 * no other spi_message queued to that device will be processed.
2170 * (This rule applies equally to all the synchronous transfer calls,
2171 * which are wrappers around this core asynchronous primitive.)
2173 int spi_async(struct spi_device *spi, struct spi_message *message)
2175 struct spi_master *master = spi->master;
2177 unsigned long flags;
2179 ret = __spi_validate(spi, message);
2183 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
2185 if (master->bus_lock_flag)
2188 ret = __spi_async(spi, message);
2190 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
2194 EXPORT_SYMBOL_GPL(spi_async);
2197 * spi_async_locked - version of spi_async with exclusive bus usage
2198 * @spi: device with which data will be exchanged
2199 * @message: describes the data transfers, including completion callback
2200 * Context: any (irqs may be blocked, etc)
2202 * This call may be used in_irq and other contexts which can't sleep,
2203 * as well as from task contexts which can sleep.
2205 * The completion callback is invoked in a context which can't sleep.
2206 * Before that invocation, the value of message->status is undefined.
2207 * When the callback is issued, message->status holds either zero (to
2208 * indicate complete success) or a negative error code. After that
2209 * callback returns, the driver which issued the transfer request may
2210 * deallocate the associated memory; it's no longer in use by any SPI
2211 * core or controller driver code.
2213 * Note that although all messages to a spi_device are handled in
2214 * FIFO order, messages may go to different devices in other orders.
2215 * Some device might be higher priority, or have various "hard" access
2216 * time requirements, for example.
2218 * On detection of any fault during the transfer, processing of
2219 * the entire message is aborted, and the device is deselected.
2220 * Until returning from the associated message completion callback,
2221 * no other spi_message queued to that device will be processed.
2222 * (This rule applies equally to all the synchronous transfer calls,
2223 * which are wrappers around this core asynchronous primitive.)
2225 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
2227 struct spi_master *master = spi->master;
2229 unsigned long flags;
2231 ret = __spi_validate(spi, message);
2235 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
2237 ret = __spi_async(spi, message);
2239 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
2244 EXPORT_SYMBOL_GPL(spi_async_locked);
2247 /*-------------------------------------------------------------------------*/
2249 /* Utility methods for SPI master protocol drivers, layered on
2250 * top of the core. Some other utility methods are defined as
2254 static void spi_complete(void *arg)
2259 static int __spi_sync(struct spi_device *spi, struct spi_message *message,
2262 DECLARE_COMPLETION_ONSTACK(done);
2264 struct spi_master *master = spi->master;
2265 unsigned long flags;
2267 status = __spi_validate(spi, message);
2271 message->complete = spi_complete;
2272 message->context = &done;
2275 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics, spi_sync);
2276 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
2279 mutex_lock(&master->bus_lock_mutex);
2281 /* If we're not using the legacy transfer method then we will
2282 * try to transfer in the calling context so special case.
2283 * This code would be less tricky if we could remove the
2284 * support for driver implemented message queues.
2286 if (master->transfer == spi_queued_transfer) {
2287 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
2289 trace_spi_message_submit(message);
2291 status = __spi_queued_transfer(spi, message, false);
2293 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
2295 status = spi_async_locked(spi, message);
2299 mutex_unlock(&master->bus_lock_mutex);
2302 /* Push out the messages in the calling context if we
2305 if (master->transfer == spi_queued_transfer) {
2306 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics,
2307 spi_sync_immediate);
2308 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
2309 spi_sync_immediate);
2310 __spi_pump_messages(master, false);
2313 wait_for_completion(&done);
2314 status = message->status;
2316 message->context = NULL;
2321 * spi_sync - blocking/synchronous SPI data transfers
2322 * @spi: device with which data will be exchanged
2323 * @message: describes the data transfers
2324 * Context: can sleep
2326 * This call may only be used from a context that may sleep. The sleep
2327 * is non-interruptible, and has no timeout. Low-overhead controller
2328 * drivers may DMA directly into and out of the message buffers.
2330 * Note that the SPI device's chip select is active during the message,
2331 * and then is normally disabled between messages. Drivers for some
2332 * frequently-used devices may want to minimize costs of selecting a chip,
2333 * by leaving it selected in anticipation that the next message will go
2334 * to the same chip. (That may increase power usage.)
2336 * Also, the caller is guaranteeing that the memory associated with the
2337 * message will not be freed before this call returns.
2339 * It returns zero on success, else a negative error code.
2341 int spi_sync(struct spi_device *spi, struct spi_message *message)
2343 return __spi_sync(spi, message, 0);
2345 EXPORT_SYMBOL_GPL(spi_sync);
2348 * spi_sync_locked - version of spi_sync with exclusive bus usage
2349 * @spi: device with which data will be exchanged
2350 * @message: describes the data transfers
2351 * Context: can sleep
2353 * This call may only be used from a context that may sleep. The sleep
2354 * is non-interruptible, and has no timeout. Low-overhead controller
2355 * drivers may DMA directly into and out of the message buffers.
2357 * This call should be used by drivers that require exclusive access to the
2358 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
2359 * be released by a spi_bus_unlock call when the exclusive access is over.
2361 * It returns zero on success, else a negative error code.
2363 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
2365 return __spi_sync(spi, message, 1);
2367 EXPORT_SYMBOL_GPL(spi_sync_locked);
2370 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
2371 * @master: SPI bus master that should be locked for exclusive bus access
2372 * Context: can sleep
2374 * This call may only be used from a context that may sleep. The sleep
2375 * is non-interruptible, and has no timeout.
2377 * This call should be used by drivers that require exclusive access to the
2378 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
2379 * exclusive access is over. Data transfer must be done by spi_sync_locked
2380 * and spi_async_locked calls when the SPI bus lock is held.
2382 * It returns zero on success, else a negative error code.
2384 int spi_bus_lock(struct spi_master *master)
2386 unsigned long flags;
2388 mutex_lock(&master->bus_lock_mutex);
2390 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
2391 master->bus_lock_flag = 1;
2392 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
2394 /* mutex remains locked until spi_bus_unlock is called */
2398 EXPORT_SYMBOL_GPL(spi_bus_lock);
2401 * spi_bus_unlock - release the lock for exclusive SPI bus usage
2402 * @master: SPI bus master that was locked for exclusive bus access
2403 * Context: can sleep
2405 * This call may only be used from a context that may sleep. The sleep
2406 * is non-interruptible, and has no timeout.
2408 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
2411 * It returns zero on success, else a negative error code.
2413 int spi_bus_unlock(struct spi_master *master)
2415 master->bus_lock_flag = 0;
2417 mutex_unlock(&master->bus_lock_mutex);
2421 EXPORT_SYMBOL_GPL(spi_bus_unlock);
2423 /* portable code must never pass more than 32 bytes */
2424 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
2429 * spi_write_then_read - SPI synchronous write followed by read
2430 * @spi: device with which data will be exchanged
2431 * @txbuf: data to be written (need not be dma-safe)
2432 * @n_tx: size of txbuf, in bytes
2433 * @rxbuf: buffer into which data will be read (need not be dma-safe)
2434 * @n_rx: size of rxbuf, in bytes
2435 * Context: can sleep
2437 * This performs a half duplex MicroWire style transaction with the
2438 * device, sending txbuf and then reading rxbuf. The return value
2439 * is zero for success, else a negative errno status code.
2440 * This call may only be used from a context that may sleep.
2442 * Parameters to this routine are always copied using a small buffer;
2443 * portable code should never use this for more than 32 bytes.
2444 * Performance-sensitive or bulk transfer code should instead use
2445 * spi_{async,sync}() calls with dma-safe buffers.
2447 int spi_write_then_read(struct spi_device *spi,
2448 const void *txbuf, unsigned n_tx,
2449 void *rxbuf, unsigned n_rx)
2451 static DEFINE_MUTEX(lock);
2454 struct spi_message message;
2455 struct spi_transfer x[2];
2458 /* Use preallocated DMA-safe buffer if we can. We can't avoid
2459 * copying here, (as a pure convenience thing), but we can
2460 * keep heap costs out of the hot path unless someone else is
2461 * using the pre-allocated buffer or the transfer is too large.
2463 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
2464 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
2465 GFP_KERNEL | GFP_DMA);
2472 spi_message_init(&message);
2473 memset(x, 0, sizeof(x));
2476 spi_message_add_tail(&x[0], &message);
2480 spi_message_add_tail(&x[1], &message);
2483 memcpy(local_buf, txbuf, n_tx);
2484 x[0].tx_buf = local_buf;
2485 x[1].rx_buf = local_buf + n_tx;
2488 status = spi_sync(spi, &message);
2490 memcpy(rxbuf, x[1].rx_buf, n_rx);
2492 if (x[0].tx_buf == buf)
2493 mutex_unlock(&lock);
2499 EXPORT_SYMBOL_GPL(spi_write_then_read);
2501 /*-------------------------------------------------------------------------*/
2503 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
2504 static int __spi_of_device_match(struct device *dev, void *data)
2506 return dev->of_node == data;
2509 /* must call put_device() when done with returned spi_device device */
2510 static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
2512 struct device *dev = bus_find_device(&spi_bus_type, NULL, node,
2513 __spi_of_device_match);
2514 return dev ? to_spi_device(dev) : NULL;
2517 static int __spi_of_master_match(struct device *dev, const void *data)
2519 return dev->of_node == data;
2522 /* the spi masters are not using spi_bus, so we find it with another way */
2523 static struct spi_master *of_find_spi_master_by_node(struct device_node *node)
2527 dev = class_find_device(&spi_master_class, NULL, node,
2528 __spi_of_master_match);
2532 /* reference got in class_find_device */
2533 return container_of(dev, struct spi_master, dev);
2536 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
2539 struct of_reconfig_data *rd = arg;
2540 struct spi_master *master;
2541 struct spi_device *spi;
2543 switch (of_reconfig_get_state_change(action, arg)) {
2544 case OF_RECONFIG_CHANGE_ADD:
2545 master = of_find_spi_master_by_node(rd->dn->parent);
2547 return NOTIFY_OK; /* not for us */
2549 spi = of_register_spi_device(master, rd->dn);
2550 put_device(&master->dev);
2553 pr_err("%s: failed to create for '%s'\n",
2554 __func__, rd->dn->full_name);
2555 return notifier_from_errno(PTR_ERR(spi));
2559 case OF_RECONFIG_CHANGE_REMOVE:
2560 /* find our device by node */
2561 spi = of_find_spi_device_by_node(rd->dn);
2563 return NOTIFY_OK; /* no? not meant for us */
2565 /* unregister takes one ref away */
2566 spi_unregister_device(spi);
2568 /* and put the reference of the find */
2569 put_device(&spi->dev);
2576 static struct notifier_block spi_of_notifier = {
2577 .notifier_call = of_spi_notify,
2579 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
2580 extern struct notifier_block spi_of_notifier;
2581 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
2583 static int __init spi_init(void)
2587 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
2593 status = bus_register(&spi_bus_type);
2597 status = class_register(&spi_master_class);
2601 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2602 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
2607 bus_unregister(&spi_bus_type);
2615 /* board_info is normally registered in arch_initcall(),
2616 * but even essential drivers wait till later
2618 * REVISIT only boardinfo really needs static linking. the rest (device and
2619 * driver registration) _could_ be dynamically linked (modular) ... costs
2620 * include needing to have boardinfo data structures be much more public.
2622 postcore_initcall(spi_init);