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_controller_put(spi->controller);
51 kfree(spi->driver_override);
56 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
58 const struct spi_device *spi = to_spi_device(dev);
61 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
65 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
67 static DEVICE_ATTR_RO(modalias);
69 static ssize_t driver_override_store(struct device *dev,
70 struct device_attribute *a,
71 const char *buf, size_t count)
73 struct spi_device *spi = to_spi_device(dev);
74 const char *end = memchr(buf, '\n', count);
75 const size_t len = end ? end - buf : count;
76 const char *driver_override, *old;
78 /* We need to keep extra room for a newline when displaying value */
79 if (len >= (PAGE_SIZE - 1))
82 driver_override = kstrndup(buf, len, GFP_KERNEL);
87 old = spi->driver_override;
89 spi->driver_override = driver_override;
91 /* Empty string, disable driver override */
92 spi->driver_override = NULL;
93 kfree(driver_override);
101 static ssize_t driver_override_show(struct device *dev,
102 struct device_attribute *a, char *buf)
104 const struct spi_device *spi = to_spi_device(dev);
108 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
112 static DEVICE_ATTR_RW(driver_override);
114 #define SPI_STATISTICS_ATTRS(field, file) \
115 static ssize_t spi_controller_##field##_show(struct device *dev, \
116 struct device_attribute *attr, \
119 struct spi_controller *ctlr = container_of(dev, \
120 struct spi_controller, dev); \
121 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
123 static struct device_attribute dev_attr_spi_controller_##field = { \
124 .attr = { .name = file, .mode = 0444 }, \
125 .show = spi_controller_##field##_show, \
127 static ssize_t spi_device_##field##_show(struct device *dev, \
128 struct device_attribute *attr, \
131 struct spi_device *spi = to_spi_device(dev); \
132 return spi_statistics_##field##_show(&spi->statistics, buf); \
134 static struct device_attribute dev_attr_spi_device_##field = { \
135 .attr = { .name = file, .mode = 0444 }, \
136 .show = spi_device_##field##_show, \
139 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
140 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
143 unsigned long flags; \
145 spin_lock_irqsave(&stat->lock, flags); \
146 len = sprintf(buf, format_string, stat->field); \
147 spin_unlock_irqrestore(&stat->lock, flags); \
150 SPI_STATISTICS_ATTRS(name, file)
152 #define SPI_STATISTICS_SHOW(field, format_string) \
153 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
154 field, format_string)
156 SPI_STATISTICS_SHOW(messages, "%lu");
157 SPI_STATISTICS_SHOW(transfers, "%lu");
158 SPI_STATISTICS_SHOW(errors, "%lu");
159 SPI_STATISTICS_SHOW(timedout, "%lu");
161 SPI_STATISTICS_SHOW(spi_sync, "%lu");
162 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
163 SPI_STATISTICS_SHOW(spi_async, "%lu");
165 SPI_STATISTICS_SHOW(bytes, "%llu");
166 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
167 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
169 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
170 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
171 "transfer_bytes_histo_" number, \
172 transfer_bytes_histo[index], "%lu")
173 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
174 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
175 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
176 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
191 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
193 static struct attribute *spi_dev_attrs[] = {
194 &dev_attr_modalias.attr,
195 &dev_attr_driver_override.attr,
199 static const struct attribute_group spi_dev_group = {
200 .attrs = spi_dev_attrs,
203 static struct attribute *spi_device_statistics_attrs[] = {
204 &dev_attr_spi_device_messages.attr,
205 &dev_attr_spi_device_transfers.attr,
206 &dev_attr_spi_device_errors.attr,
207 &dev_attr_spi_device_timedout.attr,
208 &dev_attr_spi_device_spi_sync.attr,
209 &dev_attr_spi_device_spi_sync_immediate.attr,
210 &dev_attr_spi_device_spi_async.attr,
211 &dev_attr_spi_device_bytes.attr,
212 &dev_attr_spi_device_bytes_rx.attr,
213 &dev_attr_spi_device_bytes_tx.attr,
214 &dev_attr_spi_device_transfer_bytes_histo0.attr,
215 &dev_attr_spi_device_transfer_bytes_histo1.attr,
216 &dev_attr_spi_device_transfer_bytes_histo2.attr,
217 &dev_attr_spi_device_transfer_bytes_histo3.attr,
218 &dev_attr_spi_device_transfer_bytes_histo4.attr,
219 &dev_attr_spi_device_transfer_bytes_histo5.attr,
220 &dev_attr_spi_device_transfer_bytes_histo6.attr,
221 &dev_attr_spi_device_transfer_bytes_histo7.attr,
222 &dev_attr_spi_device_transfer_bytes_histo8.attr,
223 &dev_attr_spi_device_transfer_bytes_histo9.attr,
224 &dev_attr_spi_device_transfer_bytes_histo10.attr,
225 &dev_attr_spi_device_transfer_bytes_histo11.attr,
226 &dev_attr_spi_device_transfer_bytes_histo12.attr,
227 &dev_attr_spi_device_transfer_bytes_histo13.attr,
228 &dev_attr_spi_device_transfer_bytes_histo14.attr,
229 &dev_attr_spi_device_transfer_bytes_histo15.attr,
230 &dev_attr_spi_device_transfer_bytes_histo16.attr,
231 &dev_attr_spi_device_transfers_split_maxsize.attr,
235 static const struct attribute_group spi_device_statistics_group = {
236 .name = "statistics",
237 .attrs = spi_device_statistics_attrs,
240 static const struct attribute_group *spi_dev_groups[] = {
242 &spi_device_statistics_group,
246 static struct attribute *spi_controller_statistics_attrs[] = {
247 &dev_attr_spi_controller_messages.attr,
248 &dev_attr_spi_controller_transfers.attr,
249 &dev_attr_spi_controller_errors.attr,
250 &dev_attr_spi_controller_timedout.attr,
251 &dev_attr_spi_controller_spi_sync.attr,
252 &dev_attr_spi_controller_spi_sync_immediate.attr,
253 &dev_attr_spi_controller_spi_async.attr,
254 &dev_attr_spi_controller_bytes.attr,
255 &dev_attr_spi_controller_bytes_rx.attr,
256 &dev_attr_spi_controller_bytes_tx.attr,
257 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
258 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
259 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
260 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
274 &dev_attr_spi_controller_transfers_split_maxsize.attr,
278 static const struct attribute_group spi_controller_statistics_group = {
279 .name = "statistics",
280 .attrs = spi_controller_statistics_attrs,
283 static const struct attribute_group *spi_master_groups[] = {
284 &spi_controller_statistics_group,
288 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
289 struct spi_transfer *xfer,
290 struct spi_controller *ctlr)
293 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
298 spin_lock_irqsave(&stats->lock, flags);
301 stats->transfer_bytes_histo[l2len]++;
303 stats->bytes += xfer->len;
304 if ((xfer->tx_buf) &&
305 (xfer->tx_buf != ctlr->dummy_tx))
306 stats->bytes_tx += xfer->len;
307 if ((xfer->rx_buf) &&
308 (xfer->rx_buf != ctlr->dummy_rx))
309 stats->bytes_rx += xfer->len;
311 spin_unlock_irqrestore(&stats->lock, flags);
313 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
315 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
316 * and the sysfs version makes coldplug work too.
319 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
320 const struct spi_device *sdev)
322 while (id->name[0]) {
323 if (!strcmp(sdev->modalias, id->name))
330 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
332 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
334 return spi_match_id(sdrv->id_table, sdev);
336 EXPORT_SYMBOL_GPL(spi_get_device_id);
338 static int spi_match_device(struct device *dev, struct device_driver *drv)
340 const struct spi_device *spi = to_spi_device(dev);
341 const struct spi_driver *sdrv = to_spi_driver(drv);
343 /* Check override first, and if set, only use the named driver */
344 if (spi->driver_override)
345 return strcmp(spi->driver_override, drv->name) == 0;
347 /* Attempt an OF style match */
348 if (of_driver_match_device(dev, drv))
352 if (acpi_driver_match_device(dev, drv))
356 return !!spi_match_id(sdrv->id_table, spi);
358 return strcmp(spi->modalias, drv->name) == 0;
361 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
363 const struct spi_device *spi = to_spi_device(dev);
366 rc = acpi_device_uevent_modalias(dev, env);
370 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
373 static int spi_probe(struct device *dev)
375 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
376 struct spi_device *spi = to_spi_device(dev);
379 ret = of_clk_set_defaults(dev->of_node, false);
384 spi->irq = of_irq_get(dev->of_node, 0);
385 if (spi->irq == -EPROBE_DEFER)
386 return -EPROBE_DEFER;
391 ret = dev_pm_domain_attach(dev, true);
396 ret = sdrv->probe(spi);
398 dev_pm_domain_detach(dev, true);
404 static int spi_remove(struct device *dev)
406 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
411 ret = sdrv->remove(to_spi_device(dev));
414 "Failed to unbind driver (%pe), ignoring\n",
418 dev_pm_domain_detach(dev, true);
423 static void spi_shutdown(struct device *dev)
426 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
429 sdrv->shutdown(to_spi_device(dev));
433 struct bus_type spi_bus_type = {
435 .dev_groups = spi_dev_groups,
436 .match = spi_match_device,
437 .uevent = spi_uevent,
439 .remove = spi_remove,
440 .shutdown = spi_shutdown,
442 EXPORT_SYMBOL_GPL(spi_bus_type);
445 * __spi_register_driver - register a SPI driver
446 * @owner: owner module of the driver to register
447 * @sdrv: the driver to register
450 * Return: zero on success, else a negative error code.
452 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
454 sdrv->driver.owner = owner;
455 sdrv->driver.bus = &spi_bus_type;
456 return driver_register(&sdrv->driver);
458 EXPORT_SYMBOL_GPL(__spi_register_driver);
460 /*-------------------------------------------------------------------------*/
462 /* SPI devices should normally not be created by SPI device drivers; that
463 * would make them board-specific. Similarly with SPI controller drivers.
464 * Device registration normally goes into like arch/.../mach.../board-YYY.c
465 * with other readonly (flashable) information about mainboard devices.
469 struct list_head list;
470 struct spi_board_info board_info;
473 static LIST_HEAD(board_list);
474 static LIST_HEAD(spi_controller_list);
477 * Used to protect add/del operation for board_info list and
478 * spi_controller list, and their matching process
479 * also used to protect object of type struct idr
481 static DEFINE_MUTEX(board_lock);
484 * Prevents addition of devices with same chip select and
485 * addition of devices below an unregistering controller.
487 static DEFINE_MUTEX(spi_add_lock);
490 * spi_alloc_device - Allocate a new SPI device
491 * @ctlr: Controller to which device is connected
494 * Allows a driver to allocate and initialize a spi_device without
495 * registering it immediately. This allows a driver to directly
496 * fill the spi_device with device parameters before calling
497 * spi_add_device() on it.
499 * Caller is responsible to call spi_add_device() on the returned
500 * spi_device structure to add it to the SPI controller. If the caller
501 * needs to discard the spi_device without adding it, then it should
502 * call spi_dev_put() on it.
504 * Return: a pointer to the new device, or NULL.
506 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
508 struct spi_device *spi;
510 if (!spi_controller_get(ctlr))
513 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
515 spi_controller_put(ctlr);
519 spi->master = spi->controller = ctlr;
520 spi->dev.parent = &ctlr->dev;
521 spi->dev.bus = &spi_bus_type;
522 spi->dev.release = spidev_release;
523 spi->cs_gpio = -ENOENT;
524 spi->mode = ctlr->buswidth_override_bits;
526 spin_lock_init(&spi->statistics.lock);
528 device_initialize(&spi->dev);
531 EXPORT_SYMBOL_GPL(spi_alloc_device);
533 static void spi_dev_set_name(struct spi_device *spi)
535 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
538 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
542 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
546 static int spi_dev_check(struct device *dev, void *data)
548 struct spi_device *spi = to_spi_device(dev);
549 struct spi_device *new_spi = data;
551 if (spi->controller == new_spi->controller &&
552 spi->chip_select == new_spi->chip_select)
557 static void spi_cleanup(struct spi_device *spi)
559 if (spi->controller->cleanup)
560 spi->controller->cleanup(spi);
564 * spi_add_device - Add spi_device allocated with spi_alloc_device
565 * @spi: spi_device to register
567 * Companion function to spi_alloc_device. Devices allocated with
568 * spi_alloc_device can be added onto the spi bus with this function.
570 * Return: 0 on success; negative errno on failure
572 int spi_add_device(struct spi_device *spi)
574 struct spi_controller *ctlr = spi->controller;
575 struct device *dev = ctlr->dev.parent;
578 /* Chipselects are numbered 0..max; validate. */
579 if (spi->chip_select >= ctlr->num_chipselect) {
580 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
581 ctlr->num_chipselect);
585 /* Set the bus ID string */
586 spi_dev_set_name(spi);
588 /* We need to make sure there's no other device with this
589 * chipselect **BEFORE** we call setup(), else we'll trash
590 * its configuration. Lock against concurrent add() calls.
592 mutex_lock(&spi_add_lock);
594 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
596 dev_err(dev, "chipselect %d already in use\n",
601 /* Controller may unregister concurrently */
602 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
603 !device_is_registered(&ctlr->dev)) {
608 /* Descriptors take precedence */
610 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
611 else if (ctlr->cs_gpios)
612 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
614 /* Drivers may modify this initial i/o setup, but will
615 * normally rely on the device being setup. Devices
616 * using SPI_CS_HIGH can't coexist well otherwise...
618 status = spi_setup(spi);
620 dev_err(dev, "can't setup %s, status %d\n",
621 dev_name(&spi->dev), status);
625 /* Device may be bound to an active driver when this returns */
626 status = device_add(&spi->dev);
628 dev_err(dev, "can't add %s, status %d\n",
629 dev_name(&spi->dev), status);
632 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
636 mutex_unlock(&spi_add_lock);
639 EXPORT_SYMBOL_GPL(spi_add_device);
642 * spi_new_device - instantiate one new SPI device
643 * @ctlr: Controller to which device is connected
644 * @chip: Describes the SPI device
647 * On typical mainboards, this is purely internal; and it's not needed
648 * after board init creates the hard-wired devices. Some development
649 * platforms may not be able to use spi_register_board_info though, and
650 * this is exported so that for example a USB or parport based adapter
651 * driver could add devices (which it would learn about out-of-band).
653 * Return: the new device, or NULL.
655 struct spi_device *spi_new_device(struct spi_controller *ctlr,
656 struct spi_board_info *chip)
658 struct spi_device *proxy;
661 /* NOTE: caller did any chip->bus_num checks necessary.
663 * Also, unless we change the return value convention to use
664 * error-or-pointer (not NULL-or-pointer), troubleshootability
665 * suggests syslogged diagnostics are best here (ugh).
668 proxy = spi_alloc_device(ctlr);
672 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
674 proxy->chip_select = chip->chip_select;
675 proxy->max_speed_hz = chip->max_speed_hz;
676 proxy->mode = chip->mode;
677 proxy->irq = chip->irq;
678 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
679 proxy->dev.platform_data = (void *) chip->platform_data;
680 proxy->controller_data = chip->controller_data;
681 proxy->controller_state = NULL;
684 status = device_add_software_node(&proxy->dev, chip->swnode);
686 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
687 chip->modalias, status);
692 status = spi_add_device(proxy);
699 device_remove_software_node(&proxy->dev);
703 EXPORT_SYMBOL_GPL(spi_new_device);
706 * spi_unregister_device - unregister a single SPI device
707 * @spi: spi_device to unregister
709 * Start making the passed SPI device vanish. Normally this would be handled
710 * by spi_unregister_controller().
712 void spi_unregister_device(struct spi_device *spi)
719 if (spi->dev.of_node) {
720 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
721 of_node_put(spi->dev.of_node);
723 if (ACPI_COMPANION(&spi->dev))
724 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
725 device_remove_software_node(&spi->dev);
726 device_unregister(&spi->dev);
728 EXPORT_SYMBOL_GPL(spi_unregister_device);
730 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
731 struct spi_board_info *bi)
733 struct spi_device *dev;
735 if (ctlr->bus_num != bi->bus_num)
738 dev = spi_new_device(ctlr, bi);
740 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
745 * spi_register_board_info - register SPI devices for a given board
746 * @info: array of chip descriptors
747 * @n: how many descriptors are provided
750 * Board-specific early init code calls this (probably during arch_initcall)
751 * with segments of the SPI device table. Any device nodes are created later,
752 * after the relevant parent SPI controller (bus_num) is defined. We keep
753 * this table of devices forever, so that reloading a controller driver will
754 * not make Linux forget about these hard-wired devices.
756 * Other code can also call this, e.g. a particular add-on board might provide
757 * SPI devices through its expansion connector, so code initializing that board
758 * would naturally declare its SPI devices.
760 * The board info passed can safely be __initdata ... but be careful of
761 * any embedded pointers (platform_data, etc), they're copied as-is.
763 * Return: zero on success, else a negative error code.
765 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
767 struct boardinfo *bi;
773 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
777 for (i = 0; i < n; i++, bi++, info++) {
778 struct spi_controller *ctlr;
780 memcpy(&bi->board_info, info, sizeof(*info));
782 mutex_lock(&board_lock);
783 list_add_tail(&bi->list, &board_list);
784 list_for_each_entry(ctlr, &spi_controller_list, list)
785 spi_match_controller_to_boardinfo(ctlr,
787 mutex_unlock(&board_lock);
793 /*-------------------------------------------------------------------------*/
795 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
797 bool activate = enable;
800 * Avoid calling into the driver (or doing delays) if the chip select
801 * isn't actually changing from the last time this was called.
803 if (!force && (spi->controller->last_cs_enable == enable) &&
804 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
807 spi->controller->last_cs_enable = enable;
808 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
810 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
811 !spi->controller->set_cs_timing) {
813 spi_delay_exec(&spi->controller->cs_setup, NULL);
815 spi_delay_exec(&spi->controller->cs_hold, NULL);
818 if (spi->mode & SPI_CS_HIGH)
821 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
822 if (!(spi->mode & SPI_NO_CS)) {
824 /* polarity handled by gpiolib */
825 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
828 * invert the enable line, as active low is
831 gpio_set_value_cansleep(spi->cs_gpio, !enable);
833 /* Some SPI masters need both GPIO CS & slave_select */
834 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
835 spi->controller->set_cs)
836 spi->controller->set_cs(spi, !enable);
837 } else if (spi->controller->set_cs) {
838 spi->controller->set_cs(spi, !enable);
841 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
842 !spi->controller->set_cs_timing) {
844 spi_delay_exec(&spi->controller->cs_inactive, NULL);
848 #ifdef CONFIG_HAS_DMA
849 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
850 struct sg_table *sgt, void *buf, size_t len,
851 enum dma_data_direction dir)
853 const bool vmalloced_buf = is_vmalloc_addr(buf);
854 unsigned int max_seg_size = dma_get_max_seg_size(dev);
855 #ifdef CONFIG_HIGHMEM
856 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
857 (unsigned long)buf < (PKMAP_BASE +
858 (LAST_PKMAP * PAGE_SIZE)));
860 const bool kmap_buf = false;
864 struct page *vm_page;
865 struct scatterlist *sg;
870 if (vmalloced_buf || kmap_buf) {
871 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
872 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
873 } else if (virt_addr_valid(buf)) {
874 desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
875 sgs = DIV_ROUND_UP(len, desc_len);
880 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
885 for (i = 0; i < sgs; i++) {
887 if (vmalloced_buf || kmap_buf) {
889 * Next scatterlist entry size is the minimum between
890 * the desc_len and the remaining buffer length that
893 min = min_t(size_t, desc_len,
895 PAGE_SIZE - offset_in_page(buf)));
897 vm_page = vmalloc_to_page(buf);
899 vm_page = kmap_to_page(buf);
904 sg_set_page(sg, vm_page,
905 min, offset_in_page(buf));
907 min = min_t(size_t, len, desc_len);
909 sg_set_buf(sg, sg_buf, min);
917 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
930 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
931 struct sg_table *sgt, enum dma_data_direction dir)
933 if (sgt->orig_nents) {
934 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
939 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
941 struct device *tx_dev, *rx_dev;
942 struct spi_transfer *xfer;
949 tx_dev = ctlr->dma_tx->device->dev;
951 tx_dev = ctlr->dev.parent;
954 rx_dev = ctlr->dma_rx->device->dev;
956 rx_dev = ctlr->dev.parent;
958 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
959 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
962 if (xfer->tx_buf != NULL) {
963 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
964 (void *)xfer->tx_buf, xfer->len,
970 if (xfer->rx_buf != NULL) {
971 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
972 xfer->rx_buf, xfer->len,
975 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
982 ctlr->cur_msg_mapped = true;
987 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
989 struct spi_transfer *xfer;
990 struct device *tx_dev, *rx_dev;
992 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
996 tx_dev = ctlr->dma_tx->device->dev;
998 tx_dev = ctlr->dev.parent;
1001 rx_dev = ctlr->dma_rx->device->dev;
1003 rx_dev = ctlr->dev.parent;
1005 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1006 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1009 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1010 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1013 ctlr->cur_msg_mapped = false;
1017 #else /* !CONFIG_HAS_DMA */
1018 static inline int __spi_map_msg(struct spi_controller *ctlr,
1019 struct spi_message *msg)
1024 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1025 struct spi_message *msg)
1029 #endif /* !CONFIG_HAS_DMA */
1031 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1032 struct spi_message *msg)
1034 struct spi_transfer *xfer;
1036 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1038 * Restore the original value of tx_buf or rx_buf if they are
1041 if (xfer->tx_buf == ctlr->dummy_tx)
1042 xfer->tx_buf = NULL;
1043 if (xfer->rx_buf == ctlr->dummy_rx)
1044 xfer->rx_buf = NULL;
1047 return __spi_unmap_msg(ctlr, msg);
1050 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1052 struct spi_transfer *xfer;
1054 unsigned int max_tx, max_rx;
1056 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1057 && !(msg->spi->mode & SPI_3WIRE)) {
1061 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1062 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1064 max_tx = max(xfer->len, max_tx);
1065 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1067 max_rx = max(xfer->len, max_rx);
1071 tmp = krealloc(ctlr->dummy_tx, max_tx,
1072 GFP_KERNEL | GFP_DMA);
1075 ctlr->dummy_tx = tmp;
1076 memset(tmp, 0, max_tx);
1080 tmp = krealloc(ctlr->dummy_rx, max_rx,
1081 GFP_KERNEL | GFP_DMA);
1084 ctlr->dummy_rx = tmp;
1087 if (max_tx || max_rx) {
1088 list_for_each_entry(xfer, &msg->transfers,
1093 xfer->tx_buf = ctlr->dummy_tx;
1095 xfer->rx_buf = ctlr->dummy_rx;
1100 return __spi_map_msg(ctlr, msg);
1103 static int spi_transfer_wait(struct spi_controller *ctlr,
1104 struct spi_message *msg,
1105 struct spi_transfer *xfer)
1107 struct spi_statistics *statm = &ctlr->statistics;
1108 struct spi_statistics *stats = &msg->spi->statistics;
1109 u32 speed_hz = xfer->speed_hz;
1110 unsigned long long ms;
1112 if (spi_controller_is_slave(ctlr)) {
1113 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1114 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1121 ms = 8LL * 1000LL * xfer->len;
1122 do_div(ms, speed_hz);
1123 ms += ms + 200; /* some tolerance */
1128 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1129 msecs_to_jiffies(ms));
1132 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1133 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1134 dev_err(&msg->spi->dev,
1135 "SPI transfer timed out\n");
1143 static void _spi_transfer_delay_ns(u32 ns)
1150 u32 us = DIV_ROUND_UP(ns, 1000);
1155 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1159 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1161 u32 delay = _delay->value;
1162 u32 unit = _delay->unit;
1169 case SPI_DELAY_UNIT_USECS:
1172 case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1174 case SPI_DELAY_UNIT_SCK:
1175 /* clock cycles need to be obtained from spi_transfer */
1178 /* if there is no effective speed know, then approximate
1179 * by underestimating with half the requested hz
1181 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1184 delay *= DIV_ROUND_UP(1000000000, hz);
1192 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1194 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1203 delay = spi_delay_to_ns(_delay, xfer);
1207 _spi_transfer_delay_ns(delay);
1211 EXPORT_SYMBOL_GPL(spi_delay_exec);
1213 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1214 struct spi_transfer *xfer)
1216 u32 delay = xfer->cs_change_delay.value;
1217 u32 unit = xfer->cs_change_delay.unit;
1220 /* return early on "fast" mode - for everything but USECS */
1222 if (unit == SPI_DELAY_UNIT_USECS)
1223 _spi_transfer_delay_ns(10000);
1227 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1229 dev_err_once(&msg->spi->dev,
1230 "Use of unsupported delay unit %i, using default of 10us\n",
1232 _spi_transfer_delay_ns(10000);
1237 * spi_transfer_one_message - Default implementation of transfer_one_message()
1239 * This is a standard implementation of transfer_one_message() for
1240 * drivers which implement a transfer_one() operation. It provides
1241 * standard handling of delays and chip select management.
1243 static int spi_transfer_one_message(struct spi_controller *ctlr,
1244 struct spi_message *msg)
1246 struct spi_transfer *xfer;
1247 bool keep_cs = false;
1249 struct spi_statistics *statm = &ctlr->statistics;
1250 struct spi_statistics *stats = &msg->spi->statistics;
1252 spi_set_cs(msg->spi, true, false);
1254 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1255 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1257 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1258 trace_spi_transfer_start(msg, xfer);
1260 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1261 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1263 if (!ctlr->ptp_sts_supported) {
1264 xfer->ptp_sts_word_pre = 0;
1265 ptp_read_system_prets(xfer->ptp_sts);
1268 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1269 reinit_completion(&ctlr->xfer_completion);
1272 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1274 if (ctlr->cur_msg_mapped &&
1275 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1276 __spi_unmap_msg(ctlr, msg);
1277 ctlr->fallback = true;
1278 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1282 SPI_STATISTICS_INCREMENT_FIELD(statm,
1284 SPI_STATISTICS_INCREMENT_FIELD(stats,
1286 dev_err(&msg->spi->dev,
1287 "SPI transfer failed: %d\n", ret);
1292 ret = spi_transfer_wait(ctlr, msg, xfer);
1298 dev_err(&msg->spi->dev,
1299 "Bufferless transfer has length %u\n",
1303 if (!ctlr->ptp_sts_supported) {
1304 ptp_read_system_postts(xfer->ptp_sts);
1305 xfer->ptp_sts_word_post = xfer->len;
1308 trace_spi_transfer_stop(msg, xfer);
1310 if (msg->status != -EINPROGRESS)
1313 spi_transfer_delay_exec(xfer);
1315 if (xfer->cs_change) {
1316 if (list_is_last(&xfer->transfer_list,
1320 spi_set_cs(msg->spi, false, false);
1321 _spi_transfer_cs_change_delay(msg, xfer);
1322 spi_set_cs(msg->spi, true, false);
1326 msg->actual_length += xfer->len;
1330 if (ret != 0 || !keep_cs)
1331 spi_set_cs(msg->spi, false, false);
1333 if (msg->status == -EINPROGRESS)
1336 if (msg->status && ctlr->handle_err)
1337 ctlr->handle_err(ctlr, msg);
1339 spi_finalize_current_message(ctlr);
1345 * spi_finalize_current_transfer - report completion of a transfer
1346 * @ctlr: the controller reporting completion
1348 * Called by SPI drivers using the core transfer_one_message()
1349 * implementation to notify it that the current interrupt driven
1350 * transfer has finished and the next one may be scheduled.
1352 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1354 complete(&ctlr->xfer_completion);
1356 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1358 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1360 if (ctlr->auto_runtime_pm) {
1361 pm_runtime_mark_last_busy(ctlr->dev.parent);
1362 pm_runtime_put_autosuspend(ctlr->dev.parent);
1367 * __spi_pump_messages - function which processes spi message queue
1368 * @ctlr: controller to process queue for
1369 * @in_kthread: true if we are in the context of the message pump thread
1371 * This function checks if there is any spi message in the queue that
1372 * needs processing and if so call out to the driver to initialize hardware
1373 * and transfer each message.
1375 * Note that it is called both from the kthread itself and also from
1376 * inside spi_sync(); the queue extraction handling at the top of the
1377 * function should deal with this safely.
1379 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1381 struct spi_transfer *xfer;
1382 struct spi_message *msg;
1383 bool was_busy = false;
1384 unsigned long flags;
1388 spin_lock_irqsave(&ctlr->queue_lock, flags);
1390 /* Make sure we are not already running a message */
1391 if (ctlr->cur_msg) {
1392 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1396 /* If another context is idling the device then defer */
1398 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1399 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1403 /* Check if the queue is idle */
1404 if (list_empty(&ctlr->queue) || !ctlr->running) {
1406 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1410 /* Defer any non-atomic teardown to the thread */
1412 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1413 !ctlr->unprepare_transfer_hardware) {
1414 spi_idle_runtime_pm(ctlr);
1416 trace_spi_controller_idle(ctlr);
1418 kthread_queue_work(ctlr->kworker,
1419 &ctlr->pump_messages);
1421 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1426 ctlr->idling = true;
1427 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1429 kfree(ctlr->dummy_rx);
1430 ctlr->dummy_rx = NULL;
1431 kfree(ctlr->dummy_tx);
1432 ctlr->dummy_tx = NULL;
1433 if (ctlr->unprepare_transfer_hardware &&
1434 ctlr->unprepare_transfer_hardware(ctlr))
1436 "failed to unprepare transfer hardware\n");
1437 spi_idle_runtime_pm(ctlr);
1438 trace_spi_controller_idle(ctlr);
1440 spin_lock_irqsave(&ctlr->queue_lock, flags);
1441 ctlr->idling = false;
1442 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1446 /* Extract head of queue */
1447 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1448 ctlr->cur_msg = msg;
1450 list_del_init(&msg->queue);
1455 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1457 mutex_lock(&ctlr->io_mutex);
1459 if (!was_busy && ctlr->auto_runtime_pm) {
1460 ret = pm_runtime_get_sync(ctlr->dev.parent);
1462 pm_runtime_put_noidle(ctlr->dev.parent);
1463 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1465 mutex_unlock(&ctlr->io_mutex);
1471 trace_spi_controller_busy(ctlr);
1473 if (!was_busy && ctlr->prepare_transfer_hardware) {
1474 ret = ctlr->prepare_transfer_hardware(ctlr);
1477 "failed to prepare transfer hardware: %d\n",
1480 if (ctlr->auto_runtime_pm)
1481 pm_runtime_put(ctlr->dev.parent);
1484 spi_finalize_current_message(ctlr);
1486 mutex_unlock(&ctlr->io_mutex);
1491 trace_spi_message_start(msg);
1493 if (ctlr->prepare_message) {
1494 ret = ctlr->prepare_message(ctlr, msg);
1496 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1499 spi_finalize_current_message(ctlr);
1502 ctlr->cur_msg_prepared = true;
1505 ret = spi_map_msg(ctlr, msg);
1508 spi_finalize_current_message(ctlr);
1512 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1513 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1514 xfer->ptp_sts_word_pre = 0;
1515 ptp_read_system_prets(xfer->ptp_sts);
1519 ret = ctlr->transfer_one_message(ctlr, msg);
1522 "failed to transfer one message from queue\n");
1527 mutex_unlock(&ctlr->io_mutex);
1529 /* Prod the scheduler in case transfer_one() was busy waiting */
1535 * spi_pump_messages - kthread work function which processes spi message queue
1536 * @work: pointer to kthread work struct contained in the controller struct
1538 static void spi_pump_messages(struct kthread_work *work)
1540 struct spi_controller *ctlr =
1541 container_of(work, struct spi_controller, pump_messages);
1543 __spi_pump_messages(ctlr, true);
1547 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1548 * TX timestamp for the requested byte from the SPI
1549 * transfer. The frequency with which this function
1550 * must be called (once per word, once for the whole
1551 * transfer, once per batch of words etc) is arbitrary
1552 * as long as the @tx buffer offset is greater than or
1553 * equal to the requested byte at the time of the
1554 * call. The timestamp is only taken once, at the
1555 * first such call. It is assumed that the driver
1556 * advances its @tx buffer pointer monotonically.
1557 * @ctlr: Pointer to the spi_controller structure of the driver
1558 * @xfer: Pointer to the transfer being timestamped
1559 * @progress: How many words (not bytes) have been transferred so far
1560 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1561 * transfer, for less jitter in time measurement. Only compatible
1562 * with PIO drivers. If true, must follow up with
1563 * spi_take_timestamp_post or otherwise system will crash.
1564 * WARNING: for fully predictable results, the CPU frequency must
1565 * also be under control (governor).
1567 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1568 struct spi_transfer *xfer,
1569 size_t progress, bool irqs_off)
1574 if (xfer->timestamped)
1577 if (progress > xfer->ptp_sts_word_pre)
1580 /* Capture the resolution of the timestamp */
1581 xfer->ptp_sts_word_pre = progress;
1584 local_irq_save(ctlr->irq_flags);
1588 ptp_read_system_prets(xfer->ptp_sts);
1590 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1593 * spi_take_timestamp_post - helper for drivers to collect the end of the
1594 * TX timestamp for the requested byte from the SPI
1595 * transfer. Can be called with an arbitrary
1596 * frequency: only the first call where @tx exceeds
1597 * or is equal to the requested word will be
1599 * @ctlr: Pointer to the spi_controller structure of the driver
1600 * @xfer: Pointer to the transfer being timestamped
1601 * @progress: How many words (not bytes) have been transferred so far
1602 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1604 void spi_take_timestamp_post(struct spi_controller *ctlr,
1605 struct spi_transfer *xfer,
1606 size_t progress, bool irqs_off)
1611 if (xfer->timestamped)
1614 if (progress < xfer->ptp_sts_word_post)
1617 ptp_read_system_postts(xfer->ptp_sts);
1620 local_irq_restore(ctlr->irq_flags);
1624 /* Capture the resolution of the timestamp */
1625 xfer->ptp_sts_word_post = progress;
1627 xfer->timestamped = true;
1629 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1632 * spi_set_thread_rt - set the controller to pump at realtime priority
1633 * @ctlr: controller to boost priority of
1635 * This can be called because the controller requested realtime priority
1636 * (by setting the ->rt value before calling spi_register_controller()) or
1637 * because a device on the bus said that its transfers needed realtime
1640 * NOTE: at the moment if any device on a bus says it needs realtime then
1641 * the thread will be at realtime priority for all transfers on that
1642 * controller. If this eventually becomes a problem we may see if we can
1643 * find a way to boost the priority only temporarily during relevant
1646 static void spi_set_thread_rt(struct spi_controller *ctlr)
1648 dev_info(&ctlr->dev,
1649 "will run message pump with realtime priority\n");
1650 sched_set_fifo(ctlr->kworker->task);
1653 static int spi_init_queue(struct spi_controller *ctlr)
1655 ctlr->running = false;
1658 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1659 if (IS_ERR(ctlr->kworker)) {
1660 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1661 return PTR_ERR(ctlr->kworker);
1664 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1667 * Controller config will indicate if this controller should run the
1668 * message pump with high (realtime) priority to reduce the transfer
1669 * latency on the bus by minimising the delay between a transfer
1670 * request and the scheduling of the message pump thread. Without this
1671 * setting the message pump thread will remain at default priority.
1674 spi_set_thread_rt(ctlr);
1680 * spi_get_next_queued_message() - called by driver to check for queued
1682 * @ctlr: the controller to check for queued messages
1684 * If there are more messages in the queue, the next message is returned from
1687 * Return: the next message in the queue, else NULL if the queue is empty.
1689 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1691 struct spi_message *next;
1692 unsigned long flags;
1694 /* get a pointer to the next message, if any */
1695 spin_lock_irqsave(&ctlr->queue_lock, flags);
1696 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1698 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1702 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1705 * spi_finalize_current_message() - the current message is complete
1706 * @ctlr: the controller to return the message to
1708 * Called by the driver to notify the core that the message in the front of the
1709 * queue is complete and can be removed from the queue.
1711 void spi_finalize_current_message(struct spi_controller *ctlr)
1713 struct spi_transfer *xfer;
1714 struct spi_message *mesg;
1715 unsigned long flags;
1718 spin_lock_irqsave(&ctlr->queue_lock, flags);
1719 mesg = ctlr->cur_msg;
1720 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1722 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1723 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1724 ptp_read_system_postts(xfer->ptp_sts);
1725 xfer->ptp_sts_word_post = xfer->len;
1729 if (unlikely(ctlr->ptp_sts_supported))
1730 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1731 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1733 spi_unmap_msg(ctlr, mesg);
1735 /* In the prepare_messages callback the spi bus has the opportunity to
1736 * split a transfer to smaller chunks.
1737 * Release splited transfers here since spi_map_msg is done on the
1738 * splited transfers.
1740 spi_res_release(ctlr, mesg);
1742 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1743 ret = ctlr->unprepare_message(ctlr, mesg);
1745 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1750 spin_lock_irqsave(&ctlr->queue_lock, flags);
1751 ctlr->cur_msg = NULL;
1752 ctlr->cur_msg_prepared = false;
1753 ctlr->fallback = false;
1754 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1755 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1757 trace_spi_message_done(mesg);
1761 mesg->complete(mesg->context);
1763 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1765 static int spi_start_queue(struct spi_controller *ctlr)
1767 unsigned long flags;
1769 spin_lock_irqsave(&ctlr->queue_lock, flags);
1771 if (ctlr->running || ctlr->busy) {
1772 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1776 ctlr->running = true;
1777 ctlr->cur_msg = NULL;
1778 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1780 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1785 static int spi_stop_queue(struct spi_controller *ctlr)
1787 unsigned long flags;
1788 unsigned limit = 500;
1791 spin_lock_irqsave(&ctlr->queue_lock, flags);
1794 * This is a bit lame, but is optimized for the common execution path.
1795 * A wait_queue on the ctlr->busy could be used, but then the common
1796 * execution path (pump_messages) would be required to call wake_up or
1797 * friends on every SPI message. Do this instead.
1799 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1800 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1801 usleep_range(10000, 11000);
1802 spin_lock_irqsave(&ctlr->queue_lock, flags);
1805 if (!list_empty(&ctlr->queue) || ctlr->busy)
1808 ctlr->running = false;
1810 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1813 dev_warn(&ctlr->dev, "could not stop message queue\n");
1819 static int spi_destroy_queue(struct spi_controller *ctlr)
1823 ret = spi_stop_queue(ctlr);
1826 * kthread_flush_worker will block until all work is done.
1827 * If the reason that stop_queue timed out is that the work will never
1828 * finish, then it does no good to call flush/stop thread, so
1832 dev_err(&ctlr->dev, "problem destroying queue\n");
1836 kthread_destroy_worker(ctlr->kworker);
1841 static int __spi_queued_transfer(struct spi_device *spi,
1842 struct spi_message *msg,
1845 struct spi_controller *ctlr = spi->controller;
1846 unsigned long flags;
1848 spin_lock_irqsave(&ctlr->queue_lock, flags);
1850 if (!ctlr->running) {
1851 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1854 msg->actual_length = 0;
1855 msg->status = -EINPROGRESS;
1857 list_add_tail(&msg->queue, &ctlr->queue);
1858 if (!ctlr->busy && need_pump)
1859 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1861 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1866 * spi_queued_transfer - transfer function for queued transfers
1867 * @spi: spi device which is requesting transfer
1868 * @msg: spi message which is to handled is queued to driver queue
1870 * Return: zero on success, else a negative error code.
1872 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1874 return __spi_queued_transfer(spi, msg, true);
1877 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1881 ctlr->transfer = spi_queued_transfer;
1882 if (!ctlr->transfer_one_message)
1883 ctlr->transfer_one_message = spi_transfer_one_message;
1885 /* Initialize and start queue */
1886 ret = spi_init_queue(ctlr);
1888 dev_err(&ctlr->dev, "problem initializing queue\n");
1889 goto err_init_queue;
1891 ctlr->queued = true;
1892 ret = spi_start_queue(ctlr);
1894 dev_err(&ctlr->dev, "problem starting queue\n");
1895 goto err_start_queue;
1901 spi_destroy_queue(ctlr);
1907 * spi_flush_queue - Send all pending messages in the queue from the callers'
1909 * @ctlr: controller to process queue for
1911 * This should be used when one wants to ensure all pending messages have been
1912 * sent before doing something. Is used by the spi-mem code to make sure SPI
1913 * memory operations do not preempt regular SPI transfers that have been queued
1914 * before the spi-mem operation.
1916 void spi_flush_queue(struct spi_controller *ctlr)
1918 if (ctlr->transfer == spi_queued_transfer)
1919 __spi_pump_messages(ctlr, false);
1922 /*-------------------------------------------------------------------------*/
1924 #if defined(CONFIG_OF)
1925 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1926 struct device_node *nc)
1931 /* Mode (clock phase/polarity/etc.) */
1932 if (of_property_read_bool(nc, "spi-cpha"))
1933 spi->mode |= SPI_CPHA;
1934 if (of_property_read_bool(nc, "spi-cpol"))
1935 spi->mode |= SPI_CPOL;
1936 if (of_property_read_bool(nc, "spi-3wire"))
1937 spi->mode |= SPI_3WIRE;
1938 if (of_property_read_bool(nc, "spi-lsb-first"))
1939 spi->mode |= SPI_LSB_FIRST;
1940 if (of_property_read_bool(nc, "spi-cs-high"))
1941 spi->mode |= SPI_CS_HIGH;
1943 /* Device DUAL/QUAD mode */
1944 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1947 spi->mode |= SPI_NO_TX;
1952 spi->mode |= SPI_TX_DUAL;
1955 spi->mode |= SPI_TX_QUAD;
1958 spi->mode |= SPI_TX_OCTAL;
1961 dev_warn(&ctlr->dev,
1962 "spi-tx-bus-width %d not supported\n",
1968 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1971 spi->mode |= SPI_NO_RX;
1976 spi->mode |= SPI_RX_DUAL;
1979 spi->mode |= SPI_RX_QUAD;
1982 spi->mode |= SPI_RX_OCTAL;
1985 dev_warn(&ctlr->dev,
1986 "spi-rx-bus-width %d not supported\n",
1992 if (spi_controller_is_slave(ctlr)) {
1993 if (!of_node_name_eq(nc, "slave")) {
1994 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2001 /* Device address */
2002 rc = of_property_read_u32(nc, "reg", &value);
2004 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2008 spi->chip_select = value;
2011 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2012 spi->max_speed_hz = value;
2017 static struct spi_device *
2018 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2020 struct spi_device *spi;
2023 /* Alloc an spi_device */
2024 spi = spi_alloc_device(ctlr);
2026 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2031 /* Select device driver */
2032 rc = of_modalias_node(nc, spi->modalias,
2033 sizeof(spi->modalias));
2035 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2039 rc = of_spi_parse_dt(ctlr, spi, nc);
2043 /* Store a pointer to the node in the device structure */
2045 spi->dev.of_node = nc;
2047 /* Register the new device */
2048 rc = spi_add_device(spi);
2050 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2051 goto err_of_node_put;
2064 * of_register_spi_devices() - Register child devices onto the SPI bus
2065 * @ctlr: Pointer to spi_controller device
2067 * Registers an spi_device for each child node of controller node which
2068 * represents a valid SPI slave.
2070 static void of_register_spi_devices(struct spi_controller *ctlr)
2072 struct spi_device *spi;
2073 struct device_node *nc;
2075 if (!ctlr->dev.of_node)
2078 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2079 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2081 spi = of_register_spi_device(ctlr, nc);
2083 dev_warn(&ctlr->dev,
2084 "Failed to create SPI device for %pOF\n", nc);
2085 of_node_clear_flag(nc, OF_POPULATED);
2090 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2094 struct acpi_spi_lookup {
2095 struct spi_controller *ctlr;
2103 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2104 struct acpi_spi_lookup *lookup)
2106 const union acpi_object *obj;
2108 if (!x86_apple_machine)
2111 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2112 && obj->buffer.length >= 4)
2113 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2115 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2116 && obj->buffer.length == 8)
2117 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2119 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2120 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2121 lookup->mode |= SPI_LSB_FIRST;
2123 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2124 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2125 lookup->mode |= SPI_CPOL;
2127 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2128 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2129 lookup->mode |= SPI_CPHA;
2132 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2134 struct acpi_spi_lookup *lookup = data;
2135 struct spi_controller *ctlr = lookup->ctlr;
2137 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2138 struct acpi_resource_spi_serialbus *sb;
2139 acpi_handle parent_handle;
2142 sb = &ares->data.spi_serial_bus;
2143 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2145 status = acpi_get_handle(NULL,
2146 sb->resource_source.string_ptr,
2149 if (ACPI_FAILURE(status) ||
2150 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2154 * ACPI DeviceSelection numbering is handled by the
2155 * host controller driver in Windows and can vary
2156 * from driver to driver. In Linux we always expect
2157 * 0 .. max - 1 so we need to ask the driver to
2158 * translate between the two schemes.
2160 if (ctlr->fw_translate_cs) {
2161 int cs = ctlr->fw_translate_cs(ctlr,
2162 sb->device_selection);
2165 lookup->chip_select = cs;
2167 lookup->chip_select = sb->device_selection;
2170 lookup->max_speed_hz = sb->connection_speed;
2171 lookup->bits_per_word = sb->data_bit_length;
2173 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2174 lookup->mode |= SPI_CPHA;
2175 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2176 lookup->mode |= SPI_CPOL;
2177 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2178 lookup->mode |= SPI_CS_HIGH;
2180 } else if (lookup->irq < 0) {
2183 if (acpi_dev_resource_interrupt(ares, 0, &r))
2184 lookup->irq = r.start;
2187 /* Always tell the ACPI core to skip this resource */
2191 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2192 struct acpi_device *adev)
2194 acpi_handle parent_handle = NULL;
2195 struct list_head resource_list;
2196 struct acpi_spi_lookup lookup = {};
2197 struct spi_device *spi;
2200 if (acpi_bus_get_status(adev) || !adev->status.present ||
2201 acpi_device_enumerated(adev))
2207 INIT_LIST_HEAD(&resource_list);
2208 ret = acpi_dev_get_resources(adev, &resource_list,
2209 acpi_spi_add_resource, &lookup);
2210 acpi_dev_free_resource_list(&resource_list);
2213 /* found SPI in _CRS but it points to another controller */
2216 if (!lookup.max_speed_hz &&
2217 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2218 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2219 /* Apple does not use _CRS but nested devices for SPI slaves */
2220 acpi_spi_parse_apple_properties(adev, &lookup);
2223 if (!lookup.max_speed_hz)
2226 spi = spi_alloc_device(ctlr);
2228 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2229 dev_name(&adev->dev));
2230 return AE_NO_MEMORY;
2234 ACPI_COMPANION_SET(&spi->dev, adev);
2235 spi->max_speed_hz = lookup.max_speed_hz;
2236 spi->mode |= lookup.mode;
2237 spi->irq = lookup.irq;
2238 spi->bits_per_word = lookup.bits_per_word;
2239 spi->chip_select = lookup.chip_select;
2241 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2242 sizeof(spi->modalias));
2245 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2247 acpi_device_set_enumerated(adev);
2249 adev->power.flags.ignore_parent = true;
2250 if (spi_add_device(spi)) {
2251 adev->power.flags.ignore_parent = false;
2252 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2253 dev_name(&adev->dev));
2260 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2261 void *data, void **return_value)
2263 struct spi_controller *ctlr = data;
2264 struct acpi_device *adev;
2266 if (acpi_bus_get_device(handle, &adev))
2269 return acpi_register_spi_device(ctlr, adev);
2272 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2274 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2279 handle = ACPI_HANDLE(ctlr->dev.parent);
2283 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2284 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2285 acpi_spi_add_device, NULL, ctlr, NULL);
2286 if (ACPI_FAILURE(status))
2287 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2290 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2291 #endif /* CONFIG_ACPI */
2293 static void spi_controller_release(struct device *dev)
2295 struct spi_controller *ctlr;
2297 ctlr = container_of(dev, struct spi_controller, dev);
2301 static struct class spi_master_class = {
2302 .name = "spi_master",
2303 .owner = THIS_MODULE,
2304 .dev_release = spi_controller_release,
2305 .dev_groups = spi_master_groups,
2308 #ifdef CONFIG_SPI_SLAVE
2310 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2312 * @spi: device used for the current transfer
2314 int spi_slave_abort(struct spi_device *spi)
2316 struct spi_controller *ctlr = spi->controller;
2318 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2319 return ctlr->slave_abort(ctlr);
2323 EXPORT_SYMBOL_GPL(spi_slave_abort);
2325 static int match_true(struct device *dev, void *data)
2330 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2333 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2335 struct device *child;
2337 child = device_find_child(&ctlr->dev, NULL, match_true);
2338 return sprintf(buf, "%s\n",
2339 child ? to_spi_device(child)->modalias : NULL);
2342 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2343 const char *buf, size_t count)
2345 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2347 struct spi_device *spi;
2348 struct device *child;
2352 rc = sscanf(buf, "%31s", name);
2353 if (rc != 1 || !name[0])
2356 child = device_find_child(&ctlr->dev, NULL, match_true);
2358 /* Remove registered slave */
2359 device_unregister(child);
2363 if (strcmp(name, "(null)")) {
2364 /* Register new slave */
2365 spi = spi_alloc_device(ctlr);
2369 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2371 rc = spi_add_device(spi);
2381 static DEVICE_ATTR_RW(slave);
2383 static struct attribute *spi_slave_attrs[] = {
2384 &dev_attr_slave.attr,
2388 static const struct attribute_group spi_slave_group = {
2389 .attrs = spi_slave_attrs,
2392 static const struct attribute_group *spi_slave_groups[] = {
2393 &spi_controller_statistics_group,
2398 static struct class spi_slave_class = {
2399 .name = "spi_slave",
2400 .owner = THIS_MODULE,
2401 .dev_release = spi_controller_release,
2402 .dev_groups = spi_slave_groups,
2405 extern struct class spi_slave_class; /* dummy */
2409 * __spi_alloc_controller - allocate an SPI master or slave controller
2410 * @dev: the controller, possibly using the platform_bus
2411 * @size: how much zeroed driver-private data to allocate; the pointer to this
2412 * memory is in the driver_data field of the returned device, accessible
2413 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2414 * drivers granting DMA access to portions of their private data need to
2415 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2416 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2417 * slave (true) controller
2418 * Context: can sleep
2420 * This call is used only by SPI controller drivers, which are the
2421 * only ones directly touching chip registers. It's how they allocate
2422 * an spi_controller structure, prior to calling spi_register_controller().
2424 * This must be called from context that can sleep.
2426 * The caller is responsible for assigning the bus number and initializing the
2427 * controller's methods before calling spi_register_controller(); and (after
2428 * errors adding the device) calling spi_controller_put() to prevent a memory
2431 * Return: the SPI controller structure on success, else NULL.
2433 struct spi_controller *__spi_alloc_controller(struct device *dev,
2434 unsigned int size, bool slave)
2436 struct spi_controller *ctlr;
2437 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2442 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2446 device_initialize(&ctlr->dev);
2448 ctlr->num_chipselect = 1;
2449 ctlr->slave = slave;
2450 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2451 ctlr->dev.class = &spi_slave_class;
2453 ctlr->dev.class = &spi_master_class;
2454 ctlr->dev.parent = dev;
2455 pm_suspend_ignore_children(&ctlr->dev, true);
2456 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2460 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2462 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2464 spi_controller_put(*(struct spi_controller **)ctlr);
2468 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2469 * @dev: physical device of SPI controller
2470 * @size: how much zeroed driver-private data to allocate
2471 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2472 * Context: can sleep
2474 * Allocate an SPI controller and automatically release a reference on it
2475 * when @dev is unbound from its driver. Drivers are thus relieved from
2476 * having to call spi_controller_put().
2478 * The arguments to this function are identical to __spi_alloc_controller().
2480 * Return: the SPI controller structure on success, else NULL.
2482 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2486 struct spi_controller **ptr, *ctlr;
2488 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2493 ctlr = __spi_alloc_controller(dev, size, slave);
2495 ctlr->devm_allocated = true;
2497 devres_add(dev, ptr);
2504 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2507 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2510 struct device_node *np = ctlr->dev.of_node;
2515 nb = of_gpio_named_count(np, "cs-gpios");
2516 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2518 /* Return error only for an incorrectly formed cs-gpios property */
2519 if (nb == 0 || nb == -ENOENT)
2524 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2526 ctlr->cs_gpios = cs;
2528 if (!ctlr->cs_gpios)
2531 for (i = 0; i < ctlr->num_chipselect; i++)
2534 for (i = 0; i < nb; i++)
2535 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2540 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2547 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2548 * @ctlr: The SPI master to grab GPIO descriptors for
2550 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2553 struct gpio_desc **cs;
2554 struct device *dev = &ctlr->dev;
2555 unsigned long native_cs_mask = 0;
2556 unsigned int num_cs_gpios = 0;
2558 nb = gpiod_count(dev, "cs");
2560 /* No GPIOs at all is fine, else return the error */
2566 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2568 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2572 ctlr->cs_gpiods = cs;
2574 for (i = 0; i < nb; i++) {
2576 * Most chipselects are active low, the inverted
2577 * semantics are handled by special quirks in gpiolib,
2578 * so initializing them GPIOD_OUT_LOW here means
2579 * "unasserted", in most cases this will drive the physical
2582 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2585 return PTR_ERR(cs[i]);
2589 * If we find a CS GPIO, name it after the device and
2594 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2598 gpiod_set_consumer_name(cs[i], gpioname);
2603 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2604 dev_err(dev, "Invalid native chip select %d\n", i);
2607 native_cs_mask |= BIT(i);
2610 ctlr->unused_native_cs = ffz(native_cs_mask);
2611 if (num_cs_gpios && ctlr->max_native_cs &&
2612 ctlr->unused_native_cs >= ctlr->max_native_cs) {
2613 dev_err(dev, "No unused native chip select available\n");
2620 static int spi_controller_check_ops(struct spi_controller *ctlr)
2623 * The controller may implement only the high-level SPI-memory like
2624 * operations if it does not support regular SPI transfers, and this is
2626 * If ->mem_ops is NULL, we request that at least one of the
2627 * ->transfer_xxx() method be implemented.
2629 if (ctlr->mem_ops) {
2630 if (!ctlr->mem_ops->exec_op)
2632 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2633 !ctlr->transfer_one_message) {
2641 * spi_register_controller - register SPI master or slave controller
2642 * @ctlr: initialized master, originally from spi_alloc_master() or
2644 * Context: can sleep
2646 * SPI controllers connect to their drivers using some non-SPI bus,
2647 * such as the platform bus. The final stage of probe() in that code
2648 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2650 * SPI controllers use board specific (often SOC specific) bus numbers,
2651 * and board-specific addressing for SPI devices combines those numbers
2652 * with chip select numbers. Since SPI does not directly support dynamic
2653 * device identification, boards need configuration tables telling which
2654 * chip is at which address.
2656 * This must be called from context that can sleep. It returns zero on
2657 * success, else a negative error code (dropping the controller's refcount).
2658 * After a successful return, the caller is responsible for calling
2659 * spi_unregister_controller().
2661 * Return: zero on success, else a negative error code.
2663 int spi_register_controller(struct spi_controller *ctlr)
2665 struct device *dev = ctlr->dev.parent;
2666 struct boardinfo *bi;
2668 int id, first_dynamic;
2674 * Make sure all necessary hooks are implemented before registering
2675 * the SPI controller.
2677 status = spi_controller_check_ops(ctlr);
2681 if (ctlr->bus_num >= 0) {
2682 /* devices with a fixed bus num must check-in with the num */
2683 mutex_lock(&board_lock);
2684 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2685 ctlr->bus_num + 1, GFP_KERNEL);
2686 mutex_unlock(&board_lock);
2687 if (WARN(id < 0, "couldn't get idr"))
2688 return id == -ENOSPC ? -EBUSY : id;
2690 } else if (ctlr->dev.of_node) {
2691 /* allocate dynamic bus number using Linux idr */
2692 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2695 mutex_lock(&board_lock);
2696 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2697 ctlr->bus_num + 1, GFP_KERNEL);
2698 mutex_unlock(&board_lock);
2699 if (WARN(id < 0, "couldn't get idr"))
2700 return id == -ENOSPC ? -EBUSY : id;
2703 if (ctlr->bus_num < 0) {
2704 first_dynamic = of_alias_get_highest_id("spi");
2705 if (first_dynamic < 0)
2710 mutex_lock(&board_lock);
2711 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2713 mutex_unlock(&board_lock);
2714 if (WARN(id < 0, "couldn't get idr"))
2718 INIT_LIST_HEAD(&ctlr->queue);
2719 spin_lock_init(&ctlr->queue_lock);
2720 spin_lock_init(&ctlr->bus_lock_spinlock);
2721 mutex_init(&ctlr->bus_lock_mutex);
2722 mutex_init(&ctlr->io_mutex);
2723 ctlr->bus_lock_flag = 0;
2724 init_completion(&ctlr->xfer_completion);
2725 if (!ctlr->max_dma_len)
2726 ctlr->max_dma_len = INT_MAX;
2728 /* register the device, then userspace will see it.
2729 * registration fails if the bus ID is in use.
2731 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2733 if (!spi_controller_is_slave(ctlr)) {
2734 if (ctlr->use_gpio_descriptors) {
2735 status = spi_get_gpio_descs(ctlr);
2739 * A controller using GPIO descriptors always
2740 * supports SPI_CS_HIGH if need be.
2742 ctlr->mode_bits |= SPI_CS_HIGH;
2744 /* Legacy code path for GPIOs from DT */
2745 status = of_spi_get_gpio_numbers(ctlr);
2752 * Even if it's just one always-selected device, there must
2753 * be at least one chipselect.
2755 if (!ctlr->num_chipselect) {
2760 status = device_add(&ctlr->dev);
2763 dev_dbg(dev, "registered %s %s\n",
2764 spi_controller_is_slave(ctlr) ? "slave" : "master",
2765 dev_name(&ctlr->dev));
2768 * If we're using a queued driver, start the queue. Note that we don't
2769 * need the queueing logic if the driver is only supporting high-level
2770 * memory operations.
2772 if (ctlr->transfer) {
2773 dev_info(dev, "controller is unqueued, this is deprecated\n");
2774 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2775 status = spi_controller_initialize_queue(ctlr);
2777 device_del(&ctlr->dev);
2781 /* add statistics */
2782 spin_lock_init(&ctlr->statistics.lock);
2784 mutex_lock(&board_lock);
2785 list_add_tail(&ctlr->list, &spi_controller_list);
2786 list_for_each_entry(bi, &board_list, list)
2787 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2788 mutex_unlock(&board_lock);
2790 /* Register devices from the device tree and ACPI */
2791 of_register_spi_devices(ctlr);
2792 acpi_register_spi_devices(ctlr);
2796 mutex_lock(&board_lock);
2797 idr_remove(&spi_master_idr, ctlr->bus_num);
2798 mutex_unlock(&board_lock);
2801 EXPORT_SYMBOL_GPL(spi_register_controller);
2803 static void devm_spi_unregister(void *ctlr)
2805 spi_unregister_controller(ctlr);
2809 * devm_spi_register_controller - register managed SPI master or slave
2811 * @dev: device managing SPI controller
2812 * @ctlr: initialized controller, originally from spi_alloc_master() or
2814 * Context: can sleep
2816 * Register a SPI device as with spi_register_controller() which will
2817 * automatically be unregistered and freed.
2819 * Return: zero on success, else a negative error code.
2821 int devm_spi_register_controller(struct device *dev,
2822 struct spi_controller *ctlr)
2826 ret = spi_register_controller(ctlr);
2830 return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
2832 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2834 static int __unregister(struct device *dev, void *null)
2836 spi_unregister_device(to_spi_device(dev));
2841 * spi_unregister_controller - unregister SPI master or slave controller
2842 * @ctlr: the controller being unregistered
2843 * Context: can sleep
2845 * This call is used only by SPI controller drivers, which are the
2846 * only ones directly touching chip registers.
2848 * This must be called from context that can sleep.
2850 * Note that this function also drops a reference to the controller.
2852 void spi_unregister_controller(struct spi_controller *ctlr)
2854 struct spi_controller *found;
2855 int id = ctlr->bus_num;
2857 /* Prevent addition of new devices, unregister existing ones */
2858 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2859 mutex_lock(&spi_add_lock);
2861 device_for_each_child(&ctlr->dev, NULL, __unregister);
2863 /* First make sure that this controller was ever added */
2864 mutex_lock(&board_lock);
2865 found = idr_find(&spi_master_idr, id);
2866 mutex_unlock(&board_lock);
2868 if (spi_destroy_queue(ctlr))
2869 dev_err(&ctlr->dev, "queue remove failed\n");
2871 mutex_lock(&board_lock);
2872 list_del(&ctlr->list);
2873 mutex_unlock(&board_lock);
2875 device_del(&ctlr->dev);
2877 /* Release the last reference on the controller if its driver
2878 * has not yet been converted to devm_spi_alloc_master/slave().
2880 if (!ctlr->devm_allocated)
2881 put_device(&ctlr->dev);
2884 mutex_lock(&board_lock);
2886 idr_remove(&spi_master_idr, id);
2887 mutex_unlock(&board_lock);
2889 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2890 mutex_unlock(&spi_add_lock);
2892 EXPORT_SYMBOL_GPL(spi_unregister_controller);
2894 int spi_controller_suspend(struct spi_controller *ctlr)
2898 /* Basically no-ops for non-queued controllers */
2902 ret = spi_stop_queue(ctlr);
2904 dev_err(&ctlr->dev, "queue stop failed\n");
2908 EXPORT_SYMBOL_GPL(spi_controller_suspend);
2910 int spi_controller_resume(struct spi_controller *ctlr)
2917 ret = spi_start_queue(ctlr);
2919 dev_err(&ctlr->dev, "queue restart failed\n");
2923 EXPORT_SYMBOL_GPL(spi_controller_resume);
2925 static int __spi_controller_match(struct device *dev, const void *data)
2927 struct spi_controller *ctlr;
2928 const u16 *bus_num = data;
2930 ctlr = container_of(dev, struct spi_controller, dev);
2931 return ctlr->bus_num == *bus_num;
2935 * spi_busnum_to_master - look up master associated with bus_num
2936 * @bus_num: the master's bus number
2937 * Context: can sleep
2939 * This call may be used with devices that are registered after
2940 * arch init time. It returns a refcounted pointer to the relevant
2941 * spi_controller (which the caller must release), or NULL if there is
2942 * no such master registered.
2944 * Return: the SPI master structure on success, else NULL.
2946 struct spi_controller *spi_busnum_to_master(u16 bus_num)
2949 struct spi_controller *ctlr = NULL;
2951 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2952 __spi_controller_match);
2954 ctlr = container_of(dev, struct spi_controller, dev);
2955 /* reference got in class_find_device */
2958 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2960 /*-------------------------------------------------------------------------*/
2962 /* Core methods for SPI resource management */
2965 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2966 * during the processing of a spi_message while using
2968 * @spi: the spi device for which we allocate memory
2969 * @release: the release code to execute for this resource
2970 * @size: size to alloc and return
2971 * @gfp: GFP allocation flags
2973 * Return: the pointer to the allocated data
2975 * This may get enhanced in the future to allocate from a memory pool
2976 * of the @spi_device or @spi_controller to avoid repeated allocations.
2978 void *spi_res_alloc(struct spi_device *spi,
2979 spi_res_release_t release,
2980 size_t size, gfp_t gfp)
2982 struct spi_res *sres;
2984 sres = kzalloc(sizeof(*sres) + size, gfp);
2988 INIT_LIST_HEAD(&sres->entry);
2989 sres->release = release;
2993 EXPORT_SYMBOL_GPL(spi_res_alloc);
2996 * spi_res_free - free an spi resource
2997 * @res: pointer to the custom data of a resource
3000 void spi_res_free(void *res)
3002 struct spi_res *sres = container_of(res, struct spi_res, data);
3007 WARN_ON(!list_empty(&sres->entry));
3010 EXPORT_SYMBOL_GPL(spi_res_free);
3013 * spi_res_add - add a spi_res to the spi_message
3014 * @message: the spi message
3015 * @res: the spi_resource
3017 void spi_res_add(struct spi_message *message, void *res)
3019 struct spi_res *sres = container_of(res, struct spi_res, data);
3021 WARN_ON(!list_empty(&sres->entry));
3022 list_add_tail(&sres->entry, &message->resources);
3024 EXPORT_SYMBOL_GPL(spi_res_add);
3027 * spi_res_release - release all spi resources for this message
3028 * @ctlr: the @spi_controller
3029 * @message: the @spi_message
3031 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3033 struct spi_res *res, *tmp;
3035 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3037 res->release(ctlr, message, res->data);
3039 list_del(&res->entry);
3044 EXPORT_SYMBOL_GPL(spi_res_release);
3046 /*-------------------------------------------------------------------------*/
3048 /* Core methods for spi_message alterations */
3050 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3051 struct spi_message *msg,
3054 struct spi_replaced_transfers *rxfer = res;
3057 /* call extra callback if requested */
3059 rxfer->release(ctlr, msg, res);
3061 /* insert replaced transfers back into the message */
3062 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3064 /* remove the formerly inserted entries */
3065 for (i = 0; i < rxfer->inserted; i++)
3066 list_del(&rxfer->inserted_transfers[i].transfer_list);
3070 * spi_replace_transfers - replace transfers with several transfers
3071 * and register change with spi_message.resources
3072 * @msg: the spi_message we work upon
3073 * @xfer_first: the first spi_transfer we want to replace
3074 * @remove: number of transfers to remove
3075 * @insert: the number of transfers we want to insert instead
3076 * @release: extra release code necessary in some circumstances
3077 * @extradatasize: extra data to allocate (with alignment guarantees
3078 * of struct @spi_transfer)
3081 * Returns: pointer to @spi_replaced_transfers,
3082 * PTR_ERR(...) in case of errors.
3084 struct spi_replaced_transfers *spi_replace_transfers(
3085 struct spi_message *msg,
3086 struct spi_transfer *xfer_first,
3089 spi_replaced_release_t release,
3090 size_t extradatasize,
3093 struct spi_replaced_transfers *rxfer;
3094 struct spi_transfer *xfer;
3097 /* allocate the structure using spi_res */
3098 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3099 struct_size(rxfer, inserted_transfers, insert)
3103 return ERR_PTR(-ENOMEM);
3105 /* the release code to invoke before running the generic release */
3106 rxfer->release = release;
3108 /* assign extradata */
3111 &rxfer->inserted_transfers[insert];
3113 /* init the replaced_transfers list */
3114 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3116 /* assign the list_entry after which we should reinsert
3117 * the @replaced_transfers - it may be spi_message.messages!
3119 rxfer->replaced_after = xfer_first->transfer_list.prev;
3121 /* remove the requested number of transfers */
3122 for (i = 0; i < remove; i++) {
3123 /* if the entry after replaced_after it is msg->transfers
3124 * then we have been requested to remove more transfers
3125 * than are in the list
3127 if (rxfer->replaced_after->next == &msg->transfers) {
3128 dev_err(&msg->spi->dev,
3129 "requested to remove more spi_transfers than are available\n");
3130 /* insert replaced transfers back into the message */
3131 list_splice(&rxfer->replaced_transfers,
3132 rxfer->replaced_after);
3134 /* free the spi_replace_transfer structure */
3135 spi_res_free(rxfer);
3137 /* and return with an error */
3138 return ERR_PTR(-EINVAL);
3141 /* remove the entry after replaced_after from list of
3142 * transfers and add it to list of replaced_transfers
3144 list_move_tail(rxfer->replaced_after->next,
3145 &rxfer->replaced_transfers);
3148 /* create copy of the given xfer with identical settings
3149 * based on the first transfer to get removed
3151 for (i = 0; i < insert; i++) {
3152 /* we need to run in reverse order */
3153 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3155 /* copy all spi_transfer data */
3156 memcpy(xfer, xfer_first, sizeof(*xfer));
3159 list_add(&xfer->transfer_list, rxfer->replaced_after);
3161 /* clear cs_change and delay for all but the last */
3163 xfer->cs_change = false;
3164 xfer->delay.value = 0;
3168 /* set up inserted */
3169 rxfer->inserted = insert;
3171 /* and register it with spi_res/spi_message */
3172 spi_res_add(msg, rxfer);
3176 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3178 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3179 struct spi_message *msg,
3180 struct spi_transfer **xferp,
3184 struct spi_transfer *xfer = *xferp, *xfers;
3185 struct spi_replaced_transfers *srt;
3189 /* calculate how many we have to replace */
3190 count = DIV_ROUND_UP(xfer->len, maxsize);
3192 /* create replacement */
3193 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3195 return PTR_ERR(srt);
3196 xfers = srt->inserted_transfers;
3198 /* now handle each of those newly inserted spi_transfers
3199 * note that the replacements spi_transfers all are preset
3200 * to the same values as *xferp, so tx_buf, rx_buf and len
3201 * are all identical (as well as most others)
3202 * so we just have to fix up len and the pointers.
3204 * this also includes support for the depreciated
3205 * spi_message.is_dma_mapped interface
3208 /* the first transfer just needs the length modified, so we
3209 * run it outside the loop
3211 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3213 /* all the others need rx_buf/tx_buf also set */
3214 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3215 /* update rx_buf, tx_buf and dma */
3216 if (xfers[i].rx_buf)
3217 xfers[i].rx_buf += offset;
3218 if (xfers[i].rx_dma)
3219 xfers[i].rx_dma += offset;
3220 if (xfers[i].tx_buf)
3221 xfers[i].tx_buf += offset;
3222 if (xfers[i].tx_dma)
3223 xfers[i].tx_dma += offset;
3226 xfers[i].len = min(maxsize, xfers[i].len - offset);
3229 /* we set up xferp to the last entry we have inserted,
3230 * so that we skip those already split transfers
3232 *xferp = &xfers[count - 1];
3234 /* increment statistics counters */
3235 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3236 transfers_split_maxsize);
3237 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3238 transfers_split_maxsize);
3244 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3245 * when an individual transfer exceeds a
3247 * @ctlr: the @spi_controller for this transfer
3248 * @msg: the @spi_message to transform
3249 * @maxsize: the maximum when to apply this
3250 * @gfp: GFP allocation flags
3252 * Return: status of transformation
3254 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3255 struct spi_message *msg,
3259 struct spi_transfer *xfer;
3262 /* iterate over the transfer_list,
3263 * but note that xfer is advanced to the last transfer inserted
3264 * to avoid checking sizes again unnecessarily (also xfer does
3265 * potentiall belong to a different list by the time the
3266 * replacement has happened
3268 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3269 if (xfer->len > maxsize) {
3270 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3279 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3281 /*-------------------------------------------------------------------------*/
3283 /* Core methods for SPI controller protocol drivers. Some of the
3284 * other core methods are currently defined as inline functions.
3287 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3290 if (ctlr->bits_per_word_mask) {
3291 /* Only 32 bits fit in the mask */
3292 if (bits_per_word > 32)
3294 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3302 * spi_setup - setup SPI mode and clock rate
3303 * @spi: the device whose settings are being modified
3304 * Context: can sleep, and no requests are queued to the device
3306 * SPI protocol drivers may need to update the transfer mode if the
3307 * device doesn't work with its default. They may likewise need
3308 * to update clock rates or word sizes from initial values. This function
3309 * changes those settings, and must be called from a context that can sleep.
3310 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3311 * effect the next time the device is selected and data is transferred to
3312 * or from it. When this function returns, the spi device is deselected.
3314 * Note that this call will fail if the protocol driver specifies an option
3315 * that the underlying controller or its driver does not support. For
3316 * example, not all hardware supports wire transfers using nine bit words,
3317 * LSB-first wire encoding, or active-high chipselects.
3319 * Return: zero on success, else a negative error code.
3321 int spi_setup(struct spi_device *spi)
3323 unsigned bad_bits, ugly_bits;
3327 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3328 * are set at the same time
3330 if ((hweight_long(spi->mode &
3331 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3332 (hweight_long(spi->mode &
3333 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3335 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3338 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3340 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3341 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3342 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3344 /* help drivers fail *cleanly* when they need options
3345 * that aren't supported with their current controller
3346 * SPI_CS_WORD has a fallback software implementation,
3347 * so it is ignored here.
3349 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3350 SPI_NO_TX | SPI_NO_RX);
3351 /* nothing prevents from working with active-high CS in case if it
3352 * is driven by GPIO.
3354 if (gpio_is_valid(spi->cs_gpio))
3355 bad_bits &= ~SPI_CS_HIGH;
3356 ugly_bits = bad_bits &
3357 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3358 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3361 "setup: ignoring unsupported mode bits %x\n",
3363 spi->mode &= ~ugly_bits;
3364 bad_bits &= ~ugly_bits;
3367 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3372 if (!spi->bits_per_word)
3373 spi->bits_per_word = 8;
3375 status = __spi_validate_bits_per_word(spi->controller,
3376 spi->bits_per_word);
3380 if (spi->controller->max_speed_hz &&
3381 (!spi->max_speed_hz ||
3382 spi->max_speed_hz > spi->controller->max_speed_hz))
3383 spi->max_speed_hz = spi->controller->max_speed_hz;
3385 mutex_lock(&spi->controller->io_mutex);
3387 if (spi->controller->setup) {
3388 status = spi->controller->setup(spi);
3390 mutex_unlock(&spi->controller->io_mutex);
3391 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3397 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3398 status = pm_runtime_get_sync(spi->controller->dev.parent);
3400 mutex_unlock(&spi->controller->io_mutex);
3401 pm_runtime_put_noidle(spi->controller->dev.parent);
3402 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3408 * We do not want to return positive value from pm_runtime_get,
3409 * there are many instances of devices calling spi_setup() and
3410 * checking for a non-zero return value instead of a negative
3415 spi_set_cs(spi, false, true);
3416 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3417 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3419 spi_set_cs(spi, false, true);
3422 mutex_unlock(&spi->controller->io_mutex);
3424 if (spi->rt && !spi->controller->rt) {
3425 spi->controller->rt = true;
3426 spi_set_thread_rt(spi->controller);
3429 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3430 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
3431 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3432 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3433 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3434 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3435 spi->bits_per_word, spi->max_speed_hz,
3440 EXPORT_SYMBOL_GPL(spi_setup);
3443 * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3444 * @spi: the device that requires specific CS timing configuration
3445 * @setup: CS setup time specified via @spi_delay
3446 * @hold: CS hold time specified via @spi_delay
3447 * @inactive: CS inactive delay between transfers specified via @spi_delay
3449 * Return: zero on success, else a negative error code.
3451 int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
3452 struct spi_delay *hold, struct spi_delay *inactive)
3454 struct device *parent = spi->controller->dev.parent;
3458 if (spi->controller->set_cs_timing &&
3459 !(spi->cs_gpiod || gpio_is_valid(spi->cs_gpio))) {
3460 if (spi->controller->auto_runtime_pm) {
3461 status = pm_runtime_get_sync(parent);
3463 pm_runtime_put_noidle(parent);
3464 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3469 status = spi->controller->set_cs_timing(spi, setup,
3471 pm_runtime_mark_last_busy(parent);
3472 pm_runtime_put_autosuspend(parent);
3475 return spi->controller->set_cs_timing(spi, setup, hold,
3480 if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
3481 (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
3482 (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
3484 "Clock-cycle delays for CS not supported in SW mode\n");
3488 len = sizeof(struct spi_delay);
3490 /* copy delays to controller */
3492 memcpy(&spi->controller->cs_setup, setup, len);
3494 memset(&spi->controller->cs_setup, 0, len);
3497 memcpy(&spi->controller->cs_hold, hold, len);
3499 memset(&spi->controller->cs_hold, 0, len);
3502 memcpy(&spi->controller->cs_inactive, inactive, len);
3504 memset(&spi->controller->cs_inactive, 0, len);
3508 EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3510 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3511 struct spi_device *spi)
3515 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3519 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3523 if (delay1 < delay2)
3524 memcpy(&xfer->word_delay, &spi->word_delay,
3525 sizeof(xfer->word_delay));
3530 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3532 struct spi_controller *ctlr = spi->controller;
3533 struct spi_transfer *xfer;
3536 if (list_empty(&message->transfers))
3539 /* If an SPI controller does not support toggling the CS line on each
3540 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3541 * for the CS line, we can emulate the CS-per-word hardware function by
3542 * splitting transfers into one-word transfers and ensuring that
3543 * cs_change is set for each transfer.
3545 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3547 gpio_is_valid(spi->cs_gpio))) {
3551 maxsize = (spi->bits_per_word + 7) / 8;
3553 /* spi_split_transfers_maxsize() requires message->spi */
3556 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3561 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3562 /* don't change cs_change on the last entry in the list */
3563 if (list_is_last(&xfer->transfer_list, &message->transfers))
3565 xfer->cs_change = 1;
3569 /* Half-duplex links include original MicroWire, and ones with
3570 * only one data pin like SPI_3WIRE (switches direction) or where
3571 * either MOSI or MISO is missing. They can also be caused by
3572 * software limitations.
3574 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3575 (spi->mode & SPI_3WIRE)) {
3576 unsigned flags = ctlr->flags;
3578 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3579 if (xfer->rx_buf && xfer->tx_buf)
3581 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3583 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3589 * Set transfer bits_per_word and max speed as spi device default if
3590 * it is not set for this transfer.
3591 * Set transfer tx_nbits and rx_nbits as single transfer default
3592 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3593 * Ensure transfer word_delay is at least as long as that required by
3596 message->frame_length = 0;
3597 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3598 xfer->effective_speed_hz = 0;
3599 message->frame_length += xfer->len;
3600 if (!xfer->bits_per_word)
3601 xfer->bits_per_word = spi->bits_per_word;
3603 if (!xfer->speed_hz)
3604 xfer->speed_hz = spi->max_speed_hz;
3606 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3607 xfer->speed_hz = ctlr->max_speed_hz;
3609 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3613 * SPI transfer length should be multiple of SPI word size
3614 * where SPI word size should be power-of-two multiple
3616 if (xfer->bits_per_word <= 8)
3618 else if (xfer->bits_per_word <= 16)
3623 /* No partial transfers accepted */
3624 if (xfer->len % w_size)
3627 if (xfer->speed_hz && ctlr->min_speed_hz &&
3628 xfer->speed_hz < ctlr->min_speed_hz)
3631 if (xfer->tx_buf && !xfer->tx_nbits)
3632 xfer->tx_nbits = SPI_NBITS_SINGLE;
3633 if (xfer->rx_buf && !xfer->rx_nbits)
3634 xfer->rx_nbits = SPI_NBITS_SINGLE;
3635 /* check transfer tx/rx_nbits:
3636 * 1. check the value matches one of single, dual and quad
3637 * 2. check tx/rx_nbits match the mode in spi_device
3640 if (spi->mode & SPI_NO_TX)
3642 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3643 xfer->tx_nbits != SPI_NBITS_DUAL &&
3644 xfer->tx_nbits != SPI_NBITS_QUAD)
3646 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3647 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3649 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3650 !(spi->mode & SPI_TX_QUAD))
3653 /* check transfer rx_nbits */
3655 if (spi->mode & SPI_NO_RX)
3657 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3658 xfer->rx_nbits != SPI_NBITS_DUAL &&
3659 xfer->rx_nbits != SPI_NBITS_QUAD)
3661 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3662 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3664 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3665 !(spi->mode & SPI_RX_QUAD))
3669 if (_spi_xfer_word_delay_update(xfer, spi))
3673 message->status = -EINPROGRESS;
3678 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3680 struct spi_controller *ctlr = spi->controller;
3681 struct spi_transfer *xfer;
3684 * Some controllers do not support doing regular SPI transfers. Return
3685 * ENOTSUPP when this is the case.
3687 if (!ctlr->transfer)
3692 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3693 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3695 trace_spi_message_submit(message);
3697 if (!ctlr->ptp_sts_supported) {
3698 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3699 xfer->ptp_sts_word_pre = 0;
3700 ptp_read_system_prets(xfer->ptp_sts);
3704 return ctlr->transfer(spi, message);
3708 * spi_async - asynchronous SPI transfer
3709 * @spi: device with which data will be exchanged
3710 * @message: describes the data transfers, including completion callback
3711 * Context: any (irqs may be blocked, etc)
3713 * This call may be used in_irq and other contexts which can't sleep,
3714 * as well as from task contexts which can sleep.
3716 * The completion callback is invoked in a context which can't sleep.
3717 * Before that invocation, the value of message->status is undefined.
3718 * When the callback is issued, message->status holds either zero (to
3719 * indicate complete success) or a negative error code. After that
3720 * callback returns, the driver which issued the transfer request may
3721 * deallocate the associated memory; it's no longer in use by any SPI
3722 * core or controller driver code.
3724 * Note that although all messages to a spi_device are handled in
3725 * FIFO order, messages may go to different devices in other orders.
3726 * Some device might be higher priority, or have various "hard" access
3727 * time requirements, for example.
3729 * On detection of any fault during the transfer, processing of
3730 * the entire message is aborted, and the device is deselected.
3731 * Until returning from the associated message completion callback,
3732 * no other spi_message queued to that device will be processed.
3733 * (This rule applies equally to all the synchronous transfer calls,
3734 * which are wrappers around this core asynchronous primitive.)
3736 * Return: zero on success, else a negative error code.
3738 int spi_async(struct spi_device *spi, struct spi_message *message)
3740 struct spi_controller *ctlr = spi->controller;
3742 unsigned long flags;
3744 ret = __spi_validate(spi, message);
3748 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3750 if (ctlr->bus_lock_flag)
3753 ret = __spi_async(spi, message);
3755 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3759 EXPORT_SYMBOL_GPL(spi_async);
3762 * spi_async_locked - version of spi_async with exclusive bus usage
3763 * @spi: device with which data will be exchanged
3764 * @message: describes the data transfers, including completion callback
3765 * Context: any (irqs may be blocked, etc)
3767 * This call may be used in_irq and other contexts which can't sleep,
3768 * as well as from task contexts which can sleep.
3770 * The completion callback is invoked in a context which can't sleep.
3771 * Before that invocation, the value of message->status is undefined.
3772 * When the callback is issued, message->status holds either zero (to
3773 * indicate complete success) or a negative error code. After that
3774 * callback returns, the driver which issued the transfer request may
3775 * deallocate the associated memory; it's no longer in use by any SPI
3776 * core or controller driver code.
3778 * Note that although all messages to a spi_device are handled in
3779 * FIFO order, messages may go to different devices in other orders.
3780 * Some device might be higher priority, or have various "hard" access
3781 * time requirements, for example.
3783 * On detection of any fault during the transfer, processing of
3784 * the entire message is aborted, and the device is deselected.
3785 * Until returning from the associated message completion callback,
3786 * no other spi_message queued to that device will be processed.
3787 * (This rule applies equally to all the synchronous transfer calls,
3788 * which are wrappers around this core asynchronous primitive.)
3790 * Return: zero on success, else a negative error code.
3792 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3794 struct spi_controller *ctlr = spi->controller;
3796 unsigned long flags;
3798 ret = __spi_validate(spi, message);
3802 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3804 ret = __spi_async(spi, message);
3806 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3811 EXPORT_SYMBOL_GPL(spi_async_locked);
3813 /*-------------------------------------------------------------------------*/
3815 /* Utility methods for SPI protocol drivers, layered on
3816 * top of the core. Some other utility methods are defined as
3820 static void spi_complete(void *arg)
3825 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3827 DECLARE_COMPLETION_ONSTACK(done);
3829 struct spi_controller *ctlr = spi->controller;
3830 unsigned long flags;
3832 status = __spi_validate(spi, message);
3836 message->complete = spi_complete;
3837 message->context = &done;
3840 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3841 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3843 /* If we're not using the legacy transfer method then we will
3844 * try to transfer in the calling context so special case.
3845 * This code would be less tricky if we could remove the
3846 * support for driver implemented message queues.
3848 if (ctlr->transfer == spi_queued_transfer) {
3849 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3851 trace_spi_message_submit(message);
3853 status = __spi_queued_transfer(spi, message, false);
3855 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3857 status = spi_async_locked(spi, message);
3861 /* Push out the messages in the calling context if we
3864 if (ctlr->transfer == spi_queued_transfer) {
3865 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3866 spi_sync_immediate);
3867 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3868 spi_sync_immediate);
3869 __spi_pump_messages(ctlr, false);
3872 wait_for_completion(&done);
3873 status = message->status;
3875 message->context = NULL;
3880 * spi_sync - blocking/synchronous SPI data transfers
3881 * @spi: device with which data will be exchanged
3882 * @message: describes the data transfers
3883 * Context: can sleep
3885 * This call may only be used from a context that may sleep. The sleep
3886 * is non-interruptible, and has no timeout. Low-overhead controller
3887 * drivers may DMA directly into and out of the message buffers.
3889 * Note that the SPI device's chip select is active during the message,
3890 * and then is normally disabled between messages. Drivers for some
3891 * frequently-used devices may want to minimize costs of selecting a chip,
3892 * by leaving it selected in anticipation that the next message will go
3893 * to the same chip. (That may increase power usage.)
3895 * Also, the caller is guaranteeing that the memory associated with the
3896 * message will not be freed before this call returns.
3898 * Return: zero on success, else a negative error code.
3900 int spi_sync(struct spi_device *spi, struct spi_message *message)
3904 mutex_lock(&spi->controller->bus_lock_mutex);
3905 ret = __spi_sync(spi, message);
3906 mutex_unlock(&spi->controller->bus_lock_mutex);
3910 EXPORT_SYMBOL_GPL(spi_sync);
3913 * spi_sync_locked - version of spi_sync with exclusive bus usage
3914 * @spi: device with which data will be exchanged
3915 * @message: describes the data transfers
3916 * Context: can sleep
3918 * This call may only be used from a context that may sleep. The sleep
3919 * is non-interruptible, and has no timeout. Low-overhead controller
3920 * drivers may DMA directly into and out of the message buffers.
3922 * This call should be used by drivers that require exclusive access to the
3923 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3924 * be released by a spi_bus_unlock call when the exclusive access is over.
3926 * Return: zero on success, else a negative error code.
3928 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3930 return __spi_sync(spi, message);
3932 EXPORT_SYMBOL_GPL(spi_sync_locked);
3935 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3936 * @ctlr: SPI bus master that should be locked for exclusive bus access
3937 * Context: can sleep
3939 * This call may only be used from a context that may sleep. The sleep
3940 * is non-interruptible, and has no timeout.
3942 * This call should be used by drivers that require exclusive access to the
3943 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3944 * exclusive access is over. Data transfer must be done by spi_sync_locked
3945 * and spi_async_locked calls when the SPI bus lock is held.
3947 * Return: always zero.
3949 int spi_bus_lock(struct spi_controller *ctlr)
3951 unsigned long flags;
3953 mutex_lock(&ctlr->bus_lock_mutex);
3955 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3956 ctlr->bus_lock_flag = 1;
3957 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3959 /* mutex remains locked until spi_bus_unlock is called */
3963 EXPORT_SYMBOL_GPL(spi_bus_lock);
3966 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3967 * @ctlr: SPI bus master that was locked for exclusive bus access
3968 * Context: can sleep
3970 * This call may only be used from a context that may sleep. The sleep
3971 * is non-interruptible, and has no timeout.
3973 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3976 * Return: always zero.
3978 int spi_bus_unlock(struct spi_controller *ctlr)
3980 ctlr->bus_lock_flag = 0;
3982 mutex_unlock(&ctlr->bus_lock_mutex);
3986 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3988 /* portable code must never pass more than 32 bytes */
3989 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
3994 * spi_write_then_read - SPI synchronous write followed by read
3995 * @spi: device with which data will be exchanged
3996 * @txbuf: data to be written (need not be dma-safe)
3997 * @n_tx: size of txbuf, in bytes
3998 * @rxbuf: buffer into which data will be read (need not be dma-safe)
3999 * @n_rx: size of rxbuf, in bytes
4000 * Context: can sleep
4002 * This performs a half duplex MicroWire style transaction with the
4003 * device, sending txbuf and then reading rxbuf. The return value
4004 * is zero for success, else a negative errno status code.
4005 * This call may only be used from a context that may sleep.
4007 * Parameters to this routine are always copied using a small buffer.
4008 * Performance-sensitive or bulk transfer code should instead use
4009 * spi_{async,sync}() calls with dma-safe buffers.
4011 * Return: zero on success, else a negative error code.
4013 int spi_write_then_read(struct spi_device *spi,
4014 const void *txbuf, unsigned n_tx,
4015 void *rxbuf, unsigned n_rx)
4017 static DEFINE_MUTEX(lock);
4020 struct spi_message message;
4021 struct spi_transfer x[2];
4024 /* Use preallocated DMA-safe buffer if we can. We can't avoid
4025 * copying here, (as a pure convenience thing), but we can
4026 * keep heap costs out of the hot path unless someone else is
4027 * using the pre-allocated buffer or the transfer is too large.
4029 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4030 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4031 GFP_KERNEL | GFP_DMA);
4038 spi_message_init(&message);
4039 memset(x, 0, sizeof(x));
4042 spi_message_add_tail(&x[0], &message);
4046 spi_message_add_tail(&x[1], &message);
4049 memcpy(local_buf, txbuf, n_tx);
4050 x[0].tx_buf = local_buf;
4051 x[1].rx_buf = local_buf + n_tx;
4054 status = spi_sync(spi, &message);
4056 memcpy(rxbuf, x[1].rx_buf, n_rx);
4058 if (x[0].tx_buf == buf)
4059 mutex_unlock(&lock);
4065 EXPORT_SYMBOL_GPL(spi_write_then_read);
4067 /*-------------------------------------------------------------------------*/
4069 #if IS_ENABLED(CONFIG_OF)
4070 /* must call put_device() when done with returned spi_device device */
4071 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4073 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4075 return dev ? to_spi_device(dev) : NULL;
4077 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4078 #endif /* IS_ENABLED(CONFIG_OF) */
4080 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4081 /* the spi controllers are not using spi_bus, so we find it with another way */
4082 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4086 dev = class_find_device_by_of_node(&spi_master_class, node);
4087 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4088 dev = class_find_device_by_of_node(&spi_slave_class, node);
4092 /* reference got in class_find_device */
4093 return container_of(dev, struct spi_controller, dev);
4096 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4099 struct of_reconfig_data *rd = arg;
4100 struct spi_controller *ctlr;
4101 struct spi_device *spi;
4103 switch (of_reconfig_get_state_change(action, arg)) {
4104 case OF_RECONFIG_CHANGE_ADD:
4105 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4107 return NOTIFY_OK; /* not for us */
4109 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4110 put_device(&ctlr->dev);
4114 spi = of_register_spi_device(ctlr, rd->dn);
4115 put_device(&ctlr->dev);
4118 pr_err("%s: failed to create for '%pOF'\n",
4120 of_node_clear_flag(rd->dn, OF_POPULATED);
4121 return notifier_from_errno(PTR_ERR(spi));
4125 case OF_RECONFIG_CHANGE_REMOVE:
4126 /* already depopulated? */
4127 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4130 /* find our device by node */
4131 spi = of_find_spi_device_by_node(rd->dn);
4133 return NOTIFY_OK; /* no? not meant for us */
4135 /* unregister takes one ref away */
4136 spi_unregister_device(spi);
4138 /* and put the reference of the find */
4139 put_device(&spi->dev);
4146 static struct notifier_block spi_of_notifier = {
4147 .notifier_call = of_spi_notify,
4149 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4150 extern struct notifier_block spi_of_notifier;
4151 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4153 #if IS_ENABLED(CONFIG_ACPI)
4154 static int spi_acpi_controller_match(struct device *dev, const void *data)
4156 return ACPI_COMPANION(dev->parent) == data;
4159 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4163 dev = class_find_device(&spi_master_class, NULL, adev,
4164 spi_acpi_controller_match);
4165 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4166 dev = class_find_device(&spi_slave_class, NULL, adev,
4167 spi_acpi_controller_match);
4171 return container_of(dev, struct spi_controller, dev);
4174 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4178 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4179 return to_spi_device(dev);
4182 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4185 struct acpi_device *adev = arg;
4186 struct spi_controller *ctlr;
4187 struct spi_device *spi;
4190 case ACPI_RECONFIG_DEVICE_ADD:
4191 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4195 acpi_register_spi_device(ctlr, adev);
4196 put_device(&ctlr->dev);
4198 case ACPI_RECONFIG_DEVICE_REMOVE:
4199 if (!acpi_device_enumerated(adev))
4202 spi = acpi_spi_find_device_by_adev(adev);
4206 spi_unregister_device(spi);
4207 put_device(&spi->dev);
4214 static struct notifier_block spi_acpi_notifier = {
4215 .notifier_call = acpi_spi_notify,
4218 extern struct notifier_block spi_acpi_notifier;
4221 static int __init spi_init(void)
4225 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4231 status = bus_register(&spi_bus_type);
4235 status = class_register(&spi_master_class);
4239 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4240 status = class_register(&spi_slave_class);
4245 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4246 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4247 if (IS_ENABLED(CONFIG_ACPI))
4248 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4253 class_unregister(&spi_master_class);
4255 bus_unregister(&spi_bus_type);
4263 /* board_info is normally registered in arch_initcall(),
4264 * but even essential drivers wait till later
4266 * REVISIT only boardinfo really needs static linking. the rest (device and
4267 * driver registration) _could_ be dynamically linked (modular) ... costs
4268 * include needing to have boardinfo data structures be much more public.
4270 postcore_initcall(spi_init);