1 // SPDX-License-Identifier: GPL-2.0-or-later
4 // Copyright (C) 2005 David Brownell
5 // Copyright (C) 2008 Secret Lab Technologies Ltd.
7 #include <linux/kernel.h>
8 #include <linux/device.h>
9 #include <linux/init.h>
10 #include <linux/cache.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/dmaengine.h>
13 #include <linux/mutex.h>
14 #include <linux/of_device.h>
15 #include <linux/of_irq.h>
16 #include <linux/clk/clk-conf.h>
17 #include <linux/slab.h>
18 #include <linux/mod_devicetable.h>
19 #include <linux/spi/spi.h>
20 #include <linux/spi/spi-mem.h>
21 #include <linux/of_gpio.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/pm_domain.h>
25 #include <linux/property.h>
26 #include <linux/export.h>
27 #include <linux/sched/rt.h>
28 #include <uapi/linux/sched/types.h>
29 #include <linux/delay.h>
30 #include <linux/kthread.h>
31 #include <linux/ioport.h>
32 #include <linux/acpi.h>
33 #include <linux/highmem.h>
34 #include <linux/idr.h>
35 #include <linux/platform_data/x86/apple.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/spi.h>
39 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
42 #include "internals.h"
44 static DEFINE_IDR(spi_master_idr);
46 static void spidev_release(struct device *dev)
48 struct spi_device *spi = to_spi_device(dev);
50 /* spi controllers may cleanup for released devices */
51 if (spi->controller->cleanup)
52 spi->controller->cleanup(spi);
54 spi_controller_put(spi->controller);
55 kfree(spi->driver_override);
60 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
62 const struct spi_device *spi = to_spi_device(dev);
65 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
69 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
71 static DEVICE_ATTR_RO(modalias);
73 static ssize_t driver_override_store(struct device *dev,
74 struct device_attribute *a,
75 const char *buf, size_t count)
77 struct spi_device *spi = to_spi_device(dev);
78 const char *end = memchr(buf, '\n', count);
79 const size_t len = end ? end - buf : count;
80 const char *driver_override, *old;
82 /* We need to keep extra room for a newline when displaying value */
83 if (len >= (PAGE_SIZE - 1))
86 driver_override = kstrndup(buf, len, GFP_KERNEL);
91 old = spi->driver_override;
93 spi->driver_override = driver_override;
95 /* Empty string, disable driver override */
96 spi->driver_override = NULL;
97 kfree(driver_override);
105 static ssize_t driver_override_show(struct device *dev,
106 struct device_attribute *a, char *buf)
108 const struct spi_device *spi = to_spi_device(dev);
112 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
116 static DEVICE_ATTR_RW(driver_override);
118 #define SPI_STATISTICS_ATTRS(field, file) \
119 static ssize_t spi_controller_##field##_show(struct device *dev, \
120 struct device_attribute *attr, \
123 struct spi_controller *ctlr = container_of(dev, \
124 struct spi_controller, dev); \
125 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
127 static struct device_attribute dev_attr_spi_controller_##field = { \
128 .attr = { .name = file, .mode = 0444 }, \
129 .show = spi_controller_##field##_show, \
131 static ssize_t spi_device_##field##_show(struct device *dev, \
132 struct device_attribute *attr, \
135 struct spi_device *spi = to_spi_device(dev); \
136 return spi_statistics_##field##_show(&spi->statistics, buf); \
138 static struct device_attribute dev_attr_spi_device_##field = { \
139 .attr = { .name = file, .mode = 0444 }, \
140 .show = spi_device_##field##_show, \
143 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
144 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
147 unsigned long flags; \
149 spin_lock_irqsave(&stat->lock, flags); \
150 len = sprintf(buf, format_string, stat->field); \
151 spin_unlock_irqrestore(&stat->lock, flags); \
154 SPI_STATISTICS_ATTRS(name, file)
156 #define SPI_STATISTICS_SHOW(field, format_string) \
157 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
158 field, format_string)
160 SPI_STATISTICS_SHOW(messages, "%lu");
161 SPI_STATISTICS_SHOW(transfers, "%lu");
162 SPI_STATISTICS_SHOW(errors, "%lu");
163 SPI_STATISTICS_SHOW(timedout, "%lu");
165 SPI_STATISTICS_SHOW(spi_sync, "%lu");
166 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
167 SPI_STATISTICS_SHOW(spi_async, "%lu");
169 SPI_STATISTICS_SHOW(bytes, "%llu");
170 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
171 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
173 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
174 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
175 "transfer_bytes_histo_" number, \
176 transfer_bytes_histo[index], "%lu")
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
190 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
191 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
192 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
193 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
195 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
197 static struct attribute *spi_dev_attrs[] = {
198 &dev_attr_modalias.attr,
199 &dev_attr_driver_override.attr,
203 static const struct attribute_group spi_dev_group = {
204 .attrs = spi_dev_attrs,
207 static struct attribute *spi_device_statistics_attrs[] = {
208 &dev_attr_spi_device_messages.attr,
209 &dev_attr_spi_device_transfers.attr,
210 &dev_attr_spi_device_errors.attr,
211 &dev_attr_spi_device_timedout.attr,
212 &dev_attr_spi_device_spi_sync.attr,
213 &dev_attr_spi_device_spi_sync_immediate.attr,
214 &dev_attr_spi_device_spi_async.attr,
215 &dev_attr_spi_device_bytes.attr,
216 &dev_attr_spi_device_bytes_rx.attr,
217 &dev_attr_spi_device_bytes_tx.attr,
218 &dev_attr_spi_device_transfer_bytes_histo0.attr,
219 &dev_attr_spi_device_transfer_bytes_histo1.attr,
220 &dev_attr_spi_device_transfer_bytes_histo2.attr,
221 &dev_attr_spi_device_transfer_bytes_histo3.attr,
222 &dev_attr_spi_device_transfer_bytes_histo4.attr,
223 &dev_attr_spi_device_transfer_bytes_histo5.attr,
224 &dev_attr_spi_device_transfer_bytes_histo6.attr,
225 &dev_attr_spi_device_transfer_bytes_histo7.attr,
226 &dev_attr_spi_device_transfer_bytes_histo8.attr,
227 &dev_attr_spi_device_transfer_bytes_histo9.attr,
228 &dev_attr_spi_device_transfer_bytes_histo10.attr,
229 &dev_attr_spi_device_transfer_bytes_histo11.attr,
230 &dev_attr_spi_device_transfer_bytes_histo12.attr,
231 &dev_attr_spi_device_transfer_bytes_histo13.attr,
232 &dev_attr_spi_device_transfer_bytes_histo14.attr,
233 &dev_attr_spi_device_transfer_bytes_histo15.attr,
234 &dev_attr_spi_device_transfer_bytes_histo16.attr,
235 &dev_attr_spi_device_transfers_split_maxsize.attr,
239 static const struct attribute_group spi_device_statistics_group = {
240 .name = "statistics",
241 .attrs = spi_device_statistics_attrs,
244 static const struct attribute_group *spi_dev_groups[] = {
246 &spi_device_statistics_group,
250 static struct attribute *spi_controller_statistics_attrs[] = {
251 &dev_attr_spi_controller_messages.attr,
252 &dev_attr_spi_controller_transfers.attr,
253 &dev_attr_spi_controller_errors.attr,
254 &dev_attr_spi_controller_timedout.attr,
255 &dev_attr_spi_controller_spi_sync.attr,
256 &dev_attr_spi_controller_spi_sync_immediate.attr,
257 &dev_attr_spi_controller_spi_async.attr,
258 &dev_attr_spi_controller_bytes.attr,
259 &dev_attr_spi_controller_bytes_rx.attr,
260 &dev_attr_spi_controller_bytes_tx.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
274 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
275 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
276 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
277 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
278 &dev_attr_spi_controller_transfers_split_maxsize.attr,
282 static const struct attribute_group spi_controller_statistics_group = {
283 .name = "statistics",
284 .attrs = spi_controller_statistics_attrs,
287 static const struct attribute_group *spi_master_groups[] = {
288 &spi_controller_statistics_group,
292 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
293 struct spi_transfer *xfer,
294 struct spi_controller *ctlr)
297 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
302 spin_lock_irqsave(&stats->lock, flags);
305 stats->transfer_bytes_histo[l2len]++;
307 stats->bytes += xfer->len;
308 if ((xfer->tx_buf) &&
309 (xfer->tx_buf != ctlr->dummy_tx))
310 stats->bytes_tx += xfer->len;
311 if ((xfer->rx_buf) &&
312 (xfer->rx_buf != ctlr->dummy_rx))
313 stats->bytes_rx += xfer->len;
315 spin_unlock_irqrestore(&stats->lock, flags);
317 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
319 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
320 * and the sysfs version makes coldplug work too.
323 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
324 const struct spi_device *sdev)
326 while (id->name[0]) {
327 if (!strcmp(sdev->modalias, id->name))
334 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
336 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
338 return spi_match_id(sdrv->id_table, sdev);
340 EXPORT_SYMBOL_GPL(spi_get_device_id);
342 static int spi_match_device(struct device *dev, struct device_driver *drv)
344 const struct spi_device *spi = to_spi_device(dev);
345 const struct spi_driver *sdrv = to_spi_driver(drv);
347 /* Check override first, and if set, only use the named driver */
348 if (spi->driver_override)
349 return strcmp(spi->driver_override, drv->name) == 0;
351 /* Attempt an OF style match */
352 if (of_driver_match_device(dev, drv))
356 if (acpi_driver_match_device(dev, drv))
360 return !!spi_match_id(sdrv->id_table, spi);
362 return strcmp(spi->modalias, drv->name) == 0;
365 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
367 const struct spi_device *spi = to_spi_device(dev);
370 rc = acpi_device_uevent_modalias(dev, env);
374 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
377 static int spi_probe(struct device *dev)
379 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
380 struct spi_device *spi = to_spi_device(dev);
383 ret = of_clk_set_defaults(dev->of_node, false);
388 spi->irq = of_irq_get(dev->of_node, 0);
389 if (spi->irq == -EPROBE_DEFER)
390 return -EPROBE_DEFER;
395 ret = dev_pm_domain_attach(dev, true);
400 ret = sdrv->probe(spi);
402 dev_pm_domain_detach(dev, true);
408 static int spi_remove(struct device *dev)
410 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
415 ret = sdrv->remove(to_spi_device(dev));
418 "Failed to unbind driver (%pe), ignoring\n",
422 dev_pm_domain_detach(dev, true);
427 static void spi_shutdown(struct device *dev)
430 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
433 sdrv->shutdown(to_spi_device(dev));
437 struct bus_type spi_bus_type = {
439 .dev_groups = spi_dev_groups,
440 .match = spi_match_device,
441 .uevent = spi_uevent,
443 .remove = spi_remove,
444 .shutdown = spi_shutdown,
446 EXPORT_SYMBOL_GPL(spi_bus_type);
449 * __spi_register_driver - register a SPI driver
450 * @owner: owner module of the driver to register
451 * @sdrv: the driver to register
454 * Return: zero on success, else a negative error code.
456 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
458 sdrv->driver.owner = owner;
459 sdrv->driver.bus = &spi_bus_type;
460 return driver_register(&sdrv->driver);
462 EXPORT_SYMBOL_GPL(__spi_register_driver);
464 /*-------------------------------------------------------------------------*/
466 /* SPI devices should normally not be created by SPI device drivers; that
467 * would make them board-specific. Similarly with SPI controller drivers.
468 * Device registration normally goes into like arch/.../mach.../board-YYY.c
469 * with other readonly (flashable) information about mainboard devices.
473 struct list_head list;
474 struct spi_board_info board_info;
477 static LIST_HEAD(board_list);
478 static LIST_HEAD(spi_controller_list);
481 * Used to protect add/del operation for board_info list and
482 * spi_controller list, and their matching process
483 * also used to protect object of type struct idr
485 static DEFINE_MUTEX(board_lock);
488 * Prevents addition of devices with same chip select and
489 * addition of devices below an unregistering controller.
491 static DEFINE_MUTEX(spi_add_lock);
494 * spi_alloc_device - Allocate a new SPI device
495 * @ctlr: Controller to which device is connected
498 * Allows a driver to allocate and initialize a spi_device without
499 * registering it immediately. This allows a driver to directly
500 * fill the spi_device with device parameters before calling
501 * spi_add_device() on it.
503 * Caller is responsible to call spi_add_device() on the returned
504 * spi_device structure to add it to the SPI controller. If the caller
505 * needs to discard the spi_device without adding it, then it should
506 * call spi_dev_put() on it.
508 * Return: a pointer to the new device, or NULL.
510 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
512 struct spi_device *spi;
514 if (!spi_controller_get(ctlr))
517 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
519 spi_controller_put(ctlr);
523 spi->master = spi->controller = ctlr;
524 spi->dev.parent = &ctlr->dev;
525 spi->dev.bus = &spi_bus_type;
526 spi->dev.release = spidev_release;
527 spi->cs_gpio = -ENOENT;
528 spi->mode = ctlr->buswidth_override_bits;
530 spin_lock_init(&spi->statistics.lock);
532 device_initialize(&spi->dev);
535 EXPORT_SYMBOL_GPL(spi_alloc_device);
537 static void spi_dev_set_name(struct spi_device *spi)
539 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
542 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
546 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
550 static int spi_dev_check(struct device *dev, void *data)
552 struct spi_device *spi = to_spi_device(dev);
553 struct spi_device *new_spi = data;
555 if (spi->controller == new_spi->controller &&
556 spi->chip_select == new_spi->chip_select)
562 * spi_add_device - Add spi_device allocated with spi_alloc_device
563 * @spi: spi_device to register
565 * Companion function to spi_alloc_device. Devices allocated with
566 * spi_alloc_device can be added onto the spi bus with this function.
568 * Return: 0 on success; negative errno on failure
570 int spi_add_device(struct spi_device *spi)
572 struct spi_controller *ctlr = spi->controller;
573 struct device *dev = ctlr->dev.parent;
576 /* Chipselects are numbered 0..max; validate. */
577 if (spi->chip_select >= ctlr->num_chipselect) {
578 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
579 ctlr->num_chipselect);
583 /* Set the bus ID string */
584 spi_dev_set_name(spi);
586 /* We need to make sure there's no other device with this
587 * chipselect **BEFORE** we call setup(), else we'll trash
588 * its configuration. Lock against concurrent add() calls.
590 mutex_lock(&spi_add_lock);
592 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
594 dev_err(dev, "chipselect %d already in use\n",
599 /* Controller may unregister concurrently */
600 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
601 !device_is_registered(&ctlr->dev)) {
606 /* Descriptors take precedence */
608 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
609 else if (ctlr->cs_gpios)
610 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
612 /* Drivers may modify this initial i/o setup, but will
613 * normally rely on the device being setup. Devices
614 * using SPI_CS_HIGH can't coexist well otherwise...
616 status = spi_setup(spi);
618 dev_err(dev, "can't setup %s, status %d\n",
619 dev_name(&spi->dev), status);
623 /* Device may be bound to an active driver when this returns */
624 status = device_add(&spi->dev);
626 dev_err(dev, "can't add %s, status %d\n",
627 dev_name(&spi->dev), status);
629 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
632 mutex_unlock(&spi_add_lock);
635 EXPORT_SYMBOL_GPL(spi_add_device);
638 * spi_new_device - instantiate one new SPI device
639 * @ctlr: Controller to which device is connected
640 * @chip: Describes the SPI device
643 * On typical mainboards, this is purely internal; and it's not needed
644 * after board init creates the hard-wired devices. Some development
645 * platforms may not be able to use spi_register_board_info though, and
646 * this is exported so that for example a USB or parport based adapter
647 * driver could add devices (which it would learn about out-of-band).
649 * Return: the new device, or NULL.
651 struct spi_device *spi_new_device(struct spi_controller *ctlr,
652 struct spi_board_info *chip)
654 struct spi_device *proxy;
657 /* NOTE: caller did any chip->bus_num checks necessary.
659 * Also, unless we change the return value convention to use
660 * error-or-pointer (not NULL-or-pointer), troubleshootability
661 * suggests syslogged diagnostics are best here (ugh).
664 proxy = spi_alloc_device(ctlr);
668 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
670 proxy->chip_select = chip->chip_select;
671 proxy->max_speed_hz = chip->max_speed_hz;
672 proxy->mode = chip->mode;
673 proxy->irq = chip->irq;
674 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
675 proxy->dev.platform_data = (void *) chip->platform_data;
676 proxy->controller_data = chip->controller_data;
677 proxy->controller_state = NULL;
680 status = device_add_software_node(&proxy->dev, chip->swnode);
682 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
683 chip->modalias, status);
688 status = spi_add_device(proxy);
695 device_remove_software_node(&proxy->dev);
699 EXPORT_SYMBOL_GPL(spi_new_device);
702 * spi_unregister_device - unregister a single SPI device
703 * @spi: spi_device to unregister
705 * Start making the passed SPI device vanish. Normally this would be handled
706 * by spi_unregister_controller().
708 void spi_unregister_device(struct spi_device *spi)
713 if (spi->dev.of_node) {
714 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
715 of_node_put(spi->dev.of_node);
717 if (ACPI_COMPANION(&spi->dev))
718 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
719 device_remove_software_node(&spi->dev);
720 device_unregister(&spi->dev);
722 EXPORT_SYMBOL_GPL(spi_unregister_device);
724 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
725 struct spi_board_info *bi)
727 struct spi_device *dev;
729 if (ctlr->bus_num != bi->bus_num)
732 dev = spi_new_device(ctlr, bi);
734 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
739 * spi_register_board_info - register SPI devices for a given board
740 * @info: array of chip descriptors
741 * @n: how many descriptors are provided
744 * Board-specific early init code calls this (probably during arch_initcall)
745 * with segments of the SPI device table. Any device nodes are created later,
746 * after the relevant parent SPI controller (bus_num) is defined. We keep
747 * this table of devices forever, so that reloading a controller driver will
748 * not make Linux forget about these hard-wired devices.
750 * Other code can also call this, e.g. a particular add-on board might provide
751 * SPI devices through its expansion connector, so code initializing that board
752 * would naturally declare its SPI devices.
754 * The board info passed can safely be __initdata ... but be careful of
755 * any embedded pointers (platform_data, etc), they're copied as-is.
757 * Return: zero on success, else a negative error code.
759 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
761 struct boardinfo *bi;
767 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
771 for (i = 0; i < n; i++, bi++, info++) {
772 struct spi_controller *ctlr;
774 memcpy(&bi->board_info, info, sizeof(*info));
776 mutex_lock(&board_lock);
777 list_add_tail(&bi->list, &board_list);
778 list_for_each_entry(ctlr, &spi_controller_list, list)
779 spi_match_controller_to_boardinfo(ctlr,
781 mutex_unlock(&board_lock);
787 /*-------------------------------------------------------------------------*/
789 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
791 bool activate = enable;
794 * Avoid calling into the driver (or doing delays) if the chip select
795 * isn't actually changing from the last time this was called.
797 if (!force && (spi->controller->last_cs_enable == enable) &&
798 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
801 spi->controller->last_cs_enable = enable;
802 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
804 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
805 !spi->controller->set_cs_timing) {
807 spi_delay_exec(&spi->controller->cs_setup, NULL);
809 spi_delay_exec(&spi->controller->cs_hold, NULL);
812 if (spi->mode & SPI_CS_HIGH)
815 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
816 if (!(spi->mode & SPI_NO_CS)) {
818 /* polarity handled by gpiolib */
819 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
822 * invert the enable line, as active low is
825 gpio_set_value_cansleep(spi->cs_gpio, !enable);
827 /* Some SPI masters need both GPIO CS & slave_select */
828 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
829 spi->controller->set_cs)
830 spi->controller->set_cs(spi, !enable);
831 } else if (spi->controller->set_cs) {
832 spi->controller->set_cs(spi, !enable);
835 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
836 !spi->controller->set_cs_timing) {
838 spi_delay_exec(&spi->controller->cs_inactive, NULL);
842 #ifdef CONFIG_HAS_DMA
843 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
844 struct sg_table *sgt, void *buf, size_t len,
845 enum dma_data_direction dir)
847 const bool vmalloced_buf = is_vmalloc_addr(buf);
848 unsigned int max_seg_size = dma_get_max_seg_size(dev);
849 #ifdef CONFIG_HIGHMEM
850 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
851 (unsigned long)buf < (PKMAP_BASE +
852 (LAST_PKMAP * PAGE_SIZE)));
854 const bool kmap_buf = false;
858 struct page *vm_page;
859 struct scatterlist *sg;
864 if (vmalloced_buf || kmap_buf) {
865 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
866 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
867 } else if (virt_addr_valid(buf)) {
868 desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
869 sgs = DIV_ROUND_UP(len, desc_len);
874 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
879 for (i = 0; i < sgs; i++) {
881 if (vmalloced_buf || kmap_buf) {
883 * Next scatterlist entry size is the minimum between
884 * the desc_len and the remaining buffer length that
887 min = min_t(size_t, desc_len,
889 PAGE_SIZE - offset_in_page(buf)));
891 vm_page = vmalloc_to_page(buf);
893 vm_page = kmap_to_page(buf);
898 sg_set_page(sg, vm_page,
899 min, offset_in_page(buf));
901 min = min_t(size_t, len, desc_len);
903 sg_set_buf(sg, sg_buf, min);
911 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
924 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
925 struct sg_table *sgt, enum dma_data_direction dir)
927 if (sgt->orig_nents) {
928 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
933 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
935 struct device *tx_dev, *rx_dev;
936 struct spi_transfer *xfer;
943 tx_dev = ctlr->dma_tx->device->dev;
945 tx_dev = ctlr->dev.parent;
948 rx_dev = ctlr->dma_rx->device->dev;
950 rx_dev = ctlr->dev.parent;
952 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
953 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
956 if (xfer->tx_buf != NULL) {
957 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
958 (void *)xfer->tx_buf, xfer->len,
964 if (xfer->rx_buf != NULL) {
965 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
966 xfer->rx_buf, xfer->len,
969 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
976 ctlr->cur_msg_mapped = true;
981 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
983 struct spi_transfer *xfer;
984 struct device *tx_dev, *rx_dev;
986 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
990 tx_dev = ctlr->dma_tx->device->dev;
992 tx_dev = ctlr->dev.parent;
995 rx_dev = ctlr->dma_rx->device->dev;
997 rx_dev = ctlr->dev.parent;
999 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1000 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1003 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1004 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1007 ctlr->cur_msg_mapped = false;
1011 #else /* !CONFIG_HAS_DMA */
1012 static inline int __spi_map_msg(struct spi_controller *ctlr,
1013 struct spi_message *msg)
1018 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1019 struct spi_message *msg)
1023 #endif /* !CONFIG_HAS_DMA */
1025 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1026 struct spi_message *msg)
1028 struct spi_transfer *xfer;
1030 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1032 * Restore the original value of tx_buf or rx_buf if they are
1035 if (xfer->tx_buf == ctlr->dummy_tx)
1036 xfer->tx_buf = NULL;
1037 if (xfer->rx_buf == ctlr->dummy_rx)
1038 xfer->rx_buf = NULL;
1041 return __spi_unmap_msg(ctlr, msg);
1044 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1046 struct spi_transfer *xfer;
1048 unsigned int max_tx, max_rx;
1050 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1051 && !(msg->spi->mode & SPI_3WIRE)) {
1055 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1056 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1058 max_tx = max(xfer->len, max_tx);
1059 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1061 max_rx = max(xfer->len, max_rx);
1065 tmp = krealloc(ctlr->dummy_tx, max_tx,
1066 GFP_KERNEL | GFP_DMA);
1069 ctlr->dummy_tx = tmp;
1070 memset(tmp, 0, max_tx);
1074 tmp = krealloc(ctlr->dummy_rx, max_rx,
1075 GFP_KERNEL | GFP_DMA);
1078 ctlr->dummy_rx = tmp;
1081 if (max_tx || max_rx) {
1082 list_for_each_entry(xfer, &msg->transfers,
1087 xfer->tx_buf = ctlr->dummy_tx;
1089 xfer->rx_buf = ctlr->dummy_rx;
1094 return __spi_map_msg(ctlr, msg);
1097 static int spi_transfer_wait(struct spi_controller *ctlr,
1098 struct spi_message *msg,
1099 struct spi_transfer *xfer)
1101 struct spi_statistics *statm = &ctlr->statistics;
1102 struct spi_statistics *stats = &msg->spi->statistics;
1103 u32 speed_hz = xfer->speed_hz;
1104 unsigned long long ms;
1106 if (spi_controller_is_slave(ctlr)) {
1107 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1108 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1115 ms = 8LL * 1000LL * xfer->len;
1116 do_div(ms, speed_hz);
1117 ms += ms + 200; /* some tolerance */
1122 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1123 msecs_to_jiffies(ms));
1126 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1127 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1128 dev_err(&msg->spi->dev,
1129 "SPI transfer timed out\n");
1137 static void _spi_transfer_delay_ns(u32 ns)
1144 u32 us = DIV_ROUND_UP(ns, 1000);
1149 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1153 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1155 u32 delay = _delay->value;
1156 u32 unit = _delay->unit;
1163 case SPI_DELAY_UNIT_USECS:
1166 case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1168 case SPI_DELAY_UNIT_SCK:
1169 /* clock cycles need to be obtained from spi_transfer */
1172 /* if there is no effective speed know, then approximate
1173 * by underestimating with half the requested hz
1175 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1178 delay *= DIV_ROUND_UP(1000000000, hz);
1186 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1188 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1197 delay = spi_delay_to_ns(_delay, xfer);
1201 _spi_transfer_delay_ns(delay);
1205 EXPORT_SYMBOL_GPL(spi_delay_exec);
1207 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1208 struct spi_transfer *xfer)
1210 u32 delay = xfer->cs_change_delay.value;
1211 u32 unit = xfer->cs_change_delay.unit;
1214 /* return early on "fast" mode - for everything but USECS */
1216 if (unit == SPI_DELAY_UNIT_USECS)
1217 _spi_transfer_delay_ns(10000);
1221 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1223 dev_err_once(&msg->spi->dev,
1224 "Use of unsupported delay unit %i, using default of 10us\n",
1226 _spi_transfer_delay_ns(10000);
1231 * spi_transfer_one_message - Default implementation of transfer_one_message()
1233 * This is a standard implementation of transfer_one_message() for
1234 * drivers which implement a transfer_one() operation. It provides
1235 * standard handling of delays and chip select management.
1237 static int spi_transfer_one_message(struct spi_controller *ctlr,
1238 struct spi_message *msg)
1240 struct spi_transfer *xfer;
1241 bool keep_cs = false;
1243 struct spi_statistics *statm = &ctlr->statistics;
1244 struct spi_statistics *stats = &msg->spi->statistics;
1246 spi_set_cs(msg->spi, true, false);
1248 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1249 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1251 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1252 trace_spi_transfer_start(msg, xfer);
1254 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1255 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1257 if (!ctlr->ptp_sts_supported) {
1258 xfer->ptp_sts_word_pre = 0;
1259 ptp_read_system_prets(xfer->ptp_sts);
1262 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1263 reinit_completion(&ctlr->xfer_completion);
1266 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1268 if (ctlr->cur_msg_mapped &&
1269 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1270 __spi_unmap_msg(ctlr, msg);
1271 ctlr->fallback = true;
1272 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1276 SPI_STATISTICS_INCREMENT_FIELD(statm,
1278 SPI_STATISTICS_INCREMENT_FIELD(stats,
1280 dev_err(&msg->spi->dev,
1281 "SPI transfer failed: %d\n", ret);
1286 ret = spi_transfer_wait(ctlr, msg, xfer);
1292 dev_err(&msg->spi->dev,
1293 "Bufferless transfer has length %u\n",
1297 if (!ctlr->ptp_sts_supported) {
1298 ptp_read_system_postts(xfer->ptp_sts);
1299 xfer->ptp_sts_word_post = xfer->len;
1302 trace_spi_transfer_stop(msg, xfer);
1304 if (msg->status != -EINPROGRESS)
1307 spi_transfer_delay_exec(xfer);
1309 if (xfer->cs_change) {
1310 if (list_is_last(&xfer->transfer_list,
1314 spi_set_cs(msg->spi, false, false);
1315 _spi_transfer_cs_change_delay(msg, xfer);
1316 spi_set_cs(msg->spi, true, false);
1320 msg->actual_length += xfer->len;
1324 if (ret != 0 || !keep_cs)
1325 spi_set_cs(msg->spi, false, false);
1327 if (msg->status == -EINPROGRESS)
1330 if (msg->status && ctlr->handle_err)
1331 ctlr->handle_err(ctlr, msg);
1333 spi_finalize_current_message(ctlr);
1339 * spi_finalize_current_transfer - report completion of a transfer
1340 * @ctlr: the controller reporting completion
1342 * Called by SPI drivers using the core transfer_one_message()
1343 * implementation to notify it that the current interrupt driven
1344 * transfer has finished and the next one may be scheduled.
1346 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1348 complete(&ctlr->xfer_completion);
1350 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1352 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1354 if (ctlr->auto_runtime_pm) {
1355 pm_runtime_mark_last_busy(ctlr->dev.parent);
1356 pm_runtime_put_autosuspend(ctlr->dev.parent);
1361 * __spi_pump_messages - function which processes spi message queue
1362 * @ctlr: controller to process queue for
1363 * @in_kthread: true if we are in the context of the message pump thread
1365 * This function checks if there is any spi message in the queue that
1366 * needs processing and if so call out to the driver to initialize hardware
1367 * and transfer each message.
1369 * Note that it is called both from the kthread itself and also from
1370 * inside spi_sync(); the queue extraction handling at the top of the
1371 * function should deal with this safely.
1373 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1375 struct spi_transfer *xfer;
1376 struct spi_message *msg;
1377 bool was_busy = false;
1378 unsigned long flags;
1382 spin_lock_irqsave(&ctlr->queue_lock, flags);
1384 /* Make sure we are not already running a message */
1385 if (ctlr->cur_msg) {
1386 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1390 /* If another context is idling the device then defer */
1392 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1393 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1397 /* Check if the queue is idle */
1398 if (list_empty(&ctlr->queue) || !ctlr->running) {
1400 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1404 /* Defer any non-atomic teardown to the thread */
1406 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1407 !ctlr->unprepare_transfer_hardware) {
1408 spi_idle_runtime_pm(ctlr);
1410 trace_spi_controller_idle(ctlr);
1412 kthread_queue_work(ctlr->kworker,
1413 &ctlr->pump_messages);
1415 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1420 ctlr->idling = true;
1421 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1423 kfree(ctlr->dummy_rx);
1424 ctlr->dummy_rx = NULL;
1425 kfree(ctlr->dummy_tx);
1426 ctlr->dummy_tx = NULL;
1427 if (ctlr->unprepare_transfer_hardware &&
1428 ctlr->unprepare_transfer_hardware(ctlr))
1430 "failed to unprepare transfer hardware\n");
1431 spi_idle_runtime_pm(ctlr);
1432 trace_spi_controller_idle(ctlr);
1434 spin_lock_irqsave(&ctlr->queue_lock, flags);
1435 ctlr->idling = false;
1436 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1440 /* Extract head of queue */
1441 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1442 ctlr->cur_msg = msg;
1444 list_del_init(&msg->queue);
1449 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1451 mutex_lock(&ctlr->io_mutex);
1453 if (!was_busy && ctlr->auto_runtime_pm) {
1454 ret = pm_runtime_get_sync(ctlr->dev.parent);
1456 pm_runtime_put_noidle(ctlr->dev.parent);
1457 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1459 mutex_unlock(&ctlr->io_mutex);
1465 trace_spi_controller_busy(ctlr);
1467 if (!was_busy && ctlr->prepare_transfer_hardware) {
1468 ret = ctlr->prepare_transfer_hardware(ctlr);
1471 "failed to prepare transfer hardware: %d\n",
1474 if (ctlr->auto_runtime_pm)
1475 pm_runtime_put(ctlr->dev.parent);
1478 spi_finalize_current_message(ctlr);
1480 mutex_unlock(&ctlr->io_mutex);
1485 trace_spi_message_start(msg);
1487 if (ctlr->prepare_message) {
1488 ret = ctlr->prepare_message(ctlr, msg);
1490 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1493 spi_finalize_current_message(ctlr);
1496 ctlr->cur_msg_prepared = true;
1499 ret = spi_map_msg(ctlr, msg);
1502 spi_finalize_current_message(ctlr);
1506 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1507 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1508 xfer->ptp_sts_word_pre = 0;
1509 ptp_read_system_prets(xfer->ptp_sts);
1513 ret = ctlr->transfer_one_message(ctlr, msg);
1516 "failed to transfer one message from queue\n");
1521 mutex_unlock(&ctlr->io_mutex);
1523 /* Prod the scheduler in case transfer_one() was busy waiting */
1529 * spi_pump_messages - kthread work function which processes spi message queue
1530 * @work: pointer to kthread work struct contained in the controller struct
1532 static void spi_pump_messages(struct kthread_work *work)
1534 struct spi_controller *ctlr =
1535 container_of(work, struct spi_controller, pump_messages);
1537 __spi_pump_messages(ctlr, true);
1541 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1542 * TX timestamp for the requested byte from the SPI
1543 * transfer. The frequency with which this function
1544 * must be called (once per word, once for the whole
1545 * transfer, once per batch of words etc) is arbitrary
1546 * as long as the @tx buffer offset is greater than or
1547 * equal to the requested byte at the time of the
1548 * call. The timestamp is only taken once, at the
1549 * first such call. It is assumed that the driver
1550 * advances its @tx buffer pointer monotonically.
1551 * @ctlr: Pointer to the spi_controller structure of the driver
1552 * @xfer: Pointer to the transfer being timestamped
1553 * @progress: How many words (not bytes) have been transferred so far
1554 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1555 * transfer, for less jitter in time measurement. Only compatible
1556 * with PIO drivers. If true, must follow up with
1557 * spi_take_timestamp_post or otherwise system will crash.
1558 * WARNING: for fully predictable results, the CPU frequency must
1559 * also be under control (governor).
1561 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1562 struct spi_transfer *xfer,
1563 size_t progress, bool irqs_off)
1568 if (xfer->timestamped)
1571 if (progress > xfer->ptp_sts_word_pre)
1574 /* Capture the resolution of the timestamp */
1575 xfer->ptp_sts_word_pre = progress;
1578 local_irq_save(ctlr->irq_flags);
1582 ptp_read_system_prets(xfer->ptp_sts);
1584 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1587 * spi_take_timestamp_post - helper for drivers to collect the end of the
1588 * TX timestamp for the requested byte from the SPI
1589 * transfer. Can be called with an arbitrary
1590 * frequency: only the first call where @tx exceeds
1591 * or is equal to the requested word will be
1593 * @ctlr: Pointer to the spi_controller structure of the driver
1594 * @xfer: Pointer to the transfer being timestamped
1595 * @progress: How many words (not bytes) have been transferred so far
1596 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1598 void spi_take_timestamp_post(struct spi_controller *ctlr,
1599 struct spi_transfer *xfer,
1600 size_t progress, bool irqs_off)
1605 if (xfer->timestamped)
1608 if (progress < xfer->ptp_sts_word_post)
1611 ptp_read_system_postts(xfer->ptp_sts);
1614 local_irq_restore(ctlr->irq_flags);
1618 /* Capture the resolution of the timestamp */
1619 xfer->ptp_sts_word_post = progress;
1621 xfer->timestamped = true;
1623 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1626 * spi_set_thread_rt - set the controller to pump at realtime priority
1627 * @ctlr: controller to boost priority of
1629 * This can be called because the controller requested realtime priority
1630 * (by setting the ->rt value before calling spi_register_controller()) or
1631 * because a device on the bus said that its transfers needed realtime
1634 * NOTE: at the moment if any device on a bus says it needs realtime then
1635 * the thread will be at realtime priority for all transfers on that
1636 * controller. If this eventually becomes a problem we may see if we can
1637 * find a way to boost the priority only temporarily during relevant
1640 static void spi_set_thread_rt(struct spi_controller *ctlr)
1642 dev_info(&ctlr->dev,
1643 "will run message pump with realtime priority\n");
1644 sched_set_fifo(ctlr->kworker->task);
1647 static int spi_init_queue(struct spi_controller *ctlr)
1649 ctlr->running = false;
1652 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1653 if (IS_ERR(ctlr->kworker)) {
1654 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1655 return PTR_ERR(ctlr->kworker);
1658 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1661 * Controller config will indicate if this controller should run the
1662 * message pump with high (realtime) priority to reduce the transfer
1663 * latency on the bus by minimising the delay between a transfer
1664 * request and the scheduling of the message pump thread. Without this
1665 * setting the message pump thread will remain at default priority.
1668 spi_set_thread_rt(ctlr);
1674 * spi_get_next_queued_message() - called by driver to check for queued
1676 * @ctlr: the controller to check for queued messages
1678 * If there are more messages in the queue, the next message is returned from
1681 * Return: the next message in the queue, else NULL if the queue is empty.
1683 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1685 struct spi_message *next;
1686 unsigned long flags;
1688 /* get a pointer to the next message, if any */
1689 spin_lock_irqsave(&ctlr->queue_lock, flags);
1690 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1692 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1696 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1699 * spi_finalize_current_message() - the current message is complete
1700 * @ctlr: the controller to return the message to
1702 * Called by the driver to notify the core that the message in the front of the
1703 * queue is complete and can be removed from the queue.
1705 void spi_finalize_current_message(struct spi_controller *ctlr)
1707 struct spi_transfer *xfer;
1708 struct spi_message *mesg;
1709 unsigned long flags;
1712 spin_lock_irqsave(&ctlr->queue_lock, flags);
1713 mesg = ctlr->cur_msg;
1714 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1716 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1717 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1718 ptp_read_system_postts(xfer->ptp_sts);
1719 xfer->ptp_sts_word_post = xfer->len;
1723 if (unlikely(ctlr->ptp_sts_supported))
1724 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1725 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1727 spi_unmap_msg(ctlr, mesg);
1729 /* In the prepare_messages callback the spi bus has the opportunity to
1730 * split a transfer to smaller chunks.
1731 * Release splited transfers here since spi_map_msg is done on the
1732 * splited transfers.
1734 spi_res_release(ctlr, mesg);
1736 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1737 ret = ctlr->unprepare_message(ctlr, mesg);
1739 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1744 spin_lock_irqsave(&ctlr->queue_lock, flags);
1745 ctlr->cur_msg = NULL;
1746 ctlr->cur_msg_prepared = false;
1747 ctlr->fallback = false;
1748 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1749 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1751 trace_spi_message_done(mesg);
1755 mesg->complete(mesg->context);
1757 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1759 static int spi_start_queue(struct spi_controller *ctlr)
1761 unsigned long flags;
1763 spin_lock_irqsave(&ctlr->queue_lock, flags);
1765 if (ctlr->running || ctlr->busy) {
1766 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1770 ctlr->running = true;
1771 ctlr->cur_msg = NULL;
1772 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1774 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1779 static int spi_stop_queue(struct spi_controller *ctlr)
1781 unsigned long flags;
1782 unsigned limit = 500;
1785 spin_lock_irqsave(&ctlr->queue_lock, flags);
1788 * This is a bit lame, but is optimized for the common execution path.
1789 * A wait_queue on the ctlr->busy could be used, but then the common
1790 * execution path (pump_messages) would be required to call wake_up or
1791 * friends on every SPI message. Do this instead.
1793 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1794 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1795 usleep_range(10000, 11000);
1796 spin_lock_irqsave(&ctlr->queue_lock, flags);
1799 if (!list_empty(&ctlr->queue) || ctlr->busy)
1802 ctlr->running = false;
1804 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1807 dev_warn(&ctlr->dev, "could not stop message queue\n");
1813 static int spi_destroy_queue(struct spi_controller *ctlr)
1817 ret = spi_stop_queue(ctlr);
1820 * kthread_flush_worker will block until all work is done.
1821 * If the reason that stop_queue timed out is that the work will never
1822 * finish, then it does no good to call flush/stop thread, so
1826 dev_err(&ctlr->dev, "problem destroying queue\n");
1830 kthread_destroy_worker(ctlr->kworker);
1835 static int __spi_queued_transfer(struct spi_device *spi,
1836 struct spi_message *msg,
1839 struct spi_controller *ctlr = spi->controller;
1840 unsigned long flags;
1842 spin_lock_irqsave(&ctlr->queue_lock, flags);
1844 if (!ctlr->running) {
1845 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1848 msg->actual_length = 0;
1849 msg->status = -EINPROGRESS;
1851 list_add_tail(&msg->queue, &ctlr->queue);
1852 if (!ctlr->busy && need_pump)
1853 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1855 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1860 * spi_queued_transfer - transfer function for queued transfers
1861 * @spi: spi device which is requesting transfer
1862 * @msg: spi message which is to handled is queued to driver queue
1864 * Return: zero on success, else a negative error code.
1866 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1868 return __spi_queued_transfer(spi, msg, true);
1871 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1875 ctlr->transfer = spi_queued_transfer;
1876 if (!ctlr->transfer_one_message)
1877 ctlr->transfer_one_message = spi_transfer_one_message;
1879 /* Initialize and start queue */
1880 ret = spi_init_queue(ctlr);
1882 dev_err(&ctlr->dev, "problem initializing queue\n");
1883 goto err_init_queue;
1885 ctlr->queued = true;
1886 ret = spi_start_queue(ctlr);
1888 dev_err(&ctlr->dev, "problem starting queue\n");
1889 goto err_start_queue;
1895 spi_destroy_queue(ctlr);
1901 * spi_flush_queue - Send all pending messages in the queue from the callers'
1903 * @ctlr: controller to process queue for
1905 * This should be used when one wants to ensure all pending messages have been
1906 * sent before doing something. Is used by the spi-mem code to make sure SPI
1907 * memory operations do not preempt regular SPI transfers that have been queued
1908 * before the spi-mem operation.
1910 void spi_flush_queue(struct spi_controller *ctlr)
1912 if (ctlr->transfer == spi_queued_transfer)
1913 __spi_pump_messages(ctlr, false);
1916 /*-------------------------------------------------------------------------*/
1918 #if defined(CONFIG_OF)
1919 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1920 struct device_node *nc)
1925 /* Mode (clock phase/polarity/etc.) */
1926 if (of_property_read_bool(nc, "spi-cpha"))
1927 spi->mode |= SPI_CPHA;
1928 if (of_property_read_bool(nc, "spi-cpol"))
1929 spi->mode |= SPI_CPOL;
1930 if (of_property_read_bool(nc, "spi-3wire"))
1931 spi->mode |= SPI_3WIRE;
1932 if (of_property_read_bool(nc, "spi-lsb-first"))
1933 spi->mode |= SPI_LSB_FIRST;
1934 if (of_property_read_bool(nc, "spi-cs-high"))
1935 spi->mode |= SPI_CS_HIGH;
1937 /* Device DUAL/QUAD mode */
1938 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1941 spi->mode |= SPI_NO_TX;
1946 spi->mode |= SPI_TX_DUAL;
1949 spi->mode |= SPI_TX_QUAD;
1952 spi->mode |= SPI_TX_OCTAL;
1955 dev_warn(&ctlr->dev,
1956 "spi-tx-bus-width %d not supported\n",
1962 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1965 spi->mode |= SPI_NO_RX;
1970 spi->mode |= SPI_RX_DUAL;
1973 spi->mode |= SPI_RX_QUAD;
1976 spi->mode |= SPI_RX_OCTAL;
1979 dev_warn(&ctlr->dev,
1980 "spi-rx-bus-width %d not supported\n",
1986 if (spi_controller_is_slave(ctlr)) {
1987 if (!of_node_name_eq(nc, "slave")) {
1988 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
1995 /* Device address */
1996 rc = of_property_read_u32(nc, "reg", &value);
1998 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2002 spi->chip_select = value;
2005 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2006 spi->max_speed_hz = value;
2011 static struct spi_device *
2012 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2014 struct spi_device *spi;
2017 /* Alloc an spi_device */
2018 spi = spi_alloc_device(ctlr);
2020 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2025 /* Select device driver */
2026 rc = of_modalias_node(nc, spi->modalias,
2027 sizeof(spi->modalias));
2029 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2033 rc = of_spi_parse_dt(ctlr, spi, nc);
2037 /* Store a pointer to the node in the device structure */
2039 spi->dev.of_node = nc;
2041 /* Register the new device */
2042 rc = spi_add_device(spi);
2044 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2045 goto err_of_node_put;
2058 * of_register_spi_devices() - Register child devices onto the SPI bus
2059 * @ctlr: Pointer to spi_controller device
2061 * Registers an spi_device for each child node of controller node which
2062 * represents a valid SPI slave.
2064 static void of_register_spi_devices(struct spi_controller *ctlr)
2066 struct spi_device *spi;
2067 struct device_node *nc;
2069 if (!ctlr->dev.of_node)
2072 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2073 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2075 spi = of_register_spi_device(ctlr, nc);
2077 dev_warn(&ctlr->dev,
2078 "Failed to create SPI device for %pOF\n", nc);
2079 of_node_clear_flag(nc, OF_POPULATED);
2084 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2088 struct acpi_spi_lookup {
2089 struct spi_controller *ctlr;
2097 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2098 struct acpi_spi_lookup *lookup)
2100 const union acpi_object *obj;
2102 if (!x86_apple_machine)
2105 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2106 && obj->buffer.length >= 4)
2107 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2109 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2110 && obj->buffer.length == 8)
2111 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2113 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2114 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2115 lookup->mode |= SPI_LSB_FIRST;
2117 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2118 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2119 lookup->mode |= SPI_CPOL;
2121 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2122 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2123 lookup->mode |= SPI_CPHA;
2126 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2128 struct acpi_spi_lookup *lookup = data;
2129 struct spi_controller *ctlr = lookup->ctlr;
2131 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2132 struct acpi_resource_spi_serialbus *sb;
2133 acpi_handle parent_handle;
2136 sb = &ares->data.spi_serial_bus;
2137 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2139 status = acpi_get_handle(NULL,
2140 sb->resource_source.string_ptr,
2143 if (ACPI_FAILURE(status) ||
2144 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2148 * ACPI DeviceSelection numbering is handled by the
2149 * host controller driver in Windows and can vary
2150 * from driver to driver. In Linux we always expect
2151 * 0 .. max - 1 so we need to ask the driver to
2152 * translate between the two schemes.
2154 if (ctlr->fw_translate_cs) {
2155 int cs = ctlr->fw_translate_cs(ctlr,
2156 sb->device_selection);
2159 lookup->chip_select = cs;
2161 lookup->chip_select = sb->device_selection;
2164 lookup->max_speed_hz = sb->connection_speed;
2165 lookup->bits_per_word = sb->data_bit_length;
2167 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2168 lookup->mode |= SPI_CPHA;
2169 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2170 lookup->mode |= SPI_CPOL;
2171 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2172 lookup->mode |= SPI_CS_HIGH;
2174 } else if (lookup->irq < 0) {
2177 if (acpi_dev_resource_interrupt(ares, 0, &r))
2178 lookup->irq = r.start;
2181 /* Always tell the ACPI core to skip this resource */
2185 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2186 struct acpi_device *adev)
2188 acpi_handle parent_handle = NULL;
2189 struct list_head resource_list;
2190 struct acpi_spi_lookup lookup = {};
2191 struct spi_device *spi;
2194 if (acpi_bus_get_status(adev) || !adev->status.present ||
2195 acpi_device_enumerated(adev))
2201 INIT_LIST_HEAD(&resource_list);
2202 ret = acpi_dev_get_resources(adev, &resource_list,
2203 acpi_spi_add_resource, &lookup);
2204 acpi_dev_free_resource_list(&resource_list);
2207 /* found SPI in _CRS but it points to another controller */
2210 if (!lookup.max_speed_hz &&
2211 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2212 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2213 /* Apple does not use _CRS but nested devices for SPI slaves */
2214 acpi_spi_parse_apple_properties(adev, &lookup);
2217 if (!lookup.max_speed_hz)
2220 spi = spi_alloc_device(ctlr);
2222 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2223 dev_name(&adev->dev));
2224 return AE_NO_MEMORY;
2228 ACPI_COMPANION_SET(&spi->dev, adev);
2229 spi->max_speed_hz = lookup.max_speed_hz;
2230 spi->mode |= lookup.mode;
2231 spi->irq = lookup.irq;
2232 spi->bits_per_word = lookup.bits_per_word;
2233 spi->chip_select = lookup.chip_select;
2235 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2236 sizeof(spi->modalias));
2239 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2241 acpi_device_set_enumerated(adev);
2243 adev->power.flags.ignore_parent = true;
2244 if (spi_add_device(spi)) {
2245 adev->power.flags.ignore_parent = false;
2246 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2247 dev_name(&adev->dev));
2254 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2255 void *data, void **return_value)
2257 struct spi_controller *ctlr = data;
2258 struct acpi_device *adev;
2260 if (acpi_bus_get_device(handle, &adev))
2263 return acpi_register_spi_device(ctlr, adev);
2266 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2268 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2273 handle = ACPI_HANDLE(ctlr->dev.parent);
2277 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2278 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2279 acpi_spi_add_device, NULL, ctlr, NULL);
2280 if (ACPI_FAILURE(status))
2281 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2284 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2285 #endif /* CONFIG_ACPI */
2287 static void spi_controller_release(struct device *dev)
2289 struct spi_controller *ctlr;
2291 ctlr = container_of(dev, struct spi_controller, dev);
2295 static struct class spi_master_class = {
2296 .name = "spi_master",
2297 .owner = THIS_MODULE,
2298 .dev_release = spi_controller_release,
2299 .dev_groups = spi_master_groups,
2302 #ifdef CONFIG_SPI_SLAVE
2304 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2306 * @spi: device used for the current transfer
2308 int spi_slave_abort(struct spi_device *spi)
2310 struct spi_controller *ctlr = spi->controller;
2312 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2313 return ctlr->slave_abort(ctlr);
2317 EXPORT_SYMBOL_GPL(spi_slave_abort);
2319 static int match_true(struct device *dev, void *data)
2324 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2327 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2329 struct device *child;
2331 child = device_find_child(&ctlr->dev, NULL, match_true);
2332 return sprintf(buf, "%s\n",
2333 child ? to_spi_device(child)->modalias : NULL);
2336 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2337 const char *buf, size_t count)
2339 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2341 struct spi_device *spi;
2342 struct device *child;
2346 rc = sscanf(buf, "%31s", name);
2347 if (rc != 1 || !name[0])
2350 child = device_find_child(&ctlr->dev, NULL, match_true);
2352 /* Remove registered slave */
2353 device_unregister(child);
2357 if (strcmp(name, "(null)")) {
2358 /* Register new slave */
2359 spi = spi_alloc_device(ctlr);
2363 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2365 rc = spi_add_device(spi);
2375 static DEVICE_ATTR_RW(slave);
2377 static struct attribute *spi_slave_attrs[] = {
2378 &dev_attr_slave.attr,
2382 static const struct attribute_group spi_slave_group = {
2383 .attrs = spi_slave_attrs,
2386 static const struct attribute_group *spi_slave_groups[] = {
2387 &spi_controller_statistics_group,
2392 static struct class spi_slave_class = {
2393 .name = "spi_slave",
2394 .owner = THIS_MODULE,
2395 .dev_release = spi_controller_release,
2396 .dev_groups = spi_slave_groups,
2399 extern struct class spi_slave_class; /* dummy */
2403 * __spi_alloc_controller - allocate an SPI master or slave controller
2404 * @dev: the controller, possibly using the platform_bus
2405 * @size: how much zeroed driver-private data to allocate; the pointer to this
2406 * memory is in the driver_data field of the returned device, accessible
2407 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2408 * drivers granting DMA access to portions of their private data need to
2409 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2410 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2411 * slave (true) controller
2412 * Context: can sleep
2414 * This call is used only by SPI controller drivers, which are the
2415 * only ones directly touching chip registers. It's how they allocate
2416 * an spi_controller structure, prior to calling spi_register_controller().
2418 * This must be called from context that can sleep.
2420 * The caller is responsible for assigning the bus number and initializing the
2421 * controller's methods before calling spi_register_controller(); and (after
2422 * errors adding the device) calling spi_controller_put() to prevent a memory
2425 * Return: the SPI controller structure on success, else NULL.
2427 struct spi_controller *__spi_alloc_controller(struct device *dev,
2428 unsigned int size, bool slave)
2430 struct spi_controller *ctlr;
2431 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2436 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2440 device_initialize(&ctlr->dev);
2442 ctlr->num_chipselect = 1;
2443 ctlr->slave = slave;
2444 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2445 ctlr->dev.class = &spi_slave_class;
2447 ctlr->dev.class = &spi_master_class;
2448 ctlr->dev.parent = dev;
2449 pm_suspend_ignore_children(&ctlr->dev, true);
2450 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2454 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2456 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2458 spi_controller_put(*(struct spi_controller **)ctlr);
2462 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2463 * @dev: physical device of SPI controller
2464 * @size: how much zeroed driver-private data to allocate
2465 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2466 * Context: can sleep
2468 * Allocate an SPI controller and automatically release a reference on it
2469 * when @dev is unbound from its driver. Drivers are thus relieved from
2470 * having to call spi_controller_put().
2472 * The arguments to this function are identical to __spi_alloc_controller().
2474 * Return: the SPI controller structure on success, else NULL.
2476 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2480 struct spi_controller **ptr, *ctlr;
2482 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2487 ctlr = __spi_alloc_controller(dev, size, slave);
2489 ctlr->devm_allocated = true;
2491 devres_add(dev, ptr);
2498 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2501 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2504 struct device_node *np = ctlr->dev.of_node;
2509 nb = of_gpio_named_count(np, "cs-gpios");
2510 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2512 /* Return error only for an incorrectly formed cs-gpios property */
2513 if (nb == 0 || nb == -ENOENT)
2518 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2520 ctlr->cs_gpios = cs;
2522 if (!ctlr->cs_gpios)
2525 for (i = 0; i < ctlr->num_chipselect; i++)
2528 for (i = 0; i < nb; i++)
2529 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2534 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2541 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2542 * @ctlr: The SPI master to grab GPIO descriptors for
2544 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2547 struct gpio_desc **cs;
2548 struct device *dev = &ctlr->dev;
2549 unsigned long native_cs_mask = 0;
2550 unsigned int num_cs_gpios = 0;
2552 nb = gpiod_count(dev, "cs");
2554 /* No GPIOs at all is fine, else return the error */
2560 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2562 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2566 ctlr->cs_gpiods = cs;
2568 for (i = 0; i < nb; i++) {
2570 * Most chipselects are active low, the inverted
2571 * semantics are handled by special quirks in gpiolib,
2572 * so initializing them GPIOD_OUT_LOW here means
2573 * "unasserted", in most cases this will drive the physical
2576 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2579 return PTR_ERR(cs[i]);
2583 * If we find a CS GPIO, name it after the device and
2588 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2592 gpiod_set_consumer_name(cs[i], gpioname);
2597 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2598 dev_err(dev, "Invalid native chip select %d\n", i);
2601 native_cs_mask |= BIT(i);
2604 ctlr->unused_native_cs = ffz(native_cs_mask);
2605 if (num_cs_gpios && ctlr->max_native_cs &&
2606 ctlr->unused_native_cs >= ctlr->max_native_cs) {
2607 dev_err(dev, "No unused native chip select available\n");
2614 static int spi_controller_check_ops(struct spi_controller *ctlr)
2617 * The controller may implement only the high-level SPI-memory like
2618 * operations if it does not support regular SPI transfers, and this is
2620 * If ->mem_ops is NULL, we request that at least one of the
2621 * ->transfer_xxx() method be implemented.
2623 if (ctlr->mem_ops) {
2624 if (!ctlr->mem_ops->exec_op)
2626 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2627 !ctlr->transfer_one_message) {
2635 * spi_register_controller - register SPI master or slave controller
2636 * @ctlr: initialized master, originally from spi_alloc_master() or
2638 * Context: can sleep
2640 * SPI controllers connect to their drivers using some non-SPI bus,
2641 * such as the platform bus. The final stage of probe() in that code
2642 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2644 * SPI controllers use board specific (often SOC specific) bus numbers,
2645 * and board-specific addressing for SPI devices combines those numbers
2646 * with chip select numbers. Since SPI does not directly support dynamic
2647 * device identification, boards need configuration tables telling which
2648 * chip is at which address.
2650 * This must be called from context that can sleep. It returns zero on
2651 * success, else a negative error code (dropping the controller's refcount).
2652 * After a successful return, the caller is responsible for calling
2653 * spi_unregister_controller().
2655 * Return: zero on success, else a negative error code.
2657 int spi_register_controller(struct spi_controller *ctlr)
2659 struct device *dev = ctlr->dev.parent;
2660 struct boardinfo *bi;
2662 int id, first_dynamic;
2668 * Make sure all necessary hooks are implemented before registering
2669 * the SPI controller.
2671 status = spi_controller_check_ops(ctlr);
2675 if (ctlr->bus_num >= 0) {
2676 /* devices with a fixed bus num must check-in with the num */
2677 mutex_lock(&board_lock);
2678 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2679 ctlr->bus_num + 1, GFP_KERNEL);
2680 mutex_unlock(&board_lock);
2681 if (WARN(id < 0, "couldn't get idr"))
2682 return id == -ENOSPC ? -EBUSY : id;
2684 } else if (ctlr->dev.of_node) {
2685 /* allocate dynamic bus number using Linux idr */
2686 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2689 mutex_lock(&board_lock);
2690 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2691 ctlr->bus_num + 1, GFP_KERNEL);
2692 mutex_unlock(&board_lock);
2693 if (WARN(id < 0, "couldn't get idr"))
2694 return id == -ENOSPC ? -EBUSY : id;
2697 if (ctlr->bus_num < 0) {
2698 first_dynamic = of_alias_get_highest_id("spi");
2699 if (first_dynamic < 0)
2704 mutex_lock(&board_lock);
2705 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2707 mutex_unlock(&board_lock);
2708 if (WARN(id < 0, "couldn't get idr"))
2712 INIT_LIST_HEAD(&ctlr->queue);
2713 spin_lock_init(&ctlr->queue_lock);
2714 spin_lock_init(&ctlr->bus_lock_spinlock);
2715 mutex_init(&ctlr->bus_lock_mutex);
2716 mutex_init(&ctlr->io_mutex);
2717 ctlr->bus_lock_flag = 0;
2718 init_completion(&ctlr->xfer_completion);
2719 if (!ctlr->max_dma_len)
2720 ctlr->max_dma_len = INT_MAX;
2722 /* register the device, then userspace will see it.
2723 * registration fails if the bus ID is in use.
2725 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2727 if (!spi_controller_is_slave(ctlr)) {
2728 if (ctlr->use_gpio_descriptors) {
2729 status = spi_get_gpio_descs(ctlr);
2733 * A controller using GPIO descriptors always
2734 * supports SPI_CS_HIGH if need be.
2736 ctlr->mode_bits |= SPI_CS_HIGH;
2738 /* Legacy code path for GPIOs from DT */
2739 status = of_spi_get_gpio_numbers(ctlr);
2746 * Even if it's just one always-selected device, there must
2747 * be at least one chipselect.
2749 if (!ctlr->num_chipselect) {
2754 status = device_add(&ctlr->dev);
2757 dev_dbg(dev, "registered %s %s\n",
2758 spi_controller_is_slave(ctlr) ? "slave" : "master",
2759 dev_name(&ctlr->dev));
2762 * If we're using a queued driver, start the queue. Note that we don't
2763 * need the queueing logic if the driver is only supporting high-level
2764 * memory operations.
2766 if (ctlr->transfer) {
2767 dev_info(dev, "controller is unqueued, this is deprecated\n");
2768 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2769 status = spi_controller_initialize_queue(ctlr);
2771 device_del(&ctlr->dev);
2775 /* add statistics */
2776 spin_lock_init(&ctlr->statistics.lock);
2778 mutex_lock(&board_lock);
2779 list_add_tail(&ctlr->list, &spi_controller_list);
2780 list_for_each_entry(bi, &board_list, list)
2781 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2782 mutex_unlock(&board_lock);
2784 /* Register devices from the device tree and ACPI */
2785 of_register_spi_devices(ctlr);
2786 acpi_register_spi_devices(ctlr);
2790 mutex_lock(&board_lock);
2791 idr_remove(&spi_master_idr, ctlr->bus_num);
2792 mutex_unlock(&board_lock);
2795 EXPORT_SYMBOL_GPL(spi_register_controller);
2797 static void devm_spi_unregister(void *ctlr)
2799 spi_unregister_controller(ctlr);
2803 * devm_spi_register_controller - register managed SPI master or slave
2805 * @dev: device managing SPI controller
2806 * @ctlr: initialized controller, originally from spi_alloc_master() or
2808 * Context: can sleep
2810 * Register a SPI device as with spi_register_controller() which will
2811 * automatically be unregistered and freed.
2813 * Return: zero on success, else a negative error code.
2815 int devm_spi_register_controller(struct device *dev,
2816 struct spi_controller *ctlr)
2820 ret = spi_register_controller(ctlr);
2824 return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
2826 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2828 static int __unregister(struct device *dev, void *null)
2830 spi_unregister_device(to_spi_device(dev));
2835 * spi_unregister_controller - unregister SPI master or slave controller
2836 * @ctlr: the controller being unregistered
2837 * Context: can sleep
2839 * This call is used only by SPI controller drivers, which are the
2840 * only ones directly touching chip registers.
2842 * This must be called from context that can sleep.
2844 * Note that this function also drops a reference to the controller.
2846 void spi_unregister_controller(struct spi_controller *ctlr)
2848 struct spi_controller *found;
2849 int id = ctlr->bus_num;
2851 /* Prevent addition of new devices, unregister existing ones */
2852 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2853 mutex_lock(&spi_add_lock);
2855 device_for_each_child(&ctlr->dev, NULL, __unregister);
2857 /* First make sure that this controller was ever added */
2858 mutex_lock(&board_lock);
2859 found = idr_find(&spi_master_idr, id);
2860 mutex_unlock(&board_lock);
2862 if (spi_destroy_queue(ctlr))
2863 dev_err(&ctlr->dev, "queue remove failed\n");
2865 mutex_lock(&board_lock);
2866 list_del(&ctlr->list);
2867 mutex_unlock(&board_lock);
2869 device_del(&ctlr->dev);
2871 /* Release the last reference on the controller if its driver
2872 * has not yet been converted to devm_spi_alloc_master/slave().
2874 if (!ctlr->devm_allocated)
2875 put_device(&ctlr->dev);
2878 mutex_lock(&board_lock);
2880 idr_remove(&spi_master_idr, id);
2881 mutex_unlock(&board_lock);
2883 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2884 mutex_unlock(&spi_add_lock);
2886 EXPORT_SYMBOL_GPL(spi_unregister_controller);
2888 int spi_controller_suspend(struct spi_controller *ctlr)
2892 /* Basically no-ops for non-queued controllers */
2896 ret = spi_stop_queue(ctlr);
2898 dev_err(&ctlr->dev, "queue stop failed\n");
2902 EXPORT_SYMBOL_GPL(spi_controller_suspend);
2904 int spi_controller_resume(struct spi_controller *ctlr)
2911 ret = spi_start_queue(ctlr);
2913 dev_err(&ctlr->dev, "queue restart failed\n");
2917 EXPORT_SYMBOL_GPL(spi_controller_resume);
2919 static int __spi_controller_match(struct device *dev, const void *data)
2921 struct spi_controller *ctlr;
2922 const u16 *bus_num = data;
2924 ctlr = container_of(dev, struct spi_controller, dev);
2925 return ctlr->bus_num == *bus_num;
2929 * spi_busnum_to_master - look up master associated with bus_num
2930 * @bus_num: the master's bus number
2931 * Context: can sleep
2933 * This call may be used with devices that are registered after
2934 * arch init time. It returns a refcounted pointer to the relevant
2935 * spi_controller (which the caller must release), or NULL if there is
2936 * no such master registered.
2938 * Return: the SPI master structure on success, else NULL.
2940 struct spi_controller *spi_busnum_to_master(u16 bus_num)
2943 struct spi_controller *ctlr = NULL;
2945 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2946 __spi_controller_match);
2948 ctlr = container_of(dev, struct spi_controller, dev);
2949 /* reference got in class_find_device */
2952 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2954 /*-------------------------------------------------------------------------*/
2956 /* Core methods for SPI resource management */
2959 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2960 * during the processing of a spi_message while using
2962 * @spi: the spi device for which we allocate memory
2963 * @release: the release code to execute for this resource
2964 * @size: size to alloc and return
2965 * @gfp: GFP allocation flags
2967 * Return: the pointer to the allocated data
2969 * This may get enhanced in the future to allocate from a memory pool
2970 * of the @spi_device or @spi_controller to avoid repeated allocations.
2972 void *spi_res_alloc(struct spi_device *spi,
2973 spi_res_release_t release,
2974 size_t size, gfp_t gfp)
2976 struct spi_res *sres;
2978 sres = kzalloc(sizeof(*sres) + size, gfp);
2982 INIT_LIST_HEAD(&sres->entry);
2983 sres->release = release;
2987 EXPORT_SYMBOL_GPL(spi_res_alloc);
2990 * spi_res_free - free an spi resource
2991 * @res: pointer to the custom data of a resource
2994 void spi_res_free(void *res)
2996 struct spi_res *sres = container_of(res, struct spi_res, data);
3001 WARN_ON(!list_empty(&sres->entry));
3004 EXPORT_SYMBOL_GPL(spi_res_free);
3007 * spi_res_add - add a spi_res to the spi_message
3008 * @message: the spi message
3009 * @res: the spi_resource
3011 void spi_res_add(struct spi_message *message, void *res)
3013 struct spi_res *sres = container_of(res, struct spi_res, data);
3015 WARN_ON(!list_empty(&sres->entry));
3016 list_add_tail(&sres->entry, &message->resources);
3018 EXPORT_SYMBOL_GPL(spi_res_add);
3021 * spi_res_release - release all spi resources for this message
3022 * @ctlr: the @spi_controller
3023 * @message: the @spi_message
3025 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3027 struct spi_res *res, *tmp;
3029 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3031 res->release(ctlr, message, res->data);
3033 list_del(&res->entry);
3038 EXPORT_SYMBOL_GPL(spi_res_release);
3040 /*-------------------------------------------------------------------------*/
3042 /* Core methods for spi_message alterations */
3044 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3045 struct spi_message *msg,
3048 struct spi_replaced_transfers *rxfer = res;
3051 /* call extra callback if requested */
3053 rxfer->release(ctlr, msg, res);
3055 /* insert replaced transfers back into the message */
3056 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3058 /* remove the formerly inserted entries */
3059 for (i = 0; i < rxfer->inserted; i++)
3060 list_del(&rxfer->inserted_transfers[i].transfer_list);
3064 * spi_replace_transfers - replace transfers with several transfers
3065 * and register change with spi_message.resources
3066 * @msg: the spi_message we work upon
3067 * @xfer_first: the first spi_transfer we want to replace
3068 * @remove: number of transfers to remove
3069 * @insert: the number of transfers we want to insert instead
3070 * @release: extra release code necessary in some circumstances
3071 * @extradatasize: extra data to allocate (with alignment guarantees
3072 * of struct @spi_transfer)
3075 * Returns: pointer to @spi_replaced_transfers,
3076 * PTR_ERR(...) in case of errors.
3078 struct spi_replaced_transfers *spi_replace_transfers(
3079 struct spi_message *msg,
3080 struct spi_transfer *xfer_first,
3083 spi_replaced_release_t release,
3084 size_t extradatasize,
3087 struct spi_replaced_transfers *rxfer;
3088 struct spi_transfer *xfer;
3091 /* allocate the structure using spi_res */
3092 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3093 struct_size(rxfer, inserted_transfers, insert)
3097 return ERR_PTR(-ENOMEM);
3099 /* the release code to invoke before running the generic release */
3100 rxfer->release = release;
3102 /* assign extradata */
3105 &rxfer->inserted_transfers[insert];
3107 /* init the replaced_transfers list */
3108 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3110 /* assign the list_entry after which we should reinsert
3111 * the @replaced_transfers - it may be spi_message.messages!
3113 rxfer->replaced_after = xfer_first->transfer_list.prev;
3115 /* remove the requested number of transfers */
3116 for (i = 0; i < remove; i++) {
3117 /* if the entry after replaced_after it is msg->transfers
3118 * then we have been requested to remove more transfers
3119 * than are in the list
3121 if (rxfer->replaced_after->next == &msg->transfers) {
3122 dev_err(&msg->spi->dev,
3123 "requested to remove more spi_transfers than are available\n");
3124 /* insert replaced transfers back into the message */
3125 list_splice(&rxfer->replaced_transfers,
3126 rxfer->replaced_after);
3128 /* free the spi_replace_transfer structure */
3129 spi_res_free(rxfer);
3131 /* and return with an error */
3132 return ERR_PTR(-EINVAL);
3135 /* remove the entry after replaced_after from list of
3136 * transfers and add it to list of replaced_transfers
3138 list_move_tail(rxfer->replaced_after->next,
3139 &rxfer->replaced_transfers);
3142 /* create copy of the given xfer with identical settings
3143 * based on the first transfer to get removed
3145 for (i = 0; i < insert; i++) {
3146 /* we need to run in reverse order */
3147 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3149 /* copy all spi_transfer data */
3150 memcpy(xfer, xfer_first, sizeof(*xfer));
3153 list_add(&xfer->transfer_list, rxfer->replaced_after);
3155 /* clear cs_change and delay for all but the last */
3157 xfer->cs_change = false;
3158 xfer->delay.value = 0;
3162 /* set up inserted */
3163 rxfer->inserted = insert;
3165 /* and register it with spi_res/spi_message */
3166 spi_res_add(msg, rxfer);
3170 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3172 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3173 struct spi_message *msg,
3174 struct spi_transfer **xferp,
3178 struct spi_transfer *xfer = *xferp, *xfers;
3179 struct spi_replaced_transfers *srt;
3183 /* calculate how many we have to replace */
3184 count = DIV_ROUND_UP(xfer->len, maxsize);
3186 /* create replacement */
3187 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3189 return PTR_ERR(srt);
3190 xfers = srt->inserted_transfers;
3192 /* now handle each of those newly inserted spi_transfers
3193 * note that the replacements spi_transfers all are preset
3194 * to the same values as *xferp, so tx_buf, rx_buf and len
3195 * are all identical (as well as most others)
3196 * so we just have to fix up len and the pointers.
3198 * this also includes support for the depreciated
3199 * spi_message.is_dma_mapped interface
3202 /* the first transfer just needs the length modified, so we
3203 * run it outside the loop
3205 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3207 /* all the others need rx_buf/tx_buf also set */
3208 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3209 /* update rx_buf, tx_buf and dma */
3210 if (xfers[i].rx_buf)
3211 xfers[i].rx_buf += offset;
3212 if (xfers[i].rx_dma)
3213 xfers[i].rx_dma += offset;
3214 if (xfers[i].tx_buf)
3215 xfers[i].tx_buf += offset;
3216 if (xfers[i].tx_dma)
3217 xfers[i].tx_dma += offset;
3220 xfers[i].len = min(maxsize, xfers[i].len - offset);
3223 /* we set up xferp to the last entry we have inserted,
3224 * so that we skip those already split transfers
3226 *xferp = &xfers[count - 1];
3228 /* increment statistics counters */
3229 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3230 transfers_split_maxsize);
3231 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3232 transfers_split_maxsize);
3238 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3239 * when an individual transfer exceeds a
3241 * @ctlr: the @spi_controller for this transfer
3242 * @msg: the @spi_message to transform
3243 * @maxsize: the maximum when to apply this
3244 * @gfp: GFP allocation flags
3246 * Return: status of transformation
3248 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3249 struct spi_message *msg,
3253 struct spi_transfer *xfer;
3256 /* iterate over the transfer_list,
3257 * but note that xfer is advanced to the last transfer inserted
3258 * to avoid checking sizes again unnecessarily (also xfer does
3259 * potentiall belong to a different list by the time the
3260 * replacement has happened
3262 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3263 if (xfer->len > maxsize) {
3264 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3273 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3275 /*-------------------------------------------------------------------------*/
3277 /* Core methods for SPI controller protocol drivers. Some of the
3278 * other core methods are currently defined as inline functions.
3281 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3284 if (ctlr->bits_per_word_mask) {
3285 /* Only 32 bits fit in the mask */
3286 if (bits_per_word > 32)
3288 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3296 * spi_setup - setup SPI mode and clock rate
3297 * @spi: the device whose settings are being modified
3298 * Context: can sleep, and no requests are queued to the device
3300 * SPI protocol drivers may need to update the transfer mode if the
3301 * device doesn't work with its default. They may likewise need
3302 * to update clock rates or word sizes from initial values. This function
3303 * changes those settings, and must be called from a context that can sleep.
3304 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3305 * effect the next time the device is selected and data is transferred to
3306 * or from it. When this function returns, the spi device is deselected.
3308 * Note that this call will fail if the protocol driver specifies an option
3309 * that the underlying controller or its driver does not support. For
3310 * example, not all hardware supports wire transfers using nine bit words,
3311 * LSB-first wire encoding, or active-high chipselects.
3313 * Return: zero on success, else a negative error code.
3315 int spi_setup(struct spi_device *spi)
3317 unsigned bad_bits, ugly_bits;
3321 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3322 * are set at the same time
3324 if ((hweight_long(spi->mode &
3325 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3326 (hweight_long(spi->mode &
3327 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3329 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3332 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3334 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3335 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3336 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3338 /* help drivers fail *cleanly* when they need options
3339 * that aren't supported with their current controller
3340 * SPI_CS_WORD has a fallback software implementation,
3341 * so it is ignored here.
3343 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3344 SPI_NO_TX | SPI_NO_RX);
3345 /* nothing prevents from working with active-high CS in case if it
3346 * is driven by GPIO.
3348 if (gpio_is_valid(spi->cs_gpio))
3349 bad_bits &= ~SPI_CS_HIGH;
3350 ugly_bits = bad_bits &
3351 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3352 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3355 "setup: ignoring unsupported mode bits %x\n",
3357 spi->mode &= ~ugly_bits;
3358 bad_bits &= ~ugly_bits;
3361 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3366 if (!spi->bits_per_word)
3367 spi->bits_per_word = 8;
3369 status = __spi_validate_bits_per_word(spi->controller,
3370 spi->bits_per_word);
3374 if (spi->controller->max_speed_hz &&
3375 (!spi->max_speed_hz ||
3376 spi->max_speed_hz > spi->controller->max_speed_hz))
3377 spi->max_speed_hz = spi->controller->max_speed_hz;
3379 mutex_lock(&spi->controller->io_mutex);
3381 if (spi->controller->setup) {
3382 status = spi->controller->setup(spi);
3384 mutex_unlock(&spi->controller->io_mutex);
3385 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3391 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3392 status = pm_runtime_get_sync(spi->controller->dev.parent);
3394 mutex_unlock(&spi->controller->io_mutex);
3395 pm_runtime_put_noidle(spi->controller->dev.parent);
3396 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3402 * We do not want to return positive value from pm_runtime_get,
3403 * there are many instances of devices calling spi_setup() and
3404 * checking for a non-zero return value instead of a negative
3409 spi_set_cs(spi, false, true);
3410 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3411 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3413 spi_set_cs(spi, false, true);
3416 mutex_unlock(&spi->controller->io_mutex);
3418 if (spi->rt && !spi->controller->rt) {
3419 spi->controller->rt = true;
3420 spi_set_thread_rt(spi->controller);
3423 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3424 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
3425 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3426 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3427 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3428 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3429 spi->bits_per_word, spi->max_speed_hz,
3434 EXPORT_SYMBOL_GPL(spi_setup);
3437 * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3438 * @spi: the device that requires specific CS timing configuration
3439 * @setup: CS setup time specified via @spi_delay
3440 * @hold: CS hold time specified via @spi_delay
3441 * @inactive: CS inactive delay between transfers specified via @spi_delay
3443 * Return: zero on success, else a negative error code.
3445 int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
3446 struct spi_delay *hold, struct spi_delay *inactive)
3448 struct device *parent = spi->controller->dev.parent;
3452 if (spi->controller->set_cs_timing &&
3453 !(spi->cs_gpiod || gpio_is_valid(spi->cs_gpio))) {
3454 if (spi->controller->auto_runtime_pm) {
3455 status = pm_runtime_get_sync(parent);
3457 pm_runtime_put_noidle(parent);
3458 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3463 status = spi->controller->set_cs_timing(spi, setup,
3465 pm_runtime_mark_last_busy(parent);
3466 pm_runtime_put_autosuspend(parent);
3469 return spi->controller->set_cs_timing(spi, setup, hold,
3474 if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
3475 (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
3476 (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
3478 "Clock-cycle delays for CS not supported in SW mode\n");
3482 len = sizeof(struct spi_delay);
3484 /* copy delays to controller */
3486 memcpy(&spi->controller->cs_setup, setup, len);
3488 memset(&spi->controller->cs_setup, 0, len);
3491 memcpy(&spi->controller->cs_hold, hold, len);
3493 memset(&spi->controller->cs_hold, 0, len);
3496 memcpy(&spi->controller->cs_inactive, inactive, len);
3498 memset(&spi->controller->cs_inactive, 0, len);
3502 EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3504 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3505 struct spi_device *spi)
3509 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3513 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3517 if (delay1 < delay2)
3518 memcpy(&xfer->word_delay, &spi->word_delay,
3519 sizeof(xfer->word_delay));
3524 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3526 struct spi_controller *ctlr = spi->controller;
3527 struct spi_transfer *xfer;
3530 if (list_empty(&message->transfers))
3533 /* If an SPI controller does not support toggling the CS line on each
3534 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3535 * for the CS line, we can emulate the CS-per-word hardware function by
3536 * splitting transfers into one-word transfers and ensuring that
3537 * cs_change is set for each transfer.
3539 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3541 gpio_is_valid(spi->cs_gpio))) {
3545 maxsize = (spi->bits_per_word + 7) / 8;
3547 /* spi_split_transfers_maxsize() requires message->spi */
3550 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3555 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3556 /* don't change cs_change on the last entry in the list */
3557 if (list_is_last(&xfer->transfer_list, &message->transfers))
3559 xfer->cs_change = 1;
3563 /* Half-duplex links include original MicroWire, and ones with
3564 * only one data pin like SPI_3WIRE (switches direction) or where
3565 * either MOSI or MISO is missing. They can also be caused by
3566 * software limitations.
3568 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3569 (spi->mode & SPI_3WIRE)) {
3570 unsigned flags = ctlr->flags;
3572 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3573 if (xfer->rx_buf && xfer->tx_buf)
3575 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3577 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3583 * Set transfer bits_per_word and max speed as spi device default if
3584 * it is not set for this transfer.
3585 * Set transfer tx_nbits and rx_nbits as single transfer default
3586 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3587 * Ensure transfer word_delay is at least as long as that required by
3590 message->frame_length = 0;
3591 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3592 xfer->effective_speed_hz = 0;
3593 message->frame_length += xfer->len;
3594 if (!xfer->bits_per_word)
3595 xfer->bits_per_word = spi->bits_per_word;
3597 if (!xfer->speed_hz)
3598 xfer->speed_hz = spi->max_speed_hz;
3600 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3601 xfer->speed_hz = ctlr->max_speed_hz;
3603 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3607 * SPI transfer length should be multiple of SPI word size
3608 * where SPI word size should be power-of-two multiple
3610 if (xfer->bits_per_word <= 8)
3612 else if (xfer->bits_per_word <= 16)
3617 /* No partial transfers accepted */
3618 if (xfer->len % w_size)
3621 if (xfer->speed_hz && ctlr->min_speed_hz &&
3622 xfer->speed_hz < ctlr->min_speed_hz)
3625 if (xfer->tx_buf && !xfer->tx_nbits)
3626 xfer->tx_nbits = SPI_NBITS_SINGLE;
3627 if (xfer->rx_buf && !xfer->rx_nbits)
3628 xfer->rx_nbits = SPI_NBITS_SINGLE;
3629 /* check transfer tx/rx_nbits:
3630 * 1. check the value matches one of single, dual and quad
3631 * 2. check tx/rx_nbits match the mode in spi_device
3634 if (spi->mode & SPI_NO_TX)
3636 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3637 xfer->tx_nbits != SPI_NBITS_DUAL &&
3638 xfer->tx_nbits != SPI_NBITS_QUAD)
3640 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3641 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3643 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3644 !(spi->mode & SPI_TX_QUAD))
3647 /* check transfer rx_nbits */
3649 if (spi->mode & SPI_NO_RX)
3651 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3652 xfer->rx_nbits != SPI_NBITS_DUAL &&
3653 xfer->rx_nbits != SPI_NBITS_QUAD)
3655 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3656 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3658 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3659 !(spi->mode & SPI_RX_QUAD))
3663 if (_spi_xfer_word_delay_update(xfer, spi))
3667 message->status = -EINPROGRESS;
3672 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3674 struct spi_controller *ctlr = spi->controller;
3675 struct spi_transfer *xfer;
3678 * Some controllers do not support doing regular SPI transfers. Return
3679 * ENOTSUPP when this is the case.
3681 if (!ctlr->transfer)
3686 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3687 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3689 trace_spi_message_submit(message);
3691 if (!ctlr->ptp_sts_supported) {
3692 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3693 xfer->ptp_sts_word_pre = 0;
3694 ptp_read_system_prets(xfer->ptp_sts);
3698 return ctlr->transfer(spi, message);
3702 * spi_async - asynchronous SPI transfer
3703 * @spi: device with which data will be exchanged
3704 * @message: describes the data transfers, including completion callback
3705 * Context: any (irqs may be blocked, etc)
3707 * This call may be used in_irq and other contexts which can't sleep,
3708 * as well as from task contexts which can sleep.
3710 * The completion callback is invoked in a context which can't sleep.
3711 * Before that invocation, the value of message->status is undefined.
3712 * When the callback is issued, message->status holds either zero (to
3713 * indicate complete success) or a negative error code. After that
3714 * callback returns, the driver which issued the transfer request may
3715 * deallocate the associated memory; it's no longer in use by any SPI
3716 * core or controller driver code.
3718 * Note that although all messages to a spi_device are handled in
3719 * FIFO order, messages may go to different devices in other orders.
3720 * Some device might be higher priority, or have various "hard" access
3721 * time requirements, for example.
3723 * On detection of any fault during the transfer, processing of
3724 * the entire message is aborted, and the device is deselected.
3725 * Until returning from the associated message completion callback,
3726 * no other spi_message queued to that device will be processed.
3727 * (This rule applies equally to all the synchronous transfer calls,
3728 * which are wrappers around this core asynchronous primitive.)
3730 * Return: zero on success, else a negative error code.
3732 int spi_async(struct spi_device *spi, struct spi_message *message)
3734 struct spi_controller *ctlr = spi->controller;
3736 unsigned long flags;
3738 ret = __spi_validate(spi, message);
3742 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3744 if (ctlr->bus_lock_flag)
3747 ret = __spi_async(spi, message);
3749 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3753 EXPORT_SYMBOL_GPL(spi_async);
3756 * spi_async_locked - version of spi_async with exclusive bus usage
3757 * @spi: device with which data will be exchanged
3758 * @message: describes the data transfers, including completion callback
3759 * Context: any (irqs may be blocked, etc)
3761 * This call may be used in_irq and other contexts which can't sleep,
3762 * as well as from task contexts which can sleep.
3764 * The completion callback is invoked in a context which can't sleep.
3765 * Before that invocation, the value of message->status is undefined.
3766 * When the callback is issued, message->status holds either zero (to
3767 * indicate complete success) or a negative error code. After that
3768 * callback returns, the driver which issued the transfer request may
3769 * deallocate the associated memory; it's no longer in use by any SPI
3770 * core or controller driver code.
3772 * Note that although all messages to a spi_device are handled in
3773 * FIFO order, messages may go to different devices in other orders.
3774 * Some device might be higher priority, or have various "hard" access
3775 * time requirements, for example.
3777 * On detection of any fault during the transfer, processing of
3778 * the entire message is aborted, and the device is deselected.
3779 * Until returning from the associated message completion callback,
3780 * no other spi_message queued to that device will be processed.
3781 * (This rule applies equally to all the synchronous transfer calls,
3782 * which are wrappers around this core asynchronous primitive.)
3784 * Return: zero on success, else a negative error code.
3786 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3788 struct spi_controller *ctlr = spi->controller;
3790 unsigned long flags;
3792 ret = __spi_validate(spi, message);
3796 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3798 ret = __spi_async(spi, message);
3800 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3805 EXPORT_SYMBOL_GPL(spi_async_locked);
3807 /*-------------------------------------------------------------------------*/
3809 /* Utility methods for SPI protocol drivers, layered on
3810 * top of the core. Some other utility methods are defined as
3814 static void spi_complete(void *arg)
3819 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3821 DECLARE_COMPLETION_ONSTACK(done);
3823 struct spi_controller *ctlr = spi->controller;
3824 unsigned long flags;
3826 status = __spi_validate(spi, message);
3830 message->complete = spi_complete;
3831 message->context = &done;
3834 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3835 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3837 /* If we're not using the legacy transfer method then we will
3838 * try to transfer in the calling context so special case.
3839 * This code would be less tricky if we could remove the
3840 * support for driver implemented message queues.
3842 if (ctlr->transfer == spi_queued_transfer) {
3843 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3845 trace_spi_message_submit(message);
3847 status = __spi_queued_transfer(spi, message, false);
3849 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3851 status = spi_async_locked(spi, message);
3855 /* Push out the messages in the calling context if we
3858 if (ctlr->transfer == spi_queued_transfer) {
3859 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3860 spi_sync_immediate);
3861 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3862 spi_sync_immediate);
3863 __spi_pump_messages(ctlr, false);
3866 wait_for_completion(&done);
3867 status = message->status;
3869 message->context = NULL;
3874 * spi_sync - blocking/synchronous SPI data transfers
3875 * @spi: device with which data will be exchanged
3876 * @message: describes the data transfers
3877 * Context: can sleep
3879 * This call may only be used from a context that may sleep. The sleep
3880 * is non-interruptible, and has no timeout. Low-overhead controller
3881 * drivers may DMA directly into and out of the message buffers.
3883 * Note that the SPI device's chip select is active during the message,
3884 * and then is normally disabled between messages. Drivers for some
3885 * frequently-used devices may want to minimize costs of selecting a chip,
3886 * by leaving it selected in anticipation that the next message will go
3887 * to the same chip. (That may increase power usage.)
3889 * Also, the caller is guaranteeing that the memory associated with the
3890 * message will not be freed before this call returns.
3892 * Return: zero on success, else a negative error code.
3894 int spi_sync(struct spi_device *spi, struct spi_message *message)
3898 mutex_lock(&spi->controller->bus_lock_mutex);
3899 ret = __spi_sync(spi, message);
3900 mutex_unlock(&spi->controller->bus_lock_mutex);
3904 EXPORT_SYMBOL_GPL(spi_sync);
3907 * spi_sync_locked - version of spi_sync with exclusive bus usage
3908 * @spi: device with which data will be exchanged
3909 * @message: describes the data transfers
3910 * Context: can sleep
3912 * This call may only be used from a context that may sleep. The sleep
3913 * is non-interruptible, and has no timeout. Low-overhead controller
3914 * drivers may DMA directly into and out of the message buffers.
3916 * This call should be used by drivers that require exclusive access to the
3917 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3918 * be released by a spi_bus_unlock call when the exclusive access is over.
3920 * Return: zero on success, else a negative error code.
3922 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3924 return __spi_sync(spi, message);
3926 EXPORT_SYMBOL_GPL(spi_sync_locked);
3929 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3930 * @ctlr: SPI bus master that should be locked for exclusive bus access
3931 * Context: can sleep
3933 * This call may only be used from a context that may sleep. The sleep
3934 * is non-interruptible, and has no timeout.
3936 * This call should be used by drivers that require exclusive access to the
3937 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3938 * exclusive access is over. Data transfer must be done by spi_sync_locked
3939 * and spi_async_locked calls when the SPI bus lock is held.
3941 * Return: always zero.
3943 int spi_bus_lock(struct spi_controller *ctlr)
3945 unsigned long flags;
3947 mutex_lock(&ctlr->bus_lock_mutex);
3949 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3950 ctlr->bus_lock_flag = 1;
3951 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3953 /* mutex remains locked until spi_bus_unlock is called */
3957 EXPORT_SYMBOL_GPL(spi_bus_lock);
3960 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3961 * @ctlr: SPI bus master that was locked for exclusive bus access
3962 * Context: can sleep
3964 * This call may only be used from a context that may sleep. The sleep
3965 * is non-interruptible, and has no timeout.
3967 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3970 * Return: always zero.
3972 int spi_bus_unlock(struct spi_controller *ctlr)
3974 ctlr->bus_lock_flag = 0;
3976 mutex_unlock(&ctlr->bus_lock_mutex);
3980 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3982 /* portable code must never pass more than 32 bytes */
3983 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
3988 * spi_write_then_read - SPI synchronous write followed by read
3989 * @spi: device with which data will be exchanged
3990 * @txbuf: data to be written (need not be dma-safe)
3991 * @n_tx: size of txbuf, in bytes
3992 * @rxbuf: buffer into which data will be read (need not be dma-safe)
3993 * @n_rx: size of rxbuf, in bytes
3994 * Context: can sleep
3996 * This performs a half duplex MicroWire style transaction with the
3997 * device, sending txbuf and then reading rxbuf. The return value
3998 * is zero for success, else a negative errno status code.
3999 * This call may only be used from a context that may sleep.
4001 * Parameters to this routine are always copied using a small buffer.
4002 * Performance-sensitive or bulk transfer code should instead use
4003 * spi_{async,sync}() calls with dma-safe buffers.
4005 * Return: zero on success, else a negative error code.
4007 int spi_write_then_read(struct spi_device *spi,
4008 const void *txbuf, unsigned n_tx,
4009 void *rxbuf, unsigned n_rx)
4011 static DEFINE_MUTEX(lock);
4014 struct spi_message message;
4015 struct spi_transfer x[2];
4018 /* Use preallocated DMA-safe buffer if we can. We can't avoid
4019 * copying here, (as a pure convenience thing), but we can
4020 * keep heap costs out of the hot path unless someone else is
4021 * using the pre-allocated buffer or the transfer is too large.
4023 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4024 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4025 GFP_KERNEL | GFP_DMA);
4032 spi_message_init(&message);
4033 memset(x, 0, sizeof(x));
4036 spi_message_add_tail(&x[0], &message);
4040 spi_message_add_tail(&x[1], &message);
4043 memcpy(local_buf, txbuf, n_tx);
4044 x[0].tx_buf = local_buf;
4045 x[1].rx_buf = local_buf + n_tx;
4048 status = spi_sync(spi, &message);
4050 memcpy(rxbuf, x[1].rx_buf, n_rx);
4052 if (x[0].tx_buf == buf)
4053 mutex_unlock(&lock);
4059 EXPORT_SYMBOL_GPL(spi_write_then_read);
4061 /*-------------------------------------------------------------------------*/
4063 #if IS_ENABLED(CONFIG_OF)
4064 /* must call put_device() when done with returned spi_device device */
4065 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4067 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4069 return dev ? to_spi_device(dev) : NULL;
4071 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4072 #endif /* IS_ENABLED(CONFIG_OF) */
4074 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4075 /* the spi controllers are not using spi_bus, so we find it with another way */
4076 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4080 dev = class_find_device_by_of_node(&spi_master_class, node);
4081 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4082 dev = class_find_device_by_of_node(&spi_slave_class, node);
4086 /* reference got in class_find_device */
4087 return container_of(dev, struct spi_controller, dev);
4090 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4093 struct of_reconfig_data *rd = arg;
4094 struct spi_controller *ctlr;
4095 struct spi_device *spi;
4097 switch (of_reconfig_get_state_change(action, arg)) {
4098 case OF_RECONFIG_CHANGE_ADD:
4099 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4101 return NOTIFY_OK; /* not for us */
4103 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4104 put_device(&ctlr->dev);
4108 spi = of_register_spi_device(ctlr, rd->dn);
4109 put_device(&ctlr->dev);
4112 pr_err("%s: failed to create for '%pOF'\n",
4114 of_node_clear_flag(rd->dn, OF_POPULATED);
4115 return notifier_from_errno(PTR_ERR(spi));
4119 case OF_RECONFIG_CHANGE_REMOVE:
4120 /* already depopulated? */
4121 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4124 /* find our device by node */
4125 spi = of_find_spi_device_by_node(rd->dn);
4127 return NOTIFY_OK; /* no? not meant for us */
4129 /* unregister takes one ref away */
4130 spi_unregister_device(spi);
4132 /* and put the reference of the find */
4133 put_device(&spi->dev);
4140 static struct notifier_block spi_of_notifier = {
4141 .notifier_call = of_spi_notify,
4143 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4144 extern struct notifier_block spi_of_notifier;
4145 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4147 #if IS_ENABLED(CONFIG_ACPI)
4148 static int spi_acpi_controller_match(struct device *dev, const void *data)
4150 return ACPI_COMPANION(dev->parent) == data;
4153 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4157 dev = class_find_device(&spi_master_class, NULL, adev,
4158 spi_acpi_controller_match);
4159 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4160 dev = class_find_device(&spi_slave_class, NULL, adev,
4161 spi_acpi_controller_match);
4165 return container_of(dev, struct spi_controller, dev);
4168 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4172 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4173 return to_spi_device(dev);
4176 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4179 struct acpi_device *adev = arg;
4180 struct spi_controller *ctlr;
4181 struct spi_device *spi;
4184 case ACPI_RECONFIG_DEVICE_ADD:
4185 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4189 acpi_register_spi_device(ctlr, adev);
4190 put_device(&ctlr->dev);
4192 case ACPI_RECONFIG_DEVICE_REMOVE:
4193 if (!acpi_device_enumerated(adev))
4196 spi = acpi_spi_find_device_by_adev(adev);
4200 spi_unregister_device(spi);
4201 put_device(&spi->dev);
4208 static struct notifier_block spi_acpi_notifier = {
4209 .notifier_call = acpi_spi_notify,
4212 extern struct notifier_block spi_acpi_notifier;
4215 static int __init spi_init(void)
4219 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4225 status = bus_register(&spi_bus_type);
4229 status = class_register(&spi_master_class);
4233 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4234 status = class_register(&spi_slave_class);
4239 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4240 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4241 if (IS_ENABLED(CONFIG_ACPI))
4242 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4247 class_unregister(&spi_master_class);
4249 bus_unregister(&spi_bus_type);
4257 /* board_info is normally registered in arch_initcall(),
4258 * but even essential drivers wait till later
4260 * REVISIT only boardinfo really needs static linking. the rest (device and
4261 * driver registration) _could_ be dynamically linked (modular) ... costs
4262 * include needing to have boardinfo data structures be much more public.
4264 postcore_initcall(spi_init);