1 // SPDX-License-Identifier: GPL-2.0-or-later
4 // Copyright (C) 2005 David Brownell
5 // Copyright (C) 2008 Secret Lab Technologies Ltd.
7 #include <linux/kernel.h>
8 #include <linux/device.h>
9 #include <linux/init.h>
10 #include <linux/cache.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/dmaengine.h>
13 #include <linux/mutex.h>
14 #include <linux/of_device.h>
15 #include <linux/of_irq.h>
16 #include <linux/clk/clk-conf.h>
17 #include <linux/slab.h>
18 #include <linux/mod_devicetable.h>
19 #include <linux/spi/spi.h>
20 #include <linux/spi/spi-mem.h>
21 #include <linux/of_gpio.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/pm_domain.h>
25 #include <linux/property.h>
26 #include <linux/export.h>
27 #include <linux/sched/rt.h>
28 #include <uapi/linux/sched/types.h>
29 #include <linux/delay.h>
30 #include <linux/kthread.h>
31 #include <linux/ioport.h>
32 #include <linux/acpi.h>
33 #include <linux/highmem.h>
34 #include <linux/idr.h>
35 #include <linux/platform_data/x86/apple.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/spi.h>
39 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
42 #include "internals.h"
44 static DEFINE_IDR(spi_master_idr);
46 static void spidev_release(struct device *dev)
48 struct spi_device *spi = to_spi_device(dev);
50 /* spi controllers may cleanup for released devices */
51 if (spi->controller->cleanup)
52 spi->controller->cleanup(spi);
54 spi_controller_put(spi->controller);
55 kfree(spi->driver_override);
60 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
62 const struct spi_device *spi = to_spi_device(dev);
65 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
69 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
71 static DEVICE_ATTR_RO(modalias);
73 static ssize_t driver_override_store(struct device *dev,
74 struct device_attribute *a,
75 const char *buf, size_t count)
77 struct spi_device *spi = to_spi_device(dev);
78 const char *end = memchr(buf, '\n', count);
79 const size_t len = end ? end - buf : count;
80 const char *driver_override, *old;
82 /* We need to keep extra room for a newline when displaying value */
83 if (len >= (PAGE_SIZE - 1))
86 driver_override = kstrndup(buf, len, GFP_KERNEL);
91 old = spi->driver_override;
93 spi->driver_override = driver_override;
95 /* Empty string, disable driver override */
96 spi->driver_override = NULL;
97 kfree(driver_override);
105 static ssize_t driver_override_show(struct device *dev,
106 struct device_attribute *a, char *buf)
108 const struct spi_device *spi = to_spi_device(dev);
112 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
116 static DEVICE_ATTR_RW(driver_override);
118 #define SPI_STATISTICS_ATTRS(field, file) \
119 static ssize_t spi_controller_##field##_show(struct device *dev, \
120 struct device_attribute *attr, \
123 struct spi_controller *ctlr = container_of(dev, \
124 struct spi_controller, dev); \
125 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
127 static struct device_attribute dev_attr_spi_controller_##field = { \
128 .attr = { .name = file, .mode = 0444 }, \
129 .show = spi_controller_##field##_show, \
131 static ssize_t spi_device_##field##_show(struct device *dev, \
132 struct device_attribute *attr, \
135 struct spi_device *spi = to_spi_device(dev); \
136 return spi_statistics_##field##_show(&spi->statistics, buf); \
138 static struct device_attribute dev_attr_spi_device_##field = { \
139 .attr = { .name = file, .mode = 0444 }, \
140 .show = spi_device_##field##_show, \
143 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
144 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
147 unsigned long flags; \
149 spin_lock_irqsave(&stat->lock, flags); \
150 len = sprintf(buf, format_string, stat->field); \
151 spin_unlock_irqrestore(&stat->lock, flags); \
154 SPI_STATISTICS_ATTRS(name, file)
156 #define SPI_STATISTICS_SHOW(field, format_string) \
157 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
158 field, format_string)
160 SPI_STATISTICS_SHOW(messages, "%lu");
161 SPI_STATISTICS_SHOW(transfers, "%lu");
162 SPI_STATISTICS_SHOW(errors, "%lu");
163 SPI_STATISTICS_SHOW(timedout, "%lu");
165 SPI_STATISTICS_SHOW(spi_sync, "%lu");
166 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
167 SPI_STATISTICS_SHOW(spi_async, "%lu");
169 SPI_STATISTICS_SHOW(bytes, "%llu");
170 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
171 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
173 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
174 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
175 "transfer_bytes_histo_" number, \
176 transfer_bytes_histo[index], "%lu")
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
190 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
191 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
192 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
193 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
195 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
197 static struct attribute *spi_dev_attrs[] = {
198 &dev_attr_modalias.attr,
199 &dev_attr_driver_override.attr,
203 static const struct attribute_group spi_dev_group = {
204 .attrs = spi_dev_attrs,
207 static struct attribute *spi_device_statistics_attrs[] = {
208 &dev_attr_spi_device_messages.attr,
209 &dev_attr_spi_device_transfers.attr,
210 &dev_attr_spi_device_errors.attr,
211 &dev_attr_spi_device_timedout.attr,
212 &dev_attr_spi_device_spi_sync.attr,
213 &dev_attr_spi_device_spi_sync_immediate.attr,
214 &dev_attr_spi_device_spi_async.attr,
215 &dev_attr_spi_device_bytes.attr,
216 &dev_attr_spi_device_bytes_rx.attr,
217 &dev_attr_spi_device_bytes_tx.attr,
218 &dev_attr_spi_device_transfer_bytes_histo0.attr,
219 &dev_attr_spi_device_transfer_bytes_histo1.attr,
220 &dev_attr_spi_device_transfer_bytes_histo2.attr,
221 &dev_attr_spi_device_transfer_bytes_histo3.attr,
222 &dev_attr_spi_device_transfer_bytes_histo4.attr,
223 &dev_attr_spi_device_transfer_bytes_histo5.attr,
224 &dev_attr_spi_device_transfer_bytes_histo6.attr,
225 &dev_attr_spi_device_transfer_bytes_histo7.attr,
226 &dev_attr_spi_device_transfer_bytes_histo8.attr,
227 &dev_attr_spi_device_transfer_bytes_histo9.attr,
228 &dev_attr_spi_device_transfer_bytes_histo10.attr,
229 &dev_attr_spi_device_transfer_bytes_histo11.attr,
230 &dev_attr_spi_device_transfer_bytes_histo12.attr,
231 &dev_attr_spi_device_transfer_bytes_histo13.attr,
232 &dev_attr_spi_device_transfer_bytes_histo14.attr,
233 &dev_attr_spi_device_transfer_bytes_histo15.attr,
234 &dev_attr_spi_device_transfer_bytes_histo16.attr,
235 &dev_attr_spi_device_transfers_split_maxsize.attr,
239 static const struct attribute_group spi_device_statistics_group = {
240 .name = "statistics",
241 .attrs = spi_device_statistics_attrs,
244 static const struct attribute_group *spi_dev_groups[] = {
246 &spi_device_statistics_group,
250 static struct attribute *spi_controller_statistics_attrs[] = {
251 &dev_attr_spi_controller_messages.attr,
252 &dev_attr_spi_controller_transfers.attr,
253 &dev_attr_spi_controller_errors.attr,
254 &dev_attr_spi_controller_timedout.attr,
255 &dev_attr_spi_controller_spi_sync.attr,
256 &dev_attr_spi_controller_spi_sync_immediate.attr,
257 &dev_attr_spi_controller_spi_async.attr,
258 &dev_attr_spi_controller_bytes.attr,
259 &dev_attr_spi_controller_bytes_rx.attr,
260 &dev_attr_spi_controller_bytes_tx.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
274 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
275 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
276 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
277 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
278 &dev_attr_spi_controller_transfers_split_maxsize.attr,
282 static const struct attribute_group spi_controller_statistics_group = {
283 .name = "statistics",
284 .attrs = spi_controller_statistics_attrs,
287 static const struct attribute_group *spi_master_groups[] = {
288 &spi_controller_statistics_group,
292 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
293 struct spi_transfer *xfer,
294 struct spi_controller *ctlr)
297 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
302 spin_lock_irqsave(&stats->lock, flags);
305 stats->transfer_bytes_histo[l2len]++;
307 stats->bytes += xfer->len;
308 if ((xfer->tx_buf) &&
309 (xfer->tx_buf != ctlr->dummy_tx))
310 stats->bytes_tx += xfer->len;
311 if ((xfer->rx_buf) &&
312 (xfer->rx_buf != ctlr->dummy_rx))
313 stats->bytes_rx += xfer->len;
315 spin_unlock_irqrestore(&stats->lock, flags);
317 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
319 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
320 * and the sysfs version makes coldplug work too.
323 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
324 const struct spi_device *sdev)
326 while (id->name[0]) {
327 if (!strcmp(sdev->modalias, id->name))
334 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
336 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
338 return spi_match_id(sdrv->id_table, sdev);
340 EXPORT_SYMBOL_GPL(spi_get_device_id);
342 static int spi_match_device(struct device *dev, struct device_driver *drv)
344 const struct spi_device *spi = to_spi_device(dev);
345 const struct spi_driver *sdrv = to_spi_driver(drv);
347 /* Check override first, and if set, only use the named driver */
348 if (spi->driver_override)
349 return strcmp(spi->driver_override, drv->name) == 0;
351 /* Attempt an OF style match */
352 if (of_driver_match_device(dev, drv))
356 if (acpi_driver_match_device(dev, drv))
360 return !!spi_match_id(sdrv->id_table, spi);
362 return strcmp(spi->modalias, drv->name) == 0;
365 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
367 const struct spi_device *spi = to_spi_device(dev);
370 rc = acpi_device_uevent_modalias(dev, env);
374 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
377 static int spi_probe(struct device *dev)
379 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
380 struct spi_device *spi = to_spi_device(dev);
383 ret = of_clk_set_defaults(dev->of_node, false);
388 spi->irq = of_irq_get(dev->of_node, 0);
389 if (spi->irq == -EPROBE_DEFER)
390 return -EPROBE_DEFER;
395 ret = dev_pm_domain_attach(dev, true);
400 ret = sdrv->probe(spi);
402 dev_pm_domain_detach(dev, true);
408 static int spi_remove(struct device *dev)
410 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
415 ret = sdrv->remove(to_spi_device(dev));
418 "Failed to unbind driver (%pe), ignoring\n",
422 dev_pm_domain_detach(dev, true);
427 static void spi_shutdown(struct device *dev)
430 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
433 sdrv->shutdown(to_spi_device(dev));
437 struct bus_type spi_bus_type = {
439 .dev_groups = spi_dev_groups,
440 .match = spi_match_device,
441 .uevent = spi_uevent,
443 .remove = spi_remove,
444 .shutdown = spi_shutdown,
446 EXPORT_SYMBOL_GPL(spi_bus_type);
449 * __spi_register_driver - register a SPI driver
450 * @owner: owner module of the driver to register
451 * @sdrv: the driver to register
454 * Return: zero on success, else a negative error code.
456 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
458 sdrv->driver.owner = owner;
459 sdrv->driver.bus = &spi_bus_type;
460 return driver_register(&sdrv->driver);
462 EXPORT_SYMBOL_GPL(__spi_register_driver);
464 /*-------------------------------------------------------------------------*/
466 /* SPI devices should normally not be created by SPI device drivers; that
467 * would make them board-specific. Similarly with SPI controller drivers.
468 * Device registration normally goes into like arch/.../mach.../board-YYY.c
469 * with other readonly (flashable) information about mainboard devices.
473 struct list_head list;
474 struct spi_board_info board_info;
477 static LIST_HEAD(board_list);
478 static LIST_HEAD(spi_controller_list);
481 * Used to protect add/del operation for board_info list and
482 * spi_controller list, and their matching process
483 * also used to protect object of type struct idr
485 static DEFINE_MUTEX(board_lock);
488 * Prevents addition of devices with same chip select and
489 * addition of devices below an unregistering controller.
491 static DEFINE_MUTEX(spi_add_lock);
494 * spi_alloc_device - Allocate a new SPI device
495 * @ctlr: Controller to which device is connected
498 * Allows a driver to allocate and initialize a spi_device without
499 * registering it immediately. This allows a driver to directly
500 * fill the spi_device with device parameters before calling
501 * spi_add_device() on it.
503 * Caller is responsible to call spi_add_device() on the returned
504 * spi_device structure to add it to the SPI controller. If the caller
505 * needs to discard the spi_device without adding it, then it should
506 * call spi_dev_put() on it.
508 * Return: a pointer to the new device, or NULL.
510 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
512 struct spi_device *spi;
514 if (!spi_controller_get(ctlr))
517 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
519 spi_controller_put(ctlr);
523 spi->master = spi->controller = ctlr;
524 spi->dev.parent = &ctlr->dev;
525 spi->dev.bus = &spi_bus_type;
526 spi->dev.release = spidev_release;
527 spi->cs_gpio = -ENOENT;
528 spi->mode = ctlr->buswidth_override_bits;
530 spin_lock_init(&spi->statistics.lock);
532 device_initialize(&spi->dev);
535 EXPORT_SYMBOL_GPL(spi_alloc_device);
537 static void spi_dev_set_name(struct spi_device *spi)
539 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
542 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
546 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
550 static int spi_dev_check(struct device *dev, void *data)
552 struct spi_device *spi = to_spi_device(dev);
553 struct spi_device *new_spi = data;
555 if (spi->controller == new_spi->controller &&
556 spi->chip_select == new_spi->chip_select)
562 * spi_add_device - Add spi_device allocated with spi_alloc_device
563 * @spi: spi_device to register
565 * Companion function to spi_alloc_device. Devices allocated with
566 * spi_alloc_device can be added onto the spi bus with this function.
568 * Return: 0 on success; negative errno on failure
570 int spi_add_device(struct spi_device *spi)
572 struct spi_controller *ctlr = spi->controller;
573 struct device *dev = ctlr->dev.parent;
576 /* Chipselects are numbered 0..max; validate. */
577 if (spi->chip_select >= ctlr->num_chipselect) {
578 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
579 ctlr->num_chipselect);
583 /* Set the bus ID string */
584 spi_dev_set_name(spi);
586 /* We need to make sure there's no other device with this
587 * chipselect **BEFORE** we call setup(), else we'll trash
588 * its configuration. Lock against concurrent add() calls.
590 mutex_lock(&spi_add_lock);
592 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
594 dev_err(dev, "chipselect %d already in use\n",
599 /* Controller may unregister concurrently */
600 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
601 !device_is_registered(&ctlr->dev)) {
606 /* Descriptors take precedence */
608 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
609 else if (ctlr->cs_gpios)
610 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
612 /* Drivers may modify this initial i/o setup, but will
613 * normally rely on the device being setup. Devices
614 * using SPI_CS_HIGH can't coexist well otherwise...
616 status = spi_setup(spi);
618 dev_err(dev, "can't setup %s, status %d\n",
619 dev_name(&spi->dev), status);
623 /* Device may be bound to an active driver when this returns */
624 status = device_add(&spi->dev);
626 dev_err(dev, "can't add %s, status %d\n",
627 dev_name(&spi->dev), status);
629 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
632 mutex_unlock(&spi_add_lock);
635 EXPORT_SYMBOL_GPL(spi_add_device);
638 * spi_new_device - instantiate one new SPI device
639 * @ctlr: Controller to which device is connected
640 * @chip: Describes the SPI device
643 * On typical mainboards, this is purely internal; and it's not needed
644 * after board init creates the hard-wired devices. Some development
645 * platforms may not be able to use spi_register_board_info though, and
646 * this is exported so that for example a USB or parport based adapter
647 * driver could add devices (which it would learn about out-of-band).
649 * Return: the new device, or NULL.
651 struct spi_device *spi_new_device(struct spi_controller *ctlr,
652 struct spi_board_info *chip)
654 struct spi_device *proxy;
657 /* NOTE: caller did any chip->bus_num checks necessary.
659 * Also, unless we change the return value convention to use
660 * error-or-pointer (not NULL-or-pointer), troubleshootability
661 * suggests syslogged diagnostics are best here (ugh).
664 proxy = spi_alloc_device(ctlr);
668 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
670 proxy->chip_select = chip->chip_select;
671 proxy->max_speed_hz = chip->max_speed_hz;
672 proxy->mode = chip->mode;
673 proxy->irq = chip->irq;
674 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
675 proxy->dev.platform_data = (void *) chip->platform_data;
676 proxy->controller_data = chip->controller_data;
677 proxy->controller_state = NULL;
679 if (chip->properties) {
680 status = device_add_properties(&proxy->dev, chip->properties);
683 "failed to add properties to '%s': %d\n",
684 chip->modalias, status);
689 status = spi_add_device(proxy);
691 goto err_remove_props;
696 if (chip->properties)
697 device_remove_properties(&proxy->dev);
702 EXPORT_SYMBOL_GPL(spi_new_device);
705 * spi_unregister_device - unregister a single SPI device
706 * @spi: spi_device to unregister
708 * Start making the passed SPI device vanish. Normally this would be handled
709 * by spi_unregister_controller().
711 void spi_unregister_device(struct spi_device *spi)
716 if (spi->dev.of_node) {
717 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
718 of_node_put(spi->dev.of_node);
720 if (ACPI_COMPANION(&spi->dev))
721 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
722 device_unregister(&spi->dev);
724 EXPORT_SYMBOL_GPL(spi_unregister_device);
726 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
727 struct spi_board_info *bi)
729 struct spi_device *dev;
731 if (ctlr->bus_num != bi->bus_num)
734 dev = spi_new_device(ctlr, bi);
736 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
741 * spi_register_board_info - register SPI devices for a given board
742 * @info: array of chip descriptors
743 * @n: how many descriptors are provided
746 * Board-specific early init code calls this (probably during arch_initcall)
747 * with segments of the SPI device table. Any device nodes are created later,
748 * after the relevant parent SPI controller (bus_num) is defined. We keep
749 * this table of devices forever, so that reloading a controller driver will
750 * not make Linux forget about these hard-wired devices.
752 * Other code can also call this, e.g. a particular add-on board might provide
753 * SPI devices through its expansion connector, so code initializing that board
754 * would naturally declare its SPI devices.
756 * The board info passed can safely be __initdata ... but be careful of
757 * any embedded pointers (platform_data, etc), they're copied as-is.
758 * Device properties are deep-copied though.
760 * Return: zero on success, else a negative error code.
762 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
764 struct boardinfo *bi;
770 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
774 for (i = 0; i < n; i++, bi++, info++) {
775 struct spi_controller *ctlr;
777 memcpy(&bi->board_info, info, sizeof(*info));
778 if (info->properties) {
779 bi->board_info.properties =
780 property_entries_dup(info->properties);
781 if (IS_ERR(bi->board_info.properties))
782 return PTR_ERR(bi->board_info.properties);
785 mutex_lock(&board_lock);
786 list_add_tail(&bi->list, &board_list);
787 list_for_each_entry(ctlr, &spi_controller_list, list)
788 spi_match_controller_to_boardinfo(ctlr,
790 mutex_unlock(&board_lock);
796 /*-------------------------------------------------------------------------*/
798 static void spi_set_cs(struct spi_device *spi, bool enable)
800 bool enable1 = enable;
803 * Avoid calling into the driver (or doing delays) if the chip select
804 * isn't actually changing from the last time this was called.
806 if ((spi->controller->last_cs_enable == enable) &&
807 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
810 spi->controller->last_cs_enable = enable;
811 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
813 if (!spi->controller->set_cs_timing) {
815 spi_delay_exec(&spi->controller->cs_setup, NULL);
817 spi_delay_exec(&spi->controller->cs_hold, NULL);
820 if (spi->mode & SPI_CS_HIGH)
823 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
824 if (!(spi->mode & SPI_NO_CS)) {
826 /* polarity handled by gpiolib */
827 gpiod_set_value_cansleep(spi->cs_gpiod,
831 * invert the enable line, as active low is
834 gpio_set_value_cansleep(spi->cs_gpio, !enable);
836 /* Some SPI masters need both GPIO CS & slave_select */
837 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
838 spi->controller->set_cs)
839 spi->controller->set_cs(spi, !enable);
840 } else if (spi->controller->set_cs) {
841 spi->controller->set_cs(spi, !enable);
844 if (!spi->controller->set_cs_timing) {
846 spi_delay_exec(&spi->controller->cs_inactive, NULL);
850 #ifdef CONFIG_HAS_DMA
851 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
852 struct sg_table *sgt, void *buf, size_t len,
853 enum dma_data_direction dir)
855 const bool vmalloced_buf = is_vmalloc_addr(buf);
856 unsigned int max_seg_size = dma_get_max_seg_size(dev);
857 #ifdef CONFIG_HIGHMEM
858 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
859 (unsigned long)buf < (PKMAP_BASE +
860 (LAST_PKMAP * PAGE_SIZE)));
862 const bool kmap_buf = false;
866 struct page *vm_page;
867 struct scatterlist *sg;
872 if (vmalloced_buf || kmap_buf) {
873 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
874 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
875 } else if (virt_addr_valid(buf)) {
876 desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
877 sgs = DIV_ROUND_UP(len, desc_len);
882 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
887 for (i = 0; i < sgs; i++) {
889 if (vmalloced_buf || kmap_buf) {
891 * Next scatterlist entry size is the minimum between
892 * the desc_len and the remaining buffer length that
895 min = min_t(size_t, desc_len,
897 PAGE_SIZE - offset_in_page(buf)));
899 vm_page = vmalloc_to_page(buf);
901 vm_page = kmap_to_page(buf);
906 sg_set_page(sg, vm_page,
907 min, offset_in_page(buf));
909 min = min_t(size_t, len, desc_len);
911 sg_set_buf(sg, sg_buf, min);
919 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
932 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
933 struct sg_table *sgt, enum dma_data_direction dir)
935 if (sgt->orig_nents) {
936 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
941 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
943 struct device *tx_dev, *rx_dev;
944 struct spi_transfer *xfer;
951 tx_dev = ctlr->dma_tx->device->dev;
953 tx_dev = ctlr->dev.parent;
956 rx_dev = ctlr->dma_rx->device->dev;
958 rx_dev = ctlr->dev.parent;
960 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
961 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
964 if (xfer->tx_buf != NULL) {
965 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
966 (void *)xfer->tx_buf, xfer->len,
972 if (xfer->rx_buf != NULL) {
973 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
974 xfer->rx_buf, xfer->len,
977 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
984 ctlr->cur_msg_mapped = true;
989 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
991 struct spi_transfer *xfer;
992 struct device *tx_dev, *rx_dev;
994 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
998 tx_dev = ctlr->dma_tx->device->dev;
1000 tx_dev = ctlr->dev.parent;
1003 rx_dev = ctlr->dma_rx->device->dev;
1005 rx_dev = ctlr->dev.parent;
1007 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1008 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1011 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1012 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1015 ctlr->cur_msg_mapped = false;
1019 #else /* !CONFIG_HAS_DMA */
1020 static inline int __spi_map_msg(struct spi_controller *ctlr,
1021 struct spi_message *msg)
1026 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1027 struct spi_message *msg)
1031 #endif /* !CONFIG_HAS_DMA */
1033 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1034 struct spi_message *msg)
1036 struct spi_transfer *xfer;
1038 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1040 * Restore the original value of tx_buf or rx_buf if they are
1043 if (xfer->tx_buf == ctlr->dummy_tx)
1044 xfer->tx_buf = NULL;
1045 if (xfer->rx_buf == ctlr->dummy_rx)
1046 xfer->rx_buf = NULL;
1049 return __spi_unmap_msg(ctlr, msg);
1052 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1054 struct spi_transfer *xfer;
1056 unsigned int max_tx, max_rx;
1058 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1059 && !(msg->spi->mode & SPI_3WIRE)) {
1063 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1064 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1066 max_tx = max(xfer->len, max_tx);
1067 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1069 max_rx = max(xfer->len, max_rx);
1073 tmp = krealloc(ctlr->dummy_tx, max_tx,
1074 GFP_KERNEL | GFP_DMA);
1077 ctlr->dummy_tx = tmp;
1078 memset(tmp, 0, max_tx);
1082 tmp = krealloc(ctlr->dummy_rx, max_rx,
1083 GFP_KERNEL | GFP_DMA);
1086 ctlr->dummy_rx = tmp;
1089 if (max_tx || max_rx) {
1090 list_for_each_entry(xfer, &msg->transfers,
1095 xfer->tx_buf = ctlr->dummy_tx;
1097 xfer->rx_buf = ctlr->dummy_rx;
1102 return __spi_map_msg(ctlr, msg);
1105 static int spi_transfer_wait(struct spi_controller *ctlr,
1106 struct spi_message *msg,
1107 struct spi_transfer *xfer)
1109 struct spi_statistics *statm = &ctlr->statistics;
1110 struct spi_statistics *stats = &msg->spi->statistics;
1111 unsigned long long ms;
1113 if (spi_controller_is_slave(ctlr)) {
1114 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1115 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1119 ms = 8LL * 1000LL * xfer->len;
1120 do_div(ms, xfer->speed_hz);
1121 ms += ms + 200; /* some tolerance */
1126 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1127 msecs_to_jiffies(ms));
1130 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1131 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1132 dev_err(&msg->spi->dev,
1133 "SPI transfer timed out\n");
1141 static void _spi_transfer_delay_ns(u32 ns)
1148 u32 us = DIV_ROUND_UP(ns, 1000);
1153 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1157 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1159 u32 delay = _delay->value;
1160 u32 unit = _delay->unit;
1167 case SPI_DELAY_UNIT_USECS:
1170 case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1172 case SPI_DELAY_UNIT_SCK:
1173 /* clock cycles need to be obtained from spi_transfer */
1176 /* if there is no effective speed know, then approximate
1177 * by underestimating with half the requested hz
1179 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1182 delay *= DIV_ROUND_UP(1000000000, hz);
1190 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1192 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1201 delay = spi_delay_to_ns(_delay, xfer);
1205 _spi_transfer_delay_ns(delay);
1209 EXPORT_SYMBOL_GPL(spi_delay_exec);
1211 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1212 struct spi_transfer *xfer)
1214 u32 delay = xfer->cs_change_delay.value;
1215 u32 unit = xfer->cs_change_delay.unit;
1218 /* return early on "fast" mode - for everything but USECS */
1220 if (unit == SPI_DELAY_UNIT_USECS)
1221 _spi_transfer_delay_ns(10000);
1225 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1227 dev_err_once(&msg->spi->dev,
1228 "Use of unsupported delay unit %i, using default of 10us\n",
1230 _spi_transfer_delay_ns(10000);
1235 * spi_transfer_one_message - Default implementation of transfer_one_message()
1237 * This is a standard implementation of transfer_one_message() for
1238 * drivers which implement a transfer_one() operation. It provides
1239 * standard handling of delays and chip select management.
1241 static int spi_transfer_one_message(struct spi_controller *ctlr,
1242 struct spi_message *msg)
1244 struct spi_transfer *xfer;
1245 bool keep_cs = false;
1247 struct spi_statistics *statm = &ctlr->statistics;
1248 struct spi_statistics *stats = &msg->spi->statistics;
1250 spi_set_cs(msg->spi, true);
1252 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1253 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1255 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1256 trace_spi_transfer_start(msg, xfer);
1258 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1259 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1261 if (!ctlr->ptp_sts_supported) {
1262 xfer->ptp_sts_word_pre = 0;
1263 ptp_read_system_prets(xfer->ptp_sts);
1266 if (xfer->tx_buf || xfer->rx_buf) {
1267 reinit_completion(&ctlr->xfer_completion);
1270 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1272 if (ctlr->cur_msg_mapped &&
1273 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1274 __spi_unmap_msg(ctlr, msg);
1275 ctlr->fallback = true;
1276 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1280 SPI_STATISTICS_INCREMENT_FIELD(statm,
1282 SPI_STATISTICS_INCREMENT_FIELD(stats,
1284 dev_err(&msg->spi->dev,
1285 "SPI transfer failed: %d\n", ret);
1290 ret = spi_transfer_wait(ctlr, msg, xfer);
1296 dev_err(&msg->spi->dev,
1297 "Bufferless transfer has length %u\n",
1301 if (!ctlr->ptp_sts_supported) {
1302 ptp_read_system_postts(xfer->ptp_sts);
1303 xfer->ptp_sts_word_post = xfer->len;
1306 trace_spi_transfer_stop(msg, xfer);
1308 if (msg->status != -EINPROGRESS)
1311 spi_transfer_delay_exec(xfer);
1313 if (xfer->cs_change) {
1314 if (list_is_last(&xfer->transfer_list,
1318 spi_set_cs(msg->spi, false);
1319 _spi_transfer_cs_change_delay(msg, xfer);
1320 spi_set_cs(msg->spi, true);
1324 msg->actual_length += xfer->len;
1328 if (ret != 0 || !keep_cs)
1329 spi_set_cs(msg->spi, false);
1331 if (msg->status == -EINPROGRESS)
1334 if (msg->status && ctlr->handle_err)
1335 ctlr->handle_err(ctlr, msg);
1337 spi_finalize_current_message(ctlr);
1343 * spi_finalize_current_transfer - report completion of a transfer
1344 * @ctlr: the controller reporting completion
1346 * Called by SPI drivers using the core transfer_one_message()
1347 * implementation to notify it that the current interrupt driven
1348 * transfer has finished and the next one may be scheduled.
1350 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1352 complete(&ctlr->xfer_completion);
1354 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1356 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1358 if (ctlr->auto_runtime_pm) {
1359 pm_runtime_mark_last_busy(ctlr->dev.parent);
1360 pm_runtime_put_autosuspend(ctlr->dev.parent);
1365 * __spi_pump_messages - function which processes spi message queue
1366 * @ctlr: controller to process queue for
1367 * @in_kthread: true if we are in the context of the message pump thread
1369 * This function checks if there is any spi message in the queue that
1370 * needs processing and if so call out to the driver to initialize hardware
1371 * and transfer each message.
1373 * Note that it is called both from the kthread itself and also from
1374 * inside spi_sync(); the queue extraction handling at the top of the
1375 * function should deal with this safely.
1377 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1379 struct spi_transfer *xfer;
1380 struct spi_message *msg;
1381 bool was_busy = false;
1382 unsigned long flags;
1386 spin_lock_irqsave(&ctlr->queue_lock, flags);
1388 /* Make sure we are not already running a message */
1389 if (ctlr->cur_msg) {
1390 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1394 /* If another context is idling the device then defer */
1396 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1397 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1401 /* Check if the queue is idle */
1402 if (list_empty(&ctlr->queue) || !ctlr->running) {
1404 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1408 /* Defer any non-atomic teardown to the thread */
1410 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1411 !ctlr->unprepare_transfer_hardware) {
1412 spi_idle_runtime_pm(ctlr);
1414 trace_spi_controller_idle(ctlr);
1416 kthread_queue_work(ctlr->kworker,
1417 &ctlr->pump_messages);
1419 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1424 ctlr->idling = true;
1425 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1427 kfree(ctlr->dummy_rx);
1428 ctlr->dummy_rx = NULL;
1429 kfree(ctlr->dummy_tx);
1430 ctlr->dummy_tx = NULL;
1431 if (ctlr->unprepare_transfer_hardware &&
1432 ctlr->unprepare_transfer_hardware(ctlr))
1434 "failed to unprepare transfer hardware\n");
1435 spi_idle_runtime_pm(ctlr);
1436 trace_spi_controller_idle(ctlr);
1438 spin_lock_irqsave(&ctlr->queue_lock, flags);
1439 ctlr->idling = false;
1440 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1444 /* Extract head of queue */
1445 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1446 ctlr->cur_msg = msg;
1448 list_del_init(&msg->queue);
1453 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1455 mutex_lock(&ctlr->io_mutex);
1457 if (!was_busy && ctlr->auto_runtime_pm) {
1458 ret = pm_runtime_get_sync(ctlr->dev.parent);
1460 pm_runtime_put_noidle(ctlr->dev.parent);
1461 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1463 mutex_unlock(&ctlr->io_mutex);
1469 trace_spi_controller_busy(ctlr);
1471 if (!was_busy && ctlr->prepare_transfer_hardware) {
1472 ret = ctlr->prepare_transfer_hardware(ctlr);
1475 "failed to prepare transfer hardware: %d\n",
1478 if (ctlr->auto_runtime_pm)
1479 pm_runtime_put(ctlr->dev.parent);
1482 spi_finalize_current_message(ctlr);
1484 mutex_unlock(&ctlr->io_mutex);
1489 trace_spi_message_start(msg);
1491 if (ctlr->prepare_message) {
1492 ret = ctlr->prepare_message(ctlr, msg);
1494 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1497 spi_finalize_current_message(ctlr);
1500 ctlr->cur_msg_prepared = true;
1503 ret = spi_map_msg(ctlr, msg);
1506 spi_finalize_current_message(ctlr);
1510 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1511 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1512 xfer->ptp_sts_word_pre = 0;
1513 ptp_read_system_prets(xfer->ptp_sts);
1517 ret = ctlr->transfer_one_message(ctlr, msg);
1520 "failed to transfer one message from queue\n");
1525 mutex_unlock(&ctlr->io_mutex);
1527 /* Prod the scheduler in case transfer_one() was busy waiting */
1533 * spi_pump_messages - kthread work function which processes spi message queue
1534 * @work: pointer to kthread work struct contained in the controller struct
1536 static void spi_pump_messages(struct kthread_work *work)
1538 struct spi_controller *ctlr =
1539 container_of(work, struct spi_controller, pump_messages);
1541 __spi_pump_messages(ctlr, true);
1545 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1546 * TX timestamp for the requested byte from the SPI
1547 * transfer. The frequency with which this function
1548 * must be called (once per word, once for the whole
1549 * transfer, once per batch of words etc) is arbitrary
1550 * as long as the @tx buffer offset is greater than or
1551 * equal to the requested byte at the time of the
1552 * call. The timestamp is only taken once, at the
1553 * first such call. It is assumed that the driver
1554 * advances its @tx buffer pointer monotonically.
1555 * @ctlr: Pointer to the spi_controller structure of the driver
1556 * @xfer: Pointer to the transfer being timestamped
1557 * @progress: How many words (not bytes) have been transferred so far
1558 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1559 * transfer, for less jitter in time measurement. Only compatible
1560 * with PIO drivers. If true, must follow up with
1561 * spi_take_timestamp_post or otherwise system will crash.
1562 * WARNING: for fully predictable results, the CPU frequency must
1563 * also be under control (governor).
1565 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1566 struct spi_transfer *xfer,
1567 size_t progress, bool irqs_off)
1572 if (xfer->timestamped)
1575 if (progress > xfer->ptp_sts_word_pre)
1578 /* Capture the resolution of the timestamp */
1579 xfer->ptp_sts_word_pre = progress;
1582 local_irq_save(ctlr->irq_flags);
1586 ptp_read_system_prets(xfer->ptp_sts);
1588 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1591 * spi_take_timestamp_post - helper for drivers to collect the end of the
1592 * TX timestamp for the requested byte from the SPI
1593 * transfer. Can be called with an arbitrary
1594 * frequency: only the first call where @tx exceeds
1595 * or is equal to the requested word will be
1597 * @ctlr: Pointer to the spi_controller structure of the driver
1598 * @xfer: Pointer to the transfer being timestamped
1599 * @progress: How many words (not bytes) have been transferred so far
1600 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1602 void spi_take_timestamp_post(struct spi_controller *ctlr,
1603 struct spi_transfer *xfer,
1604 size_t progress, bool irqs_off)
1609 if (xfer->timestamped)
1612 if (progress < xfer->ptp_sts_word_post)
1615 ptp_read_system_postts(xfer->ptp_sts);
1618 local_irq_restore(ctlr->irq_flags);
1622 /* Capture the resolution of the timestamp */
1623 xfer->ptp_sts_word_post = progress;
1625 xfer->timestamped = true;
1627 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1630 * spi_set_thread_rt - set the controller to pump at realtime priority
1631 * @ctlr: controller to boost priority of
1633 * This can be called because the controller requested realtime priority
1634 * (by setting the ->rt value before calling spi_register_controller()) or
1635 * because a device on the bus said that its transfers needed realtime
1638 * NOTE: at the moment if any device on a bus says it needs realtime then
1639 * the thread will be at realtime priority for all transfers on that
1640 * controller. If this eventually becomes a problem we may see if we can
1641 * find a way to boost the priority only temporarily during relevant
1644 static void spi_set_thread_rt(struct spi_controller *ctlr)
1646 dev_info(&ctlr->dev,
1647 "will run message pump with realtime priority\n");
1648 sched_set_fifo(ctlr->kworker->task);
1651 static int spi_init_queue(struct spi_controller *ctlr)
1653 ctlr->running = false;
1656 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1657 if (IS_ERR(ctlr->kworker)) {
1658 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1659 return PTR_ERR(ctlr->kworker);
1662 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1665 * Controller config will indicate if this controller should run the
1666 * message pump with high (realtime) priority to reduce the transfer
1667 * latency on the bus by minimising the delay between a transfer
1668 * request and the scheduling of the message pump thread. Without this
1669 * setting the message pump thread will remain at default priority.
1672 spi_set_thread_rt(ctlr);
1678 * spi_get_next_queued_message() - called by driver to check for queued
1680 * @ctlr: the controller to check for queued messages
1682 * If there are more messages in the queue, the next message is returned from
1685 * Return: the next message in the queue, else NULL if the queue is empty.
1687 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1689 struct spi_message *next;
1690 unsigned long flags;
1692 /* get a pointer to the next message, if any */
1693 spin_lock_irqsave(&ctlr->queue_lock, flags);
1694 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1696 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1700 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1703 * spi_finalize_current_message() - the current message is complete
1704 * @ctlr: the controller to return the message to
1706 * Called by the driver to notify the core that the message in the front of the
1707 * queue is complete and can be removed from the queue.
1709 void spi_finalize_current_message(struct spi_controller *ctlr)
1711 struct spi_transfer *xfer;
1712 struct spi_message *mesg;
1713 unsigned long flags;
1716 spin_lock_irqsave(&ctlr->queue_lock, flags);
1717 mesg = ctlr->cur_msg;
1718 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1720 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1721 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1722 ptp_read_system_postts(xfer->ptp_sts);
1723 xfer->ptp_sts_word_post = xfer->len;
1727 if (unlikely(ctlr->ptp_sts_supported))
1728 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1729 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1731 spi_unmap_msg(ctlr, mesg);
1733 /* In the prepare_messages callback the spi bus has the opportunity to
1734 * split a transfer to smaller chunks.
1735 * Release splited transfers here since spi_map_msg is done on the
1736 * splited transfers.
1738 spi_res_release(ctlr, mesg);
1740 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1741 ret = ctlr->unprepare_message(ctlr, mesg);
1743 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1748 spin_lock_irqsave(&ctlr->queue_lock, flags);
1749 ctlr->cur_msg = NULL;
1750 ctlr->cur_msg_prepared = false;
1751 ctlr->fallback = false;
1752 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1753 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1755 trace_spi_message_done(mesg);
1759 mesg->complete(mesg->context);
1761 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1763 static int spi_start_queue(struct spi_controller *ctlr)
1765 unsigned long flags;
1767 spin_lock_irqsave(&ctlr->queue_lock, flags);
1769 if (ctlr->running || ctlr->busy) {
1770 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1774 ctlr->running = true;
1775 ctlr->cur_msg = NULL;
1776 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1778 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1783 static int spi_stop_queue(struct spi_controller *ctlr)
1785 unsigned long flags;
1786 unsigned limit = 500;
1789 spin_lock_irqsave(&ctlr->queue_lock, flags);
1792 * This is a bit lame, but is optimized for the common execution path.
1793 * A wait_queue on the ctlr->busy could be used, but then the common
1794 * execution path (pump_messages) would be required to call wake_up or
1795 * friends on every SPI message. Do this instead.
1797 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1798 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1799 usleep_range(10000, 11000);
1800 spin_lock_irqsave(&ctlr->queue_lock, flags);
1803 if (!list_empty(&ctlr->queue) || ctlr->busy)
1806 ctlr->running = false;
1808 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1811 dev_warn(&ctlr->dev, "could not stop message queue\n");
1817 static int spi_destroy_queue(struct spi_controller *ctlr)
1821 ret = spi_stop_queue(ctlr);
1824 * kthread_flush_worker will block until all work is done.
1825 * If the reason that stop_queue timed out is that the work will never
1826 * finish, then it does no good to call flush/stop thread, so
1830 dev_err(&ctlr->dev, "problem destroying queue\n");
1834 kthread_destroy_worker(ctlr->kworker);
1839 static int __spi_queued_transfer(struct spi_device *spi,
1840 struct spi_message *msg,
1843 struct spi_controller *ctlr = spi->controller;
1844 unsigned long flags;
1846 spin_lock_irqsave(&ctlr->queue_lock, flags);
1848 if (!ctlr->running) {
1849 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1852 msg->actual_length = 0;
1853 msg->status = -EINPROGRESS;
1855 list_add_tail(&msg->queue, &ctlr->queue);
1856 if (!ctlr->busy && need_pump)
1857 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1859 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1864 * spi_queued_transfer - transfer function for queued transfers
1865 * @spi: spi device which is requesting transfer
1866 * @msg: spi message which is to handled is queued to driver queue
1868 * Return: zero on success, else a negative error code.
1870 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1872 return __spi_queued_transfer(spi, msg, true);
1875 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1879 ctlr->transfer = spi_queued_transfer;
1880 if (!ctlr->transfer_one_message)
1881 ctlr->transfer_one_message = spi_transfer_one_message;
1883 /* Initialize and start queue */
1884 ret = spi_init_queue(ctlr);
1886 dev_err(&ctlr->dev, "problem initializing queue\n");
1887 goto err_init_queue;
1889 ctlr->queued = true;
1890 ret = spi_start_queue(ctlr);
1892 dev_err(&ctlr->dev, "problem starting queue\n");
1893 goto err_start_queue;
1899 spi_destroy_queue(ctlr);
1905 * spi_flush_queue - Send all pending messages in the queue from the callers'
1907 * @ctlr: controller to process queue for
1909 * This should be used when one wants to ensure all pending messages have been
1910 * sent before doing something. Is used by the spi-mem code to make sure SPI
1911 * memory operations do not preempt regular SPI transfers that have been queued
1912 * before the spi-mem operation.
1914 void spi_flush_queue(struct spi_controller *ctlr)
1916 if (ctlr->transfer == spi_queued_transfer)
1917 __spi_pump_messages(ctlr, false);
1920 /*-------------------------------------------------------------------------*/
1922 #if defined(CONFIG_OF)
1923 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1924 struct device_node *nc)
1929 /* Mode (clock phase/polarity/etc.) */
1930 if (of_property_read_bool(nc, "spi-cpha"))
1931 spi->mode |= SPI_CPHA;
1932 if (of_property_read_bool(nc, "spi-cpol"))
1933 spi->mode |= SPI_CPOL;
1934 if (of_property_read_bool(nc, "spi-3wire"))
1935 spi->mode |= SPI_3WIRE;
1936 if (of_property_read_bool(nc, "spi-lsb-first"))
1937 spi->mode |= SPI_LSB_FIRST;
1938 if (of_property_read_bool(nc, "spi-cs-high"))
1939 spi->mode |= SPI_CS_HIGH;
1941 /* Device DUAL/QUAD mode */
1942 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1945 spi->mode |= SPI_NO_TX;
1950 spi->mode |= SPI_TX_DUAL;
1953 spi->mode |= SPI_TX_QUAD;
1956 spi->mode |= SPI_TX_OCTAL;
1959 dev_warn(&ctlr->dev,
1960 "spi-tx-bus-width %d not supported\n",
1966 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1969 spi->mode |= SPI_NO_RX;
1974 spi->mode |= SPI_RX_DUAL;
1977 spi->mode |= SPI_RX_QUAD;
1980 spi->mode |= SPI_RX_OCTAL;
1983 dev_warn(&ctlr->dev,
1984 "spi-rx-bus-width %d not supported\n",
1990 if (spi_controller_is_slave(ctlr)) {
1991 if (!of_node_name_eq(nc, "slave")) {
1992 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
1999 /* Device address */
2000 rc = of_property_read_u32(nc, "reg", &value);
2002 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2006 spi->chip_select = value;
2009 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2010 spi->max_speed_hz = value;
2015 static struct spi_device *
2016 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2018 struct spi_device *spi;
2021 /* Alloc an spi_device */
2022 spi = spi_alloc_device(ctlr);
2024 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2029 /* Select device driver */
2030 rc = of_modalias_node(nc, spi->modalias,
2031 sizeof(spi->modalias));
2033 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2037 rc = of_spi_parse_dt(ctlr, spi, nc);
2041 /* Store a pointer to the node in the device structure */
2043 spi->dev.of_node = nc;
2045 /* Register the new device */
2046 rc = spi_add_device(spi);
2048 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2049 goto err_of_node_put;
2062 * of_register_spi_devices() - Register child devices onto the SPI bus
2063 * @ctlr: Pointer to spi_controller device
2065 * Registers an spi_device for each child node of controller node which
2066 * represents a valid SPI slave.
2068 static void of_register_spi_devices(struct spi_controller *ctlr)
2070 struct spi_device *spi;
2071 struct device_node *nc;
2073 if (!ctlr->dev.of_node)
2076 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2077 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2079 spi = of_register_spi_device(ctlr, nc);
2081 dev_warn(&ctlr->dev,
2082 "Failed to create SPI device for %pOF\n", nc);
2083 of_node_clear_flag(nc, OF_POPULATED);
2088 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2092 struct acpi_spi_lookup {
2093 struct spi_controller *ctlr;
2101 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2102 struct acpi_spi_lookup *lookup)
2104 const union acpi_object *obj;
2106 if (!x86_apple_machine)
2109 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2110 && obj->buffer.length >= 4)
2111 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2113 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2114 && obj->buffer.length == 8)
2115 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2117 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2118 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2119 lookup->mode |= SPI_LSB_FIRST;
2121 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2122 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2123 lookup->mode |= SPI_CPOL;
2125 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2126 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2127 lookup->mode |= SPI_CPHA;
2130 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2132 struct acpi_spi_lookup *lookup = data;
2133 struct spi_controller *ctlr = lookup->ctlr;
2135 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2136 struct acpi_resource_spi_serialbus *sb;
2137 acpi_handle parent_handle;
2140 sb = &ares->data.spi_serial_bus;
2141 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2143 status = acpi_get_handle(NULL,
2144 sb->resource_source.string_ptr,
2147 if (ACPI_FAILURE(status) ||
2148 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2152 * ACPI DeviceSelection numbering is handled by the
2153 * host controller driver in Windows and can vary
2154 * from driver to driver. In Linux we always expect
2155 * 0 .. max - 1 so we need to ask the driver to
2156 * translate between the two schemes.
2158 if (ctlr->fw_translate_cs) {
2159 int cs = ctlr->fw_translate_cs(ctlr,
2160 sb->device_selection);
2163 lookup->chip_select = cs;
2165 lookup->chip_select = sb->device_selection;
2168 lookup->max_speed_hz = sb->connection_speed;
2169 lookup->bits_per_word = sb->data_bit_length;
2171 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2172 lookup->mode |= SPI_CPHA;
2173 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2174 lookup->mode |= SPI_CPOL;
2175 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2176 lookup->mode |= SPI_CS_HIGH;
2178 } else if (lookup->irq < 0) {
2181 if (acpi_dev_resource_interrupt(ares, 0, &r))
2182 lookup->irq = r.start;
2185 /* Always tell the ACPI core to skip this resource */
2189 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2190 struct acpi_device *adev)
2192 acpi_handle parent_handle = NULL;
2193 struct list_head resource_list;
2194 struct acpi_spi_lookup lookup = {};
2195 struct spi_device *spi;
2198 if (acpi_bus_get_status(adev) || !adev->status.present ||
2199 acpi_device_enumerated(adev))
2205 INIT_LIST_HEAD(&resource_list);
2206 ret = acpi_dev_get_resources(adev, &resource_list,
2207 acpi_spi_add_resource, &lookup);
2208 acpi_dev_free_resource_list(&resource_list);
2211 /* found SPI in _CRS but it points to another controller */
2214 if (!lookup.max_speed_hz &&
2215 !ACPI_FAILURE(acpi_get_parent(adev->handle, &parent_handle)) &&
2216 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2217 /* Apple does not use _CRS but nested devices for SPI slaves */
2218 acpi_spi_parse_apple_properties(adev, &lookup);
2221 if (!lookup.max_speed_hz)
2224 spi = spi_alloc_device(ctlr);
2226 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2227 dev_name(&adev->dev));
2228 return AE_NO_MEMORY;
2232 ACPI_COMPANION_SET(&spi->dev, adev);
2233 spi->max_speed_hz = lookup.max_speed_hz;
2234 spi->mode |= lookup.mode;
2235 spi->irq = lookup.irq;
2236 spi->bits_per_word = lookup.bits_per_word;
2237 spi->chip_select = lookup.chip_select;
2239 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2240 sizeof(spi->modalias));
2243 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2245 acpi_device_set_enumerated(adev);
2247 adev->power.flags.ignore_parent = true;
2248 if (spi_add_device(spi)) {
2249 adev->power.flags.ignore_parent = false;
2250 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2251 dev_name(&adev->dev));
2258 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2259 void *data, void **return_value)
2261 struct spi_controller *ctlr = data;
2262 struct acpi_device *adev;
2264 if (acpi_bus_get_device(handle, &adev))
2267 return acpi_register_spi_device(ctlr, adev);
2270 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2272 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2277 handle = ACPI_HANDLE(ctlr->dev.parent);
2281 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2282 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2283 acpi_spi_add_device, NULL, ctlr, NULL);
2284 if (ACPI_FAILURE(status))
2285 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2288 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2289 #endif /* CONFIG_ACPI */
2291 static void spi_controller_release(struct device *dev)
2293 struct spi_controller *ctlr;
2295 ctlr = container_of(dev, struct spi_controller, dev);
2299 static struct class spi_master_class = {
2300 .name = "spi_master",
2301 .owner = THIS_MODULE,
2302 .dev_release = spi_controller_release,
2303 .dev_groups = spi_master_groups,
2306 #ifdef CONFIG_SPI_SLAVE
2308 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2310 * @spi: device used for the current transfer
2312 int spi_slave_abort(struct spi_device *spi)
2314 struct spi_controller *ctlr = spi->controller;
2316 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2317 return ctlr->slave_abort(ctlr);
2321 EXPORT_SYMBOL_GPL(spi_slave_abort);
2323 static int match_true(struct device *dev, void *data)
2328 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2331 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2333 struct device *child;
2335 child = device_find_child(&ctlr->dev, NULL, match_true);
2336 return sprintf(buf, "%s\n",
2337 child ? to_spi_device(child)->modalias : NULL);
2340 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2341 const char *buf, size_t count)
2343 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2345 struct spi_device *spi;
2346 struct device *child;
2350 rc = sscanf(buf, "%31s", name);
2351 if (rc != 1 || !name[0])
2354 child = device_find_child(&ctlr->dev, NULL, match_true);
2356 /* Remove registered slave */
2357 device_unregister(child);
2361 if (strcmp(name, "(null)")) {
2362 /* Register new slave */
2363 spi = spi_alloc_device(ctlr);
2367 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2369 rc = spi_add_device(spi);
2379 static DEVICE_ATTR_RW(slave);
2381 static struct attribute *spi_slave_attrs[] = {
2382 &dev_attr_slave.attr,
2386 static const struct attribute_group spi_slave_group = {
2387 .attrs = spi_slave_attrs,
2390 static const struct attribute_group *spi_slave_groups[] = {
2391 &spi_controller_statistics_group,
2396 static struct class spi_slave_class = {
2397 .name = "spi_slave",
2398 .owner = THIS_MODULE,
2399 .dev_release = spi_controller_release,
2400 .dev_groups = spi_slave_groups,
2403 extern struct class spi_slave_class; /* dummy */
2407 * __spi_alloc_controller - allocate an SPI master or slave controller
2408 * @dev: the controller, possibly using the platform_bus
2409 * @size: how much zeroed driver-private data to allocate; the pointer to this
2410 * memory is in the driver_data field of the returned device, accessible
2411 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2412 * drivers granting DMA access to portions of their private data need to
2413 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2414 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2415 * slave (true) controller
2416 * Context: can sleep
2418 * This call is used only by SPI controller drivers, which are the
2419 * only ones directly touching chip registers. It's how they allocate
2420 * an spi_controller structure, prior to calling spi_register_controller().
2422 * This must be called from context that can sleep.
2424 * The caller is responsible for assigning the bus number and initializing the
2425 * controller's methods before calling spi_register_controller(); and (after
2426 * errors adding the device) calling spi_controller_put() to prevent a memory
2429 * Return: the SPI controller structure on success, else NULL.
2431 struct spi_controller *__spi_alloc_controller(struct device *dev,
2432 unsigned int size, bool slave)
2434 struct spi_controller *ctlr;
2435 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2440 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2444 device_initialize(&ctlr->dev);
2446 ctlr->num_chipselect = 1;
2447 ctlr->slave = slave;
2448 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2449 ctlr->dev.class = &spi_slave_class;
2451 ctlr->dev.class = &spi_master_class;
2452 ctlr->dev.parent = dev;
2453 pm_suspend_ignore_children(&ctlr->dev, true);
2454 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2458 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2460 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2462 spi_controller_put(*(struct spi_controller **)ctlr);
2466 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2467 * @dev: physical device of SPI controller
2468 * @size: how much zeroed driver-private data to allocate
2469 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2470 * Context: can sleep
2472 * Allocate an SPI controller and automatically release a reference on it
2473 * when @dev is unbound from its driver. Drivers are thus relieved from
2474 * having to call spi_controller_put().
2476 * The arguments to this function are identical to __spi_alloc_controller().
2478 * Return: the SPI controller structure on success, else NULL.
2480 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2484 struct spi_controller **ptr, *ctlr;
2486 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2491 ctlr = __spi_alloc_controller(dev, size, slave);
2494 devres_add(dev, ptr);
2501 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2504 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2507 struct device_node *np = ctlr->dev.of_node;
2512 nb = of_gpio_named_count(np, "cs-gpios");
2513 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2515 /* Return error only for an incorrectly formed cs-gpios property */
2516 if (nb == 0 || nb == -ENOENT)
2521 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2523 ctlr->cs_gpios = cs;
2525 if (!ctlr->cs_gpios)
2528 for (i = 0; i < ctlr->num_chipselect; i++)
2531 for (i = 0; i < nb; i++)
2532 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2537 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2544 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2545 * @ctlr: The SPI master to grab GPIO descriptors for
2547 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2550 struct gpio_desc **cs;
2551 struct device *dev = &ctlr->dev;
2552 unsigned long native_cs_mask = 0;
2553 unsigned int num_cs_gpios = 0;
2555 nb = gpiod_count(dev, "cs");
2556 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2558 /* No GPIOs at all is fine, else return the error */
2559 if (nb == 0 || nb == -ENOENT)
2564 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2568 ctlr->cs_gpiods = cs;
2570 for (i = 0; i < nb; i++) {
2572 * Most chipselects are active low, the inverted
2573 * semantics are handled by special quirks in gpiolib,
2574 * so initializing them GPIOD_OUT_LOW here means
2575 * "unasserted", in most cases this will drive the physical
2578 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2581 return PTR_ERR(cs[i]);
2585 * If we find a CS GPIO, name it after the device and
2590 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2594 gpiod_set_consumer_name(cs[i], gpioname);
2599 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2600 dev_err(dev, "Invalid native chip select %d\n", i);
2603 native_cs_mask |= BIT(i);
2606 ctlr->unused_native_cs = ffz(native_cs_mask);
2607 if (num_cs_gpios && ctlr->max_native_cs &&
2608 ctlr->unused_native_cs >= ctlr->max_native_cs) {
2609 dev_err(dev, "No unused native chip select available\n");
2616 static int spi_controller_check_ops(struct spi_controller *ctlr)
2619 * The controller may implement only the high-level SPI-memory like
2620 * operations if it does not support regular SPI transfers, and this is
2622 * If ->mem_ops is NULL, we request that at least one of the
2623 * ->transfer_xxx() method be implemented.
2625 if (ctlr->mem_ops) {
2626 if (!ctlr->mem_ops->exec_op)
2628 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2629 !ctlr->transfer_one_message) {
2637 * spi_register_controller - register SPI master or slave controller
2638 * @ctlr: initialized master, originally from spi_alloc_master() or
2640 * Context: can sleep
2642 * SPI controllers connect to their drivers using some non-SPI bus,
2643 * such as the platform bus. The final stage of probe() in that code
2644 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2646 * SPI controllers use board specific (often SOC specific) bus numbers,
2647 * and board-specific addressing for SPI devices combines those numbers
2648 * with chip select numbers. Since SPI does not directly support dynamic
2649 * device identification, boards need configuration tables telling which
2650 * chip is at which address.
2652 * This must be called from context that can sleep. It returns zero on
2653 * success, else a negative error code (dropping the controller's refcount).
2654 * After a successful return, the caller is responsible for calling
2655 * spi_unregister_controller().
2657 * Return: zero on success, else a negative error code.
2659 int spi_register_controller(struct spi_controller *ctlr)
2661 struct device *dev = ctlr->dev.parent;
2662 struct boardinfo *bi;
2664 int id, first_dynamic;
2670 * Make sure all necessary hooks are implemented before registering
2671 * the SPI controller.
2673 status = spi_controller_check_ops(ctlr);
2677 if (ctlr->bus_num >= 0) {
2678 /* devices with a fixed bus num must check-in with the num */
2679 mutex_lock(&board_lock);
2680 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2681 ctlr->bus_num + 1, GFP_KERNEL);
2682 mutex_unlock(&board_lock);
2683 if (WARN(id < 0, "couldn't get idr"))
2684 return id == -ENOSPC ? -EBUSY : id;
2686 } else if (ctlr->dev.of_node) {
2687 /* allocate dynamic bus number using Linux idr */
2688 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2691 mutex_lock(&board_lock);
2692 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2693 ctlr->bus_num + 1, GFP_KERNEL);
2694 mutex_unlock(&board_lock);
2695 if (WARN(id < 0, "couldn't get idr"))
2696 return id == -ENOSPC ? -EBUSY : id;
2699 if (ctlr->bus_num < 0) {
2700 first_dynamic = of_alias_get_highest_id("spi");
2701 if (first_dynamic < 0)
2706 mutex_lock(&board_lock);
2707 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2709 mutex_unlock(&board_lock);
2710 if (WARN(id < 0, "couldn't get idr"))
2714 INIT_LIST_HEAD(&ctlr->queue);
2715 spin_lock_init(&ctlr->queue_lock);
2716 spin_lock_init(&ctlr->bus_lock_spinlock);
2717 mutex_init(&ctlr->bus_lock_mutex);
2718 mutex_init(&ctlr->io_mutex);
2719 ctlr->bus_lock_flag = 0;
2720 init_completion(&ctlr->xfer_completion);
2721 if (!ctlr->max_dma_len)
2722 ctlr->max_dma_len = INT_MAX;
2724 /* register the device, then userspace will see it.
2725 * registration fails if the bus ID is in use.
2727 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2729 if (!spi_controller_is_slave(ctlr)) {
2730 if (ctlr->use_gpio_descriptors) {
2731 status = spi_get_gpio_descs(ctlr);
2735 * A controller using GPIO descriptors always
2736 * supports SPI_CS_HIGH if need be.
2738 ctlr->mode_bits |= SPI_CS_HIGH;
2740 /* Legacy code path for GPIOs from DT */
2741 status = of_spi_get_gpio_numbers(ctlr);
2748 * Even if it's just one always-selected device, there must
2749 * be at least one chipselect.
2751 if (!ctlr->num_chipselect) {
2756 status = device_add(&ctlr->dev);
2759 dev_dbg(dev, "registered %s %s\n",
2760 spi_controller_is_slave(ctlr) ? "slave" : "master",
2761 dev_name(&ctlr->dev));
2764 * If we're using a queued driver, start the queue. Note that we don't
2765 * need the queueing logic if the driver is only supporting high-level
2766 * memory operations.
2768 if (ctlr->transfer) {
2769 dev_info(dev, "controller is unqueued, this is deprecated\n");
2770 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2771 status = spi_controller_initialize_queue(ctlr);
2773 device_del(&ctlr->dev);
2777 /* add statistics */
2778 spin_lock_init(&ctlr->statistics.lock);
2780 mutex_lock(&board_lock);
2781 list_add_tail(&ctlr->list, &spi_controller_list);
2782 list_for_each_entry(bi, &board_list, list)
2783 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2784 mutex_unlock(&board_lock);
2786 /* Register devices from the device tree and ACPI */
2787 of_register_spi_devices(ctlr);
2788 acpi_register_spi_devices(ctlr);
2792 mutex_lock(&board_lock);
2793 idr_remove(&spi_master_idr, ctlr->bus_num);
2794 mutex_unlock(&board_lock);
2797 EXPORT_SYMBOL_GPL(spi_register_controller);
2799 static void devm_spi_unregister(struct device *dev, void *res)
2801 spi_unregister_controller(*(struct spi_controller **)res);
2805 * devm_spi_register_controller - register managed SPI master or slave
2807 * @dev: device managing SPI controller
2808 * @ctlr: initialized controller, originally from spi_alloc_master() or
2810 * Context: can sleep
2812 * Register a SPI device as with spi_register_controller() which will
2813 * automatically be unregistered and freed.
2815 * Return: zero on success, else a negative error code.
2817 int devm_spi_register_controller(struct device *dev,
2818 struct spi_controller *ctlr)
2820 struct spi_controller **ptr;
2823 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2827 ret = spi_register_controller(ctlr);
2830 devres_add(dev, ptr);
2837 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2839 static int devm_spi_match_controller(struct device *dev, void *res, void *ctlr)
2841 return *(struct spi_controller **)res == ctlr;
2844 static int __unregister(struct device *dev, void *null)
2846 spi_unregister_device(to_spi_device(dev));
2851 * spi_unregister_controller - unregister SPI master or slave controller
2852 * @ctlr: the controller being unregistered
2853 * Context: can sleep
2855 * This call is used only by SPI controller drivers, which are the
2856 * only ones directly touching chip registers.
2858 * This must be called from context that can sleep.
2860 * Note that this function also drops a reference to the controller.
2862 void spi_unregister_controller(struct spi_controller *ctlr)
2864 struct spi_controller *found;
2865 int id = ctlr->bus_num;
2867 /* Prevent addition of new devices, unregister existing ones */
2868 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2869 mutex_lock(&spi_add_lock);
2871 device_for_each_child(&ctlr->dev, NULL, __unregister);
2873 /* First make sure that this controller was ever added */
2874 mutex_lock(&board_lock);
2875 found = idr_find(&spi_master_idr, id);
2876 mutex_unlock(&board_lock);
2878 if (spi_destroy_queue(ctlr))
2879 dev_err(&ctlr->dev, "queue remove failed\n");
2881 mutex_lock(&board_lock);
2882 list_del(&ctlr->list);
2883 mutex_unlock(&board_lock);
2885 device_del(&ctlr->dev);
2887 /* Release the last reference on the controller if its driver
2888 * has not yet been converted to devm_spi_alloc_master/slave().
2890 if (!devres_find(ctlr->dev.parent, devm_spi_release_controller,
2891 devm_spi_match_controller, ctlr))
2892 put_device(&ctlr->dev);
2895 mutex_lock(&board_lock);
2897 idr_remove(&spi_master_idr, id);
2898 mutex_unlock(&board_lock);
2900 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2901 mutex_unlock(&spi_add_lock);
2903 EXPORT_SYMBOL_GPL(spi_unregister_controller);
2905 int spi_controller_suspend(struct spi_controller *ctlr)
2909 /* Basically no-ops for non-queued controllers */
2913 ret = spi_stop_queue(ctlr);
2915 dev_err(&ctlr->dev, "queue stop failed\n");
2919 EXPORT_SYMBOL_GPL(spi_controller_suspend);
2921 int spi_controller_resume(struct spi_controller *ctlr)
2928 ret = spi_start_queue(ctlr);
2930 dev_err(&ctlr->dev, "queue restart failed\n");
2934 EXPORT_SYMBOL_GPL(spi_controller_resume);
2936 static int __spi_controller_match(struct device *dev, const void *data)
2938 struct spi_controller *ctlr;
2939 const u16 *bus_num = data;
2941 ctlr = container_of(dev, struct spi_controller, dev);
2942 return ctlr->bus_num == *bus_num;
2946 * spi_busnum_to_master - look up master associated with bus_num
2947 * @bus_num: the master's bus number
2948 * Context: can sleep
2950 * This call may be used with devices that are registered after
2951 * arch init time. It returns a refcounted pointer to the relevant
2952 * spi_controller (which the caller must release), or NULL if there is
2953 * no such master registered.
2955 * Return: the SPI master structure on success, else NULL.
2957 struct spi_controller *spi_busnum_to_master(u16 bus_num)
2960 struct spi_controller *ctlr = NULL;
2962 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2963 __spi_controller_match);
2965 ctlr = container_of(dev, struct spi_controller, dev);
2966 /* reference got in class_find_device */
2969 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2971 /*-------------------------------------------------------------------------*/
2973 /* Core methods for SPI resource management */
2976 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2977 * during the processing of a spi_message while using
2979 * @spi: the spi device for which we allocate memory
2980 * @release: the release code to execute for this resource
2981 * @size: size to alloc and return
2982 * @gfp: GFP allocation flags
2984 * Return: the pointer to the allocated data
2986 * This may get enhanced in the future to allocate from a memory pool
2987 * of the @spi_device or @spi_controller to avoid repeated allocations.
2989 void *spi_res_alloc(struct spi_device *spi,
2990 spi_res_release_t release,
2991 size_t size, gfp_t gfp)
2993 struct spi_res *sres;
2995 sres = kzalloc(sizeof(*sres) + size, gfp);
2999 INIT_LIST_HEAD(&sres->entry);
3000 sres->release = release;
3004 EXPORT_SYMBOL_GPL(spi_res_alloc);
3007 * spi_res_free - free an spi resource
3008 * @res: pointer to the custom data of a resource
3011 void spi_res_free(void *res)
3013 struct spi_res *sres = container_of(res, struct spi_res, data);
3018 WARN_ON(!list_empty(&sres->entry));
3021 EXPORT_SYMBOL_GPL(spi_res_free);
3024 * spi_res_add - add a spi_res to the spi_message
3025 * @message: the spi message
3026 * @res: the spi_resource
3028 void spi_res_add(struct spi_message *message, void *res)
3030 struct spi_res *sres = container_of(res, struct spi_res, data);
3032 WARN_ON(!list_empty(&sres->entry));
3033 list_add_tail(&sres->entry, &message->resources);
3035 EXPORT_SYMBOL_GPL(spi_res_add);
3038 * spi_res_release - release all spi resources for this message
3039 * @ctlr: the @spi_controller
3040 * @message: the @spi_message
3042 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3044 struct spi_res *res, *tmp;
3046 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3048 res->release(ctlr, message, res->data);
3050 list_del(&res->entry);
3055 EXPORT_SYMBOL_GPL(spi_res_release);
3057 /*-------------------------------------------------------------------------*/
3059 /* Core methods for spi_message alterations */
3061 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3062 struct spi_message *msg,
3065 struct spi_replaced_transfers *rxfer = res;
3068 /* call extra callback if requested */
3070 rxfer->release(ctlr, msg, res);
3072 /* insert replaced transfers back into the message */
3073 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3075 /* remove the formerly inserted entries */
3076 for (i = 0; i < rxfer->inserted; i++)
3077 list_del(&rxfer->inserted_transfers[i].transfer_list);
3081 * spi_replace_transfers - replace transfers with several transfers
3082 * and register change with spi_message.resources
3083 * @msg: the spi_message we work upon
3084 * @xfer_first: the first spi_transfer we want to replace
3085 * @remove: number of transfers to remove
3086 * @insert: the number of transfers we want to insert instead
3087 * @release: extra release code necessary in some circumstances
3088 * @extradatasize: extra data to allocate (with alignment guarantees
3089 * of struct @spi_transfer)
3092 * Returns: pointer to @spi_replaced_transfers,
3093 * PTR_ERR(...) in case of errors.
3095 struct spi_replaced_transfers *spi_replace_transfers(
3096 struct spi_message *msg,
3097 struct spi_transfer *xfer_first,
3100 spi_replaced_release_t release,
3101 size_t extradatasize,
3104 struct spi_replaced_transfers *rxfer;
3105 struct spi_transfer *xfer;
3108 /* allocate the structure using spi_res */
3109 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3110 struct_size(rxfer, inserted_transfers, insert)
3114 return ERR_PTR(-ENOMEM);
3116 /* the release code to invoke before running the generic release */
3117 rxfer->release = release;
3119 /* assign extradata */
3122 &rxfer->inserted_transfers[insert];
3124 /* init the replaced_transfers list */
3125 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3127 /* assign the list_entry after which we should reinsert
3128 * the @replaced_transfers - it may be spi_message.messages!
3130 rxfer->replaced_after = xfer_first->transfer_list.prev;
3132 /* remove the requested number of transfers */
3133 for (i = 0; i < remove; i++) {
3134 /* if the entry after replaced_after it is msg->transfers
3135 * then we have been requested to remove more transfers
3136 * than are in the list
3138 if (rxfer->replaced_after->next == &msg->transfers) {
3139 dev_err(&msg->spi->dev,
3140 "requested to remove more spi_transfers than are available\n");
3141 /* insert replaced transfers back into the message */
3142 list_splice(&rxfer->replaced_transfers,
3143 rxfer->replaced_after);
3145 /* free the spi_replace_transfer structure */
3146 spi_res_free(rxfer);
3148 /* and return with an error */
3149 return ERR_PTR(-EINVAL);
3152 /* remove the entry after replaced_after from list of
3153 * transfers and add it to list of replaced_transfers
3155 list_move_tail(rxfer->replaced_after->next,
3156 &rxfer->replaced_transfers);
3159 /* create copy of the given xfer with identical settings
3160 * based on the first transfer to get removed
3162 for (i = 0; i < insert; i++) {
3163 /* we need to run in reverse order */
3164 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3166 /* copy all spi_transfer data */
3167 memcpy(xfer, xfer_first, sizeof(*xfer));
3170 list_add(&xfer->transfer_list, rxfer->replaced_after);
3172 /* clear cs_change and delay for all but the last */
3174 xfer->cs_change = false;
3175 xfer->delay_usecs = 0;
3176 xfer->delay.value = 0;
3180 /* set up inserted */
3181 rxfer->inserted = insert;
3183 /* and register it with spi_res/spi_message */
3184 spi_res_add(msg, rxfer);
3188 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3190 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3191 struct spi_message *msg,
3192 struct spi_transfer **xferp,
3196 struct spi_transfer *xfer = *xferp, *xfers;
3197 struct spi_replaced_transfers *srt;
3201 /* calculate how many we have to replace */
3202 count = DIV_ROUND_UP(xfer->len, maxsize);
3204 /* create replacement */
3205 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3207 return PTR_ERR(srt);
3208 xfers = srt->inserted_transfers;
3210 /* now handle each of those newly inserted spi_transfers
3211 * note that the replacements spi_transfers all are preset
3212 * to the same values as *xferp, so tx_buf, rx_buf and len
3213 * are all identical (as well as most others)
3214 * so we just have to fix up len and the pointers.
3216 * this also includes support for the depreciated
3217 * spi_message.is_dma_mapped interface
3220 /* the first transfer just needs the length modified, so we
3221 * run it outside the loop
3223 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3225 /* all the others need rx_buf/tx_buf also set */
3226 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3227 /* update rx_buf, tx_buf and dma */
3228 if (xfers[i].rx_buf)
3229 xfers[i].rx_buf += offset;
3230 if (xfers[i].rx_dma)
3231 xfers[i].rx_dma += offset;
3232 if (xfers[i].tx_buf)
3233 xfers[i].tx_buf += offset;
3234 if (xfers[i].tx_dma)
3235 xfers[i].tx_dma += offset;
3238 xfers[i].len = min(maxsize, xfers[i].len - offset);
3241 /* we set up xferp to the last entry we have inserted,
3242 * so that we skip those already split transfers
3244 *xferp = &xfers[count - 1];
3246 /* increment statistics counters */
3247 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3248 transfers_split_maxsize);
3249 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3250 transfers_split_maxsize);
3256 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3257 * when an individual transfer exceeds a
3259 * @ctlr: the @spi_controller for this transfer
3260 * @msg: the @spi_message to transform
3261 * @maxsize: the maximum when to apply this
3262 * @gfp: GFP allocation flags
3264 * Return: status of transformation
3266 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3267 struct spi_message *msg,
3271 struct spi_transfer *xfer;
3274 /* iterate over the transfer_list,
3275 * but note that xfer is advanced to the last transfer inserted
3276 * to avoid checking sizes again unnecessarily (also xfer does
3277 * potentiall belong to a different list by the time the
3278 * replacement has happened
3280 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3281 if (xfer->len > maxsize) {
3282 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3291 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3293 /*-------------------------------------------------------------------------*/
3295 /* Core methods for SPI controller protocol drivers. Some of the
3296 * other core methods are currently defined as inline functions.
3299 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3302 if (ctlr->bits_per_word_mask) {
3303 /* Only 32 bits fit in the mask */
3304 if (bits_per_word > 32)
3306 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3314 * spi_setup - setup SPI mode and clock rate
3315 * @spi: the device whose settings are being modified
3316 * Context: can sleep, and no requests are queued to the device
3318 * SPI protocol drivers may need to update the transfer mode if the
3319 * device doesn't work with its default. They may likewise need
3320 * to update clock rates or word sizes from initial values. This function
3321 * changes those settings, and must be called from a context that can sleep.
3322 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3323 * effect the next time the device is selected and data is transferred to
3324 * or from it. When this function returns, the spi device is deselected.
3326 * Note that this call will fail if the protocol driver specifies an option
3327 * that the underlying controller or its driver does not support. For
3328 * example, not all hardware supports wire transfers using nine bit words,
3329 * LSB-first wire encoding, or active-high chipselects.
3331 * Return: zero on success, else a negative error code.
3333 int spi_setup(struct spi_device *spi)
3335 unsigned bad_bits, ugly_bits;
3339 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3340 * are set at the same time
3342 if ((hweight_long(spi->mode &
3343 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3344 (hweight_long(spi->mode &
3345 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3347 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3350 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3352 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3353 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3354 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3356 /* help drivers fail *cleanly* when they need options
3357 * that aren't supported with their current controller
3358 * SPI_CS_WORD has a fallback software implementation,
3359 * so it is ignored here.
3361 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3362 SPI_NO_TX | SPI_NO_RX);
3363 /* nothing prevents from working with active-high CS in case if it
3364 * is driven by GPIO.
3366 if (gpio_is_valid(spi->cs_gpio))
3367 bad_bits &= ~SPI_CS_HIGH;
3368 ugly_bits = bad_bits &
3369 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3370 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3373 "setup: ignoring unsupported mode bits %x\n",
3375 spi->mode &= ~ugly_bits;
3376 bad_bits &= ~ugly_bits;
3379 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3384 if (!spi->bits_per_word)
3385 spi->bits_per_word = 8;
3387 status = __spi_validate_bits_per_word(spi->controller,
3388 spi->bits_per_word);
3392 if (!spi->max_speed_hz ||
3393 spi->max_speed_hz > spi->controller->max_speed_hz)
3394 spi->max_speed_hz = spi->controller->max_speed_hz;
3396 mutex_lock(&spi->controller->io_mutex);
3398 if (spi->controller->setup)
3399 status = spi->controller->setup(spi);
3401 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3402 status = pm_runtime_get_sync(spi->controller->dev.parent);
3404 mutex_unlock(&spi->controller->io_mutex);
3405 pm_runtime_put_noidle(spi->controller->dev.parent);
3406 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3412 * We do not want to return positive value from pm_runtime_get,
3413 * there are many instances of devices calling spi_setup() and
3414 * checking for a non-zero return value instead of a negative
3419 spi_set_cs(spi, false);
3420 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3421 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3423 spi_set_cs(spi, false);
3426 mutex_unlock(&spi->controller->io_mutex);
3428 if (spi->rt && !spi->controller->rt) {
3429 spi->controller->rt = true;
3430 spi_set_thread_rt(spi->controller);
3433 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3434 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
3435 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3436 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3437 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3438 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3439 spi->bits_per_word, spi->max_speed_hz,
3444 EXPORT_SYMBOL_GPL(spi_setup);
3447 * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3448 * @spi: the device that requires specific CS timing configuration
3449 * @setup: CS setup time specified via @spi_delay
3450 * @hold: CS hold time specified via @spi_delay
3451 * @inactive: CS inactive delay between transfers specified via @spi_delay
3453 * Return: zero on success, else a negative error code.
3455 int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
3456 struct spi_delay *hold, struct spi_delay *inactive)
3460 if (spi->controller->set_cs_timing)
3461 return spi->controller->set_cs_timing(spi, setup, hold,
3464 if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
3465 (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
3466 (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
3468 "Clock-cycle delays for CS not supported in SW mode\n");
3472 len = sizeof(struct spi_delay);
3474 /* copy delays to controller */
3476 memcpy(&spi->controller->cs_setup, setup, len);
3478 memset(&spi->controller->cs_setup, 0, len);
3481 memcpy(&spi->controller->cs_hold, hold, len);
3483 memset(&spi->controller->cs_hold, 0, len);
3486 memcpy(&spi->controller->cs_inactive, inactive, len);
3488 memset(&spi->controller->cs_inactive, 0, len);
3492 EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3494 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3495 struct spi_device *spi)
3499 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3503 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3507 if (delay1 < delay2)
3508 memcpy(&xfer->word_delay, &spi->word_delay,
3509 sizeof(xfer->word_delay));
3514 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3516 struct spi_controller *ctlr = spi->controller;
3517 struct spi_transfer *xfer;
3520 if (list_empty(&message->transfers))
3523 /* If an SPI controller does not support toggling the CS line on each
3524 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3525 * for the CS line, we can emulate the CS-per-word hardware function by
3526 * splitting transfers into one-word transfers and ensuring that
3527 * cs_change is set for each transfer.
3529 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3531 gpio_is_valid(spi->cs_gpio))) {
3535 maxsize = (spi->bits_per_word + 7) / 8;
3537 /* spi_split_transfers_maxsize() requires message->spi */
3540 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3545 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3546 /* don't change cs_change on the last entry in the list */
3547 if (list_is_last(&xfer->transfer_list, &message->transfers))
3549 xfer->cs_change = 1;
3553 /* Half-duplex links include original MicroWire, and ones with
3554 * only one data pin like SPI_3WIRE (switches direction) or where
3555 * either MOSI or MISO is missing. They can also be caused by
3556 * software limitations.
3558 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3559 (spi->mode & SPI_3WIRE)) {
3560 unsigned flags = ctlr->flags;
3562 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3563 if (xfer->rx_buf && xfer->tx_buf)
3565 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3567 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3573 * Set transfer bits_per_word and max speed as spi device default if
3574 * it is not set for this transfer.
3575 * Set transfer tx_nbits and rx_nbits as single transfer default
3576 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3577 * Ensure transfer word_delay is at least as long as that required by
3580 message->frame_length = 0;
3581 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3582 xfer->effective_speed_hz = 0;
3583 message->frame_length += xfer->len;
3584 if (!xfer->bits_per_word)
3585 xfer->bits_per_word = spi->bits_per_word;
3587 if (!xfer->speed_hz)
3588 xfer->speed_hz = spi->max_speed_hz;
3590 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3591 xfer->speed_hz = ctlr->max_speed_hz;
3593 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3597 * SPI transfer length should be multiple of SPI word size
3598 * where SPI word size should be power-of-two multiple
3600 if (xfer->bits_per_word <= 8)
3602 else if (xfer->bits_per_word <= 16)
3607 /* No partial transfers accepted */
3608 if (xfer->len % w_size)
3611 if (xfer->speed_hz && ctlr->min_speed_hz &&
3612 xfer->speed_hz < ctlr->min_speed_hz)
3615 if (xfer->tx_buf && !xfer->tx_nbits)
3616 xfer->tx_nbits = SPI_NBITS_SINGLE;
3617 if (xfer->rx_buf && !xfer->rx_nbits)
3618 xfer->rx_nbits = SPI_NBITS_SINGLE;
3619 /* check transfer tx/rx_nbits:
3620 * 1. check the value matches one of single, dual and quad
3621 * 2. check tx/rx_nbits match the mode in spi_device
3624 if (spi->mode & SPI_NO_TX)
3626 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3627 xfer->tx_nbits != SPI_NBITS_DUAL &&
3628 xfer->tx_nbits != SPI_NBITS_QUAD)
3630 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3631 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3633 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3634 !(spi->mode & SPI_TX_QUAD))
3637 /* check transfer rx_nbits */
3639 if (spi->mode & SPI_NO_RX)
3641 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3642 xfer->rx_nbits != SPI_NBITS_DUAL &&
3643 xfer->rx_nbits != SPI_NBITS_QUAD)
3645 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3646 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3648 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3649 !(spi->mode & SPI_RX_QUAD))
3653 if (_spi_xfer_word_delay_update(xfer, spi))
3657 message->status = -EINPROGRESS;
3662 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3664 struct spi_controller *ctlr = spi->controller;
3665 struct spi_transfer *xfer;
3668 * Some controllers do not support doing regular SPI transfers. Return
3669 * ENOTSUPP when this is the case.
3671 if (!ctlr->transfer)
3676 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3677 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3679 trace_spi_message_submit(message);
3681 if (!ctlr->ptp_sts_supported) {
3682 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3683 xfer->ptp_sts_word_pre = 0;
3684 ptp_read_system_prets(xfer->ptp_sts);
3688 return ctlr->transfer(spi, message);
3692 * spi_async - asynchronous SPI transfer
3693 * @spi: device with which data will be exchanged
3694 * @message: describes the data transfers, including completion callback
3695 * Context: any (irqs may be blocked, etc)
3697 * This call may be used in_irq and other contexts which can't sleep,
3698 * as well as from task contexts which can sleep.
3700 * The completion callback is invoked in a context which can't sleep.
3701 * Before that invocation, the value of message->status is undefined.
3702 * When the callback is issued, message->status holds either zero (to
3703 * indicate complete success) or a negative error code. After that
3704 * callback returns, the driver which issued the transfer request may
3705 * deallocate the associated memory; it's no longer in use by any SPI
3706 * core or controller driver code.
3708 * Note that although all messages to a spi_device are handled in
3709 * FIFO order, messages may go to different devices in other orders.
3710 * Some device might be higher priority, or have various "hard" access
3711 * time requirements, for example.
3713 * On detection of any fault during the transfer, processing of
3714 * the entire message is aborted, and the device is deselected.
3715 * Until returning from the associated message completion callback,
3716 * no other spi_message queued to that device will be processed.
3717 * (This rule applies equally to all the synchronous transfer calls,
3718 * which are wrappers around this core asynchronous primitive.)
3720 * Return: zero on success, else a negative error code.
3722 int spi_async(struct spi_device *spi, struct spi_message *message)
3724 struct spi_controller *ctlr = spi->controller;
3726 unsigned long flags;
3728 ret = __spi_validate(spi, message);
3732 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3734 if (ctlr->bus_lock_flag)
3737 ret = __spi_async(spi, message);
3739 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3743 EXPORT_SYMBOL_GPL(spi_async);
3746 * spi_async_locked - version of spi_async with exclusive bus usage
3747 * @spi: device with which data will be exchanged
3748 * @message: describes the data transfers, including completion callback
3749 * Context: any (irqs may be blocked, etc)
3751 * This call may be used in_irq and other contexts which can't sleep,
3752 * as well as from task contexts which can sleep.
3754 * The completion callback is invoked in a context which can't sleep.
3755 * Before that invocation, the value of message->status is undefined.
3756 * When the callback is issued, message->status holds either zero (to
3757 * indicate complete success) or a negative error code. After that
3758 * callback returns, the driver which issued the transfer request may
3759 * deallocate the associated memory; it's no longer in use by any SPI
3760 * core or controller driver code.
3762 * Note that although all messages to a spi_device are handled in
3763 * FIFO order, messages may go to different devices in other orders.
3764 * Some device might be higher priority, or have various "hard" access
3765 * time requirements, for example.
3767 * On detection of any fault during the transfer, processing of
3768 * the entire message is aborted, and the device is deselected.
3769 * Until returning from the associated message completion callback,
3770 * no other spi_message queued to that device will be processed.
3771 * (This rule applies equally to all the synchronous transfer calls,
3772 * which are wrappers around this core asynchronous primitive.)
3774 * Return: zero on success, else a negative error code.
3776 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3778 struct spi_controller *ctlr = spi->controller;
3780 unsigned long flags;
3782 ret = __spi_validate(spi, message);
3786 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3788 ret = __spi_async(spi, message);
3790 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3795 EXPORT_SYMBOL_GPL(spi_async_locked);
3797 /*-------------------------------------------------------------------------*/
3799 /* Utility methods for SPI protocol drivers, layered on
3800 * top of the core. Some other utility methods are defined as
3804 static void spi_complete(void *arg)
3809 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3811 DECLARE_COMPLETION_ONSTACK(done);
3813 struct spi_controller *ctlr = spi->controller;
3814 unsigned long flags;
3816 status = __spi_validate(spi, message);
3820 message->complete = spi_complete;
3821 message->context = &done;
3824 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3825 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3827 /* If we're not using the legacy transfer method then we will
3828 * try to transfer in the calling context so special case.
3829 * This code would be less tricky if we could remove the
3830 * support for driver implemented message queues.
3832 if (ctlr->transfer == spi_queued_transfer) {
3833 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3835 trace_spi_message_submit(message);
3837 status = __spi_queued_transfer(spi, message, false);
3839 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3841 status = spi_async_locked(spi, message);
3845 /* Push out the messages in the calling context if we
3848 if (ctlr->transfer == spi_queued_transfer) {
3849 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3850 spi_sync_immediate);
3851 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3852 spi_sync_immediate);
3853 __spi_pump_messages(ctlr, false);
3856 wait_for_completion(&done);
3857 status = message->status;
3859 message->context = NULL;
3864 * spi_sync - blocking/synchronous SPI data transfers
3865 * @spi: device with which data will be exchanged
3866 * @message: describes the data transfers
3867 * Context: can sleep
3869 * This call may only be used from a context that may sleep. The sleep
3870 * is non-interruptible, and has no timeout. Low-overhead controller
3871 * drivers may DMA directly into and out of the message buffers.
3873 * Note that the SPI device's chip select is active during the message,
3874 * and then is normally disabled between messages. Drivers for some
3875 * frequently-used devices may want to minimize costs of selecting a chip,
3876 * by leaving it selected in anticipation that the next message will go
3877 * to the same chip. (That may increase power usage.)
3879 * Also, the caller is guaranteeing that the memory associated with the
3880 * message will not be freed before this call returns.
3882 * Return: zero on success, else a negative error code.
3884 int spi_sync(struct spi_device *spi, struct spi_message *message)
3888 mutex_lock(&spi->controller->bus_lock_mutex);
3889 ret = __spi_sync(spi, message);
3890 mutex_unlock(&spi->controller->bus_lock_mutex);
3894 EXPORT_SYMBOL_GPL(spi_sync);
3897 * spi_sync_locked - version of spi_sync with exclusive bus usage
3898 * @spi: device with which data will be exchanged
3899 * @message: describes the data transfers
3900 * Context: can sleep
3902 * This call may only be used from a context that may sleep. The sleep
3903 * is non-interruptible, and has no timeout. Low-overhead controller
3904 * drivers may DMA directly into and out of the message buffers.
3906 * This call should be used by drivers that require exclusive access to the
3907 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3908 * be released by a spi_bus_unlock call when the exclusive access is over.
3910 * Return: zero on success, else a negative error code.
3912 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3914 return __spi_sync(spi, message);
3916 EXPORT_SYMBOL_GPL(spi_sync_locked);
3919 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3920 * @ctlr: SPI bus master that should be locked for exclusive bus access
3921 * Context: can sleep
3923 * This call may only be used from a context that may sleep. The sleep
3924 * is non-interruptible, and has no timeout.
3926 * This call should be used by drivers that require exclusive access to the
3927 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3928 * exclusive access is over. Data transfer must be done by spi_sync_locked
3929 * and spi_async_locked calls when the SPI bus lock is held.
3931 * Return: always zero.
3933 int spi_bus_lock(struct spi_controller *ctlr)
3935 unsigned long flags;
3937 mutex_lock(&ctlr->bus_lock_mutex);
3939 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3940 ctlr->bus_lock_flag = 1;
3941 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3943 /* mutex remains locked until spi_bus_unlock is called */
3947 EXPORT_SYMBOL_GPL(spi_bus_lock);
3950 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3951 * @ctlr: SPI bus master that was locked for exclusive bus access
3952 * Context: can sleep
3954 * This call may only be used from a context that may sleep. The sleep
3955 * is non-interruptible, and has no timeout.
3957 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3960 * Return: always zero.
3962 int spi_bus_unlock(struct spi_controller *ctlr)
3964 ctlr->bus_lock_flag = 0;
3966 mutex_unlock(&ctlr->bus_lock_mutex);
3970 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3972 /* portable code must never pass more than 32 bytes */
3973 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
3978 * spi_write_then_read - SPI synchronous write followed by read
3979 * @spi: device with which data will be exchanged
3980 * @txbuf: data to be written (need not be dma-safe)
3981 * @n_tx: size of txbuf, in bytes
3982 * @rxbuf: buffer into which data will be read (need not be dma-safe)
3983 * @n_rx: size of rxbuf, in bytes
3984 * Context: can sleep
3986 * This performs a half duplex MicroWire style transaction with the
3987 * device, sending txbuf and then reading rxbuf. The return value
3988 * is zero for success, else a negative errno status code.
3989 * This call may only be used from a context that may sleep.
3991 * Parameters to this routine are always copied using a small buffer.
3992 * Performance-sensitive or bulk transfer code should instead use
3993 * spi_{async,sync}() calls with dma-safe buffers.
3995 * Return: zero on success, else a negative error code.
3997 int spi_write_then_read(struct spi_device *spi,
3998 const void *txbuf, unsigned n_tx,
3999 void *rxbuf, unsigned n_rx)
4001 static DEFINE_MUTEX(lock);
4004 struct spi_message message;
4005 struct spi_transfer x[2];
4008 /* Use preallocated DMA-safe buffer if we can. We can't avoid
4009 * copying here, (as a pure convenience thing), but we can
4010 * keep heap costs out of the hot path unless someone else is
4011 * using the pre-allocated buffer or the transfer is too large.
4013 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4014 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4015 GFP_KERNEL | GFP_DMA);
4022 spi_message_init(&message);
4023 memset(x, 0, sizeof(x));
4026 spi_message_add_tail(&x[0], &message);
4030 spi_message_add_tail(&x[1], &message);
4033 memcpy(local_buf, txbuf, n_tx);
4034 x[0].tx_buf = local_buf;
4035 x[1].rx_buf = local_buf + n_tx;
4038 status = spi_sync(spi, &message);
4040 memcpy(rxbuf, x[1].rx_buf, n_rx);
4042 if (x[0].tx_buf == buf)
4043 mutex_unlock(&lock);
4049 EXPORT_SYMBOL_GPL(spi_write_then_read);
4051 /*-------------------------------------------------------------------------*/
4053 #if IS_ENABLED(CONFIG_OF)
4054 /* must call put_device() when done with returned spi_device device */
4055 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4057 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4059 return dev ? to_spi_device(dev) : NULL;
4061 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4062 #endif /* IS_ENABLED(CONFIG_OF) */
4064 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4065 /* the spi controllers are not using spi_bus, so we find it with another way */
4066 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4070 dev = class_find_device_by_of_node(&spi_master_class, node);
4071 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4072 dev = class_find_device_by_of_node(&spi_slave_class, node);
4076 /* reference got in class_find_device */
4077 return container_of(dev, struct spi_controller, dev);
4080 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4083 struct of_reconfig_data *rd = arg;
4084 struct spi_controller *ctlr;
4085 struct spi_device *spi;
4087 switch (of_reconfig_get_state_change(action, arg)) {
4088 case OF_RECONFIG_CHANGE_ADD:
4089 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4091 return NOTIFY_OK; /* not for us */
4093 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4094 put_device(&ctlr->dev);
4098 spi = of_register_spi_device(ctlr, rd->dn);
4099 put_device(&ctlr->dev);
4102 pr_err("%s: failed to create for '%pOF'\n",
4104 of_node_clear_flag(rd->dn, OF_POPULATED);
4105 return notifier_from_errno(PTR_ERR(spi));
4109 case OF_RECONFIG_CHANGE_REMOVE:
4110 /* already depopulated? */
4111 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4114 /* find our device by node */
4115 spi = of_find_spi_device_by_node(rd->dn);
4117 return NOTIFY_OK; /* no? not meant for us */
4119 /* unregister takes one ref away */
4120 spi_unregister_device(spi);
4122 /* and put the reference of the find */
4123 put_device(&spi->dev);
4130 static struct notifier_block spi_of_notifier = {
4131 .notifier_call = of_spi_notify,
4133 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4134 extern struct notifier_block spi_of_notifier;
4135 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4137 #if IS_ENABLED(CONFIG_ACPI)
4138 static int spi_acpi_controller_match(struct device *dev, const void *data)
4140 return ACPI_COMPANION(dev->parent) == data;
4143 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4147 dev = class_find_device(&spi_master_class, NULL, adev,
4148 spi_acpi_controller_match);
4149 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4150 dev = class_find_device(&spi_slave_class, NULL, adev,
4151 spi_acpi_controller_match);
4155 return container_of(dev, struct spi_controller, dev);
4158 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4162 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4163 return to_spi_device(dev);
4166 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4169 struct acpi_device *adev = arg;
4170 struct spi_controller *ctlr;
4171 struct spi_device *spi;
4174 case ACPI_RECONFIG_DEVICE_ADD:
4175 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4179 acpi_register_spi_device(ctlr, adev);
4180 put_device(&ctlr->dev);
4182 case ACPI_RECONFIG_DEVICE_REMOVE:
4183 if (!acpi_device_enumerated(adev))
4186 spi = acpi_spi_find_device_by_adev(adev);
4190 spi_unregister_device(spi);
4191 put_device(&spi->dev);
4198 static struct notifier_block spi_acpi_notifier = {
4199 .notifier_call = acpi_spi_notify,
4202 extern struct notifier_block spi_acpi_notifier;
4205 static int __init spi_init(void)
4209 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4215 status = bus_register(&spi_bus_type);
4219 status = class_register(&spi_master_class);
4223 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4224 status = class_register(&spi_slave_class);
4229 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4230 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4231 if (IS_ENABLED(CONFIG_ACPI))
4232 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4237 class_unregister(&spi_master_class);
4239 bus_unregister(&spi_bus_type);
4247 /* board_info is normally registered in arch_initcall(),
4248 * but even essential drivers wait till later
4250 * REVISIT only boardinfo really needs static linking. the rest (device and
4251 * driver registration) _could_ be dynamically linked (modular) ... costs
4252 * include needing to have boardinfo data structures be much more public.
4254 postcore_initcall(spi_init);