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->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
814 !spi->controller->set_cs_timing) {
816 spi_delay_exec(&spi->controller->cs_setup, NULL);
818 spi_delay_exec(&spi->controller->cs_hold, NULL);
821 if (spi->mode & SPI_CS_HIGH)
824 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
825 if (!(spi->mode & SPI_NO_CS)) {
827 /* polarity handled by gpiolib */
828 gpiod_set_value_cansleep(spi->cs_gpiod,
832 * invert the enable line, as active low is
835 gpio_set_value_cansleep(spi->cs_gpio, !enable);
837 /* Some SPI masters need both GPIO CS & slave_select */
838 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
839 spi->controller->set_cs)
840 spi->controller->set_cs(spi, !enable);
841 } else if (spi->controller->set_cs) {
842 spi->controller->set_cs(spi, !enable);
845 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
846 !spi->controller->set_cs_timing) {
848 spi_delay_exec(&spi->controller->cs_inactive, NULL);
852 #ifdef CONFIG_HAS_DMA
853 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
854 struct sg_table *sgt, void *buf, size_t len,
855 enum dma_data_direction dir)
857 const bool vmalloced_buf = is_vmalloc_addr(buf);
858 unsigned int max_seg_size = dma_get_max_seg_size(dev);
859 #ifdef CONFIG_HIGHMEM
860 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
861 (unsigned long)buf < (PKMAP_BASE +
862 (LAST_PKMAP * PAGE_SIZE)));
864 const bool kmap_buf = false;
868 struct page *vm_page;
869 struct scatterlist *sg;
874 if (vmalloced_buf || kmap_buf) {
875 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
876 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
877 } else if (virt_addr_valid(buf)) {
878 desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
879 sgs = DIV_ROUND_UP(len, desc_len);
884 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
889 for (i = 0; i < sgs; i++) {
891 if (vmalloced_buf || kmap_buf) {
893 * Next scatterlist entry size is the minimum between
894 * the desc_len and the remaining buffer length that
897 min = min_t(size_t, desc_len,
899 PAGE_SIZE - offset_in_page(buf)));
901 vm_page = vmalloc_to_page(buf);
903 vm_page = kmap_to_page(buf);
908 sg_set_page(sg, vm_page,
909 min, offset_in_page(buf));
911 min = min_t(size_t, len, desc_len);
913 sg_set_buf(sg, sg_buf, min);
921 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
934 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
935 struct sg_table *sgt, enum dma_data_direction dir)
937 if (sgt->orig_nents) {
938 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
943 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
945 struct device *tx_dev, *rx_dev;
946 struct spi_transfer *xfer;
953 tx_dev = ctlr->dma_tx->device->dev;
955 tx_dev = ctlr->dev.parent;
958 rx_dev = ctlr->dma_rx->device->dev;
960 rx_dev = ctlr->dev.parent;
962 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
963 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
966 if (xfer->tx_buf != NULL) {
967 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
968 (void *)xfer->tx_buf, xfer->len,
974 if (xfer->rx_buf != NULL) {
975 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
976 xfer->rx_buf, xfer->len,
979 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
986 ctlr->cur_msg_mapped = true;
991 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
993 struct spi_transfer *xfer;
994 struct device *tx_dev, *rx_dev;
996 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1000 tx_dev = ctlr->dma_tx->device->dev;
1002 tx_dev = ctlr->dev.parent;
1005 rx_dev = ctlr->dma_rx->device->dev;
1007 rx_dev = ctlr->dev.parent;
1009 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1010 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1013 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1014 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1017 ctlr->cur_msg_mapped = false;
1021 #else /* !CONFIG_HAS_DMA */
1022 static inline int __spi_map_msg(struct spi_controller *ctlr,
1023 struct spi_message *msg)
1028 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1029 struct spi_message *msg)
1033 #endif /* !CONFIG_HAS_DMA */
1035 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1036 struct spi_message *msg)
1038 struct spi_transfer *xfer;
1040 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1042 * Restore the original value of tx_buf or rx_buf if they are
1045 if (xfer->tx_buf == ctlr->dummy_tx)
1046 xfer->tx_buf = NULL;
1047 if (xfer->rx_buf == ctlr->dummy_rx)
1048 xfer->rx_buf = NULL;
1051 return __spi_unmap_msg(ctlr, msg);
1054 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1056 struct spi_transfer *xfer;
1058 unsigned int max_tx, max_rx;
1060 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1061 && !(msg->spi->mode & SPI_3WIRE)) {
1065 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1066 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1068 max_tx = max(xfer->len, max_tx);
1069 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1071 max_rx = max(xfer->len, max_rx);
1075 tmp = krealloc(ctlr->dummy_tx, max_tx,
1076 GFP_KERNEL | GFP_DMA);
1079 ctlr->dummy_tx = tmp;
1080 memset(tmp, 0, max_tx);
1084 tmp = krealloc(ctlr->dummy_rx, max_rx,
1085 GFP_KERNEL | GFP_DMA);
1088 ctlr->dummy_rx = tmp;
1091 if (max_tx || max_rx) {
1092 list_for_each_entry(xfer, &msg->transfers,
1097 xfer->tx_buf = ctlr->dummy_tx;
1099 xfer->rx_buf = ctlr->dummy_rx;
1104 return __spi_map_msg(ctlr, msg);
1107 static int spi_transfer_wait(struct spi_controller *ctlr,
1108 struct spi_message *msg,
1109 struct spi_transfer *xfer)
1111 struct spi_statistics *statm = &ctlr->statistics;
1112 struct spi_statistics *stats = &msg->spi->statistics;
1113 u32 speed_hz = xfer->speed_hz;
1114 unsigned long long ms;
1116 if (spi_controller_is_slave(ctlr)) {
1117 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1118 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1125 ms = 8LL * 1000LL * xfer->len;
1126 do_div(ms, speed_hz);
1127 ms += ms + 200; /* some tolerance */
1132 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1133 msecs_to_jiffies(ms));
1136 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1137 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1138 dev_err(&msg->spi->dev,
1139 "SPI transfer timed out\n");
1147 static void _spi_transfer_delay_ns(u32 ns)
1154 u32 us = DIV_ROUND_UP(ns, 1000);
1159 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1163 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1165 u32 delay = _delay->value;
1166 u32 unit = _delay->unit;
1173 case SPI_DELAY_UNIT_USECS:
1176 case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1178 case SPI_DELAY_UNIT_SCK:
1179 /* clock cycles need to be obtained from spi_transfer */
1182 /* if there is no effective speed know, then approximate
1183 * by underestimating with half the requested hz
1185 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1188 delay *= DIV_ROUND_UP(1000000000, hz);
1196 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1198 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1207 delay = spi_delay_to_ns(_delay, xfer);
1211 _spi_transfer_delay_ns(delay);
1215 EXPORT_SYMBOL_GPL(spi_delay_exec);
1217 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1218 struct spi_transfer *xfer)
1220 u32 delay = xfer->cs_change_delay.value;
1221 u32 unit = xfer->cs_change_delay.unit;
1224 /* return early on "fast" mode - for everything but USECS */
1226 if (unit == SPI_DELAY_UNIT_USECS)
1227 _spi_transfer_delay_ns(10000);
1231 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1233 dev_err_once(&msg->spi->dev,
1234 "Use of unsupported delay unit %i, using default of 10us\n",
1236 _spi_transfer_delay_ns(10000);
1241 * spi_transfer_one_message - Default implementation of transfer_one_message()
1243 * This is a standard implementation of transfer_one_message() for
1244 * drivers which implement a transfer_one() operation. It provides
1245 * standard handling of delays and chip select management.
1247 static int spi_transfer_one_message(struct spi_controller *ctlr,
1248 struct spi_message *msg)
1250 struct spi_transfer *xfer;
1251 bool keep_cs = false;
1253 struct spi_statistics *statm = &ctlr->statistics;
1254 struct spi_statistics *stats = &msg->spi->statistics;
1256 spi_set_cs(msg->spi, true);
1258 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1259 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1261 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1262 trace_spi_transfer_start(msg, xfer);
1264 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1265 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1267 if (!ctlr->ptp_sts_supported) {
1268 xfer->ptp_sts_word_pre = 0;
1269 ptp_read_system_prets(xfer->ptp_sts);
1272 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1273 reinit_completion(&ctlr->xfer_completion);
1276 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1278 if (ctlr->cur_msg_mapped &&
1279 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1280 __spi_unmap_msg(ctlr, msg);
1281 ctlr->fallback = true;
1282 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1286 SPI_STATISTICS_INCREMENT_FIELD(statm,
1288 SPI_STATISTICS_INCREMENT_FIELD(stats,
1290 dev_err(&msg->spi->dev,
1291 "SPI transfer failed: %d\n", ret);
1296 ret = spi_transfer_wait(ctlr, msg, xfer);
1302 dev_err(&msg->spi->dev,
1303 "Bufferless transfer has length %u\n",
1307 if (!ctlr->ptp_sts_supported) {
1308 ptp_read_system_postts(xfer->ptp_sts);
1309 xfer->ptp_sts_word_post = xfer->len;
1312 trace_spi_transfer_stop(msg, xfer);
1314 if (msg->status != -EINPROGRESS)
1317 spi_transfer_delay_exec(xfer);
1319 if (xfer->cs_change) {
1320 if (list_is_last(&xfer->transfer_list,
1324 spi_set_cs(msg->spi, false);
1325 _spi_transfer_cs_change_delay(msg, xfer);
1326 spi_set_cs(msg->spi, true);
1330 msg->actual_length += xfer->len;
1334 if (ret != 0 || !keep_cs)
1335 spi_set_cs(msg->spi, false);
1337 if (msg->status == -EINPROGRESS)
1340 if (msg->status && ctlr->handle_err)
1341 ctlr->handle_err(ctlr, msg);
1343 spi_finalize_current_message(ctlr);
1349 * spi_finalize_current_transfer - report completion of a transfer
1350 * @ctlr: the controller reporting completion
1352 * Called by SPI drivers using the core transfer_one_message()
1353 * implementation to notify it that the current interrupt driven
1354 * transfer has finished and the next one may be scheduled.
1356 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1358 complete(&ctlr->xfer_completion);
1360 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1362 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1364 if (ctlr->auto_runtime_pm) {
1365 pm_runtime_mark_last_busy(ctlr->dev.parent);
1366 pm_runtime_put_autosuspend(ctlr->dev.parent);
1371 * __spi_pump_messages - function which processes spi message queue
1372 * @ctlr: controller to process queue for
1373 * @in_kthread: true if we are in the context of the message pump thread
1375 * This function checks if there is any spi message in the queue that
1376 * needs processing and if so call out to the driver to initialize hardware
1377 * and transfer each message.
1379 * Note that it is called both from the kthread itself and also from
1380 * inside spi_sync(); the queue extraction handling at the top of the
1381 * function should deal with this safely.
1383 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1385 struct spi_transfer *xfer;
1386 struct spi_message *msg;
1387 bool was_busy = false;
1388 unsigned long flags;
1392 spin_lock_irqsave(&ctlr->queue_lock, flags);
1394 /* Make sure we are not already running a message */
1395 if (ctlr->cur_msg) {
1396 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1400 /* If another context is idling the device then defer */
1402 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1403 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1407 /* Check if the queue is idle */
1408 if (list_empty(&ctlr->queue) || !ctlr->running) {
1410 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1414 /* Defer any non-atomic teardown to the thread */
1416 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1417 !ctlr->unprepare_transfer_hardware) {
1418 spi_idle_runtime_pm(ctlr);
1420 trace_spi_controller_idle(ctlr);
1422 kthread_queue_work(ctlr->kworker,
1423 &ctlr->pump_messages);
1425 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1430 ctlr->idling = true;
1431 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1433 kfree(ctlr->dummy_rx);
1434 ctlr->dummy_rx = NULL;
1435 kfree(ctlr->dummy_tx);
1436 ctlr->dummy_tx = NULL;
1437 if (ctlr->unprepare_transfer_hardware &&
1438 ctlr->unprepare_transfer_hardware(ctlr))
1440 "failed to unprepare transfer hardware\n");
1441 spi_idle_runtime_pm(ctlr);
1442 trace_spi_controller_idle(ctlr);
1444 spin_lock_irqsave(&ctlr->queue_lock, flags);
1445 ctlr->idling = false;
1446 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1450 /* Extract head of queue */
1451 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1452 ctlr->cur_msg = msg;
1454 list_del_init(&msg->queue);
1459 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1461 mutex_lock(&ctlr->io_mutex);
1463 if (!was_busy && ctlr->auto_runtime_pm) {
1464 ret = pm_runtime_get_sync(ctlr->dev.parent);
1466 pm_runtime_put_noidle(ctlr->dev.parent);
1467 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1469 mutex_unlock(&ctlr->io_mutex);
1475 trace_spi_controller_busy(ctlr);
1477 if (!was_busy && ctlr->prepare_transfer_hardware) {
1478 ret = ctlr->prepare_transfer_hardware(ctlr);
1481 "failed to prepare transfer hardware: %d\n",
1484 if (ctlr->auto_runtime_pm)
1485 pm_runtime_put(ctlr->dev.parent);
1488 spi_finalize_current_message(ctlr);
1490 mutex_unlock(&ctlr->io_mutex);
1495 trace_spi_message_start(msg);
1497 if (ctlr->prepare_message) {
1498 ret = ctlr->prepare_message(ctlr, msg);
1500 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1503 spi_finalize_current_message(ctlr);
1506 ctlr->cur_msg_prepared = true;
1509 ret = spi_map_msg(ctlr, msg);
1512 spi_finalize_current_message(ctlr);
1516 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1517 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1518 xfer->ptp_sts_word_pre = 0;
1519 ptp_read_system_prets(xfer->ptp_sts);
1523 ret = ctlr->transfer_one_message(ctlr, msg);
1526 "failed to transfer one message from queue\n");
1531 mutex_unlock(&ctlr->io_mutex);
1533 /* Prod the scheduler in case transfer_one() was busy waiting */
1539 * spi_pump_messages - kthread work function which processes spi message queue
1540 * @work: pointer to kthread work struct contained in the controller struct
1542 static void spi_pump_messages(struct kthread_work *work)
1544 struct spi_controller *ctlr =
1545 container_of(work, struct spi_controller, pump_messages);
1547 __spi_pump_messages(ctlr, true);
1551 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1552 * TX timestamp for the requested byte from the SPI
1553 * transfer. The frequency with which this function
1554 * must be called (once per word, once for the whole
1555 * transfer, once per batch of words etc) is arbitrary
1556 * as long as the @tx buffer offset is greater than or
1557 * equal to the requested byte at the time of the
1558 * call. The timestamp is only taken once, at the
1559 * first such call. It is assumed that the driver
1560 * advances its @tx buffer pointer monotonically.
1561 * @ctlr: Pointer to the spi_controller structure of the driver
1562 * @xfer: Pointer to the transfer being timestamped
1563 * @progress: How many words (not bytes) have been transferred so far
1564 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1565 * transfer, for less jitter in time measurement. Only compatible
1566 * with PIO drivers. If true, must follow up with
1567 * spi_take_timestamp_post or otherwise system will crash.
1568 * WARNING: for fully predictable results, the CPU frequency must
1569 * also be under control (governor).
1571 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1572 struct spi_transfer *xfer,
1573 size_t progress, bool irqs_off)
1578 if (xfer->timestamped)
1581 if (progress > xfer->ptp_sts_word_pre)
1584 /* Capture the resolution of the timestamp */
1585 xfer->ptp_sts_word_pre = progress;
1588 local_irq_save(ctlr->irq_flags);
1592 ptp_read_system_prets(xfer->ptp_sts);
1594 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1597 * spi_take_timestamp_post - helper for drivers to collect the end of the
1598 * TX timestamp for the requested byte from the SPI
1599 * transfer. Can be called with an arbitrary
1600 * frequency: only the first call where @tx exceeds
1601 * or is equal to the requested word will be
1603 * @ctlr: Pointer to the spi_controller structure of the driver
1604 * @xfer: Pointer to the transfer being timestamped
1605 * @progress: How many words (not bytes) have been transferred so far
1606 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1608 void spi_take_timestamp_post(struct spi_controller *ctlr,
1609 struct spi_transfer *xfer,
1610 size_t progress, bool irqs_off)
1615 if (xfer->timestamped)
1618 if (progress < xfer->ptp_sts_word_post)
1621 ptp_read_system_postts(xfer->ptp_sts);
1624 local_irq_restore(ctlr->irq_flags);
1628 /* Capture the resolution of the timestamp */
1629 xfer->ptp_sts_word_post = progress;
1631 xfer->timestamped = true;
1633 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1636 * spi_set_thread_rt - set the controller to pump at realtime priority
1637 * @ctlr: controller to boost priority of
1639 * This can be called because the controller requested realtime priority
1640 * (by setting the ->rt value before calling spi_register_controller()) or
1641 * because a device on the bus said that its transfers needed realtime
1644 * NOTE: at the moment if any device on a bus says it needs realtime then
1645 * the thread will be at realtime priority for all transfers on that
1646 * controller. If this eventually becomes a problem we may see if we can
1647 * find a way to boost the priority only temporarily during relevant
1650 static void spi_set_thread_rt(struct spi_controller *ctlr)
1652 dev_info(&ctlr->dev,
1653 "will run message pump with realtime priority\n");
1654 sched_set_fifo(ctlr->kworker->task);
1657 static int spi_init_queue(struct spi_controller *ctlr)
1659 ctlr->running = false;
1662 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1663 if (IS_ERR(ctlr->kworker)) {
1664 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1665 return PTR_ERR(ctlr->kworker);
1668 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1671 * Controller config will indicate if this controller should run the
1672 * message pump with high (realtime) priority to reduce the transfer
1673 * latency on the bus by minimising the delay between a transfer
1674 * request and the scheduling of the message pump thread. Without this
1675 * setting the message pump thread will remain at default priority.
1678 spi_set_thread_rt(ctlr);
1684 * spi_get_next_queued_message() - called by driver to check for queued
1686 * @ctlr: the controller to check for queued messages
1688 * If there are more messages in the queue, the next message is returned from
1691 * Return: the next message in the queue, else NULL if the queue is empty.
1693 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1695 struct spi_message *next;
1696 unsigned long flags;
1698 /* get a pointer to the next message, if any */
1699 spin_lock_irqsave(&ctlr->queue_lock, flags);
1700 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1702 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1706 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1709 * spi_finalize_current_message() - the current message is complete
1710 * @ctlr: the controller to return the message to
1712 * Called by the driver to notify the core that the message in the front of the
1713 * queue is complete and can be removed from the queue.
1715 void spi_finalize_current_message(struct spi_controller *ctlr)
1717 struct spi_transfer *xfer;
1718 struct spi_message *mesg;
1719 unsigned long flags;
1722 spin_lock_irqsave(&ctlr->queue_lock, flags);
1723 mesg = ctlr->cur_msg;
1724 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1726 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1727 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1728 ptp_read_system_postts(xfer->ptp_sts);
1729 xfer->ptp_sts_word_post = xfer->len;
1733 if (unlikely(ctlr->ptp_sts_supported))
1734 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1735 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1737 spi_unmap_msg(ctlr, mesg);
1739 /* In the prepare_messages callback the spi bus has the opportunity to
1740 * split a transfer to smaller chunks.
1741 * Release splited transfers here since spi_map_msg is done on the
1742 * splited transfers.
1744 spi_res_release(ctlr, mesg);
1746 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1747 ret = ctlr->unprepare_message(ctlr, mesg);
1749 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1754 spin_lock_irqsave(&ctlr->queue_lock, flags);
1755 ctlr->cur_msg = NULL;
1756 ctlr->cur_msg_prepared = false;
1757 ctlr->fallback = false;
1758 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1759 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1761 trace_spi_message_done(mesg);
1765 mesg->complete(mesg->context);
1767 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1769 static int spi_start_queue(struct spi_controller *ctlr)
1771 unsigned long flags;
1773 spin_lock_irqsave(&ctlr->queue_lock, flags);
1775 if (ctlr->running || ctlr->busy) {
1776 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1780 ctlr->running = true;
1781 ctlr->cur_msg = NULL;
1782 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1784 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1789 static int spi_stop_queue(struct spi_controller *ctlr)
1791 unsigned long flags;
1792 unsigned limit = 500;
1795 spin_lock_irqsave(&ctlr->queue_lock, flags);
1798 * This is a bit lame, but is optimized for the common execution path.
1799 * A wait_queue on the ctlr->busy could be used, but then the common
1800 * execution path (pump_messages) would be required to call wake_up or
1801 * friends on every SPI message. Do this instead.
1803 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1804 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1805 usleep_range(10000, 11000);
1806 spin_lock_irqsave(&ctlr->queue_lock, flags);
1809 if (!list_empty(&ctlr->queue) || ctlr->busy)
1812 ctlr->running = false;
1814 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1817 dev_warn(&ctlr->dev, "could not stop message queue\n");
1823 static int spi_destroy_queue(struct spi_controller *ctlr)
1827 ret = spi_stop_queue(ctlr);
1830 * kthread_flush_worker will block until all work is done.
1831 * If the reason that stop_queue timed out is that the work will never
1832 * finish, then it does no good to call flush/stop thread, so
1836 dev_err(&ctlr->dev, "problem destroying queue\n");
1840 kthread_destroy_worker(ctlr->kworker);
1845 static int __spi_queued_transfer(struct spi_device *spi,
1846 struct spi_message *msg,
1849 struct spi_controller *ctlr = spi->controller;
1850 unsigned long flags;
1852 spin_lock_irqsave(&ctlr->queue_lock, flags);
1854 if (!ctlr->running) {
1855 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1858 msg->actual_length = 0;
1859 msg->status = -EINPROGRESS;
1861 list_add_tail(&msg->queue, &ctlr->queue);
1862 if (!ctlr->busy && need_pump)
1863 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1865 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1870 * spi_queued_transfer - transfer function for queued transfers
1871 * @spi: spi device which is requesting transfer
1872 * @msg: spi message which is to handled is queued to driver queue
1874 * Return: zero on success, else a negative error code.
1876 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1878 return __spi_queued_transfer(spi, msg, true);
1881 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1885 ctlr->transfer = spi_queued_transfer;
1886 if (!ctlr->transfer_one_message)
1887 ctlr->transfer_one_message = spi_transfer_one_message;
1889 /* Initialize and start queue */
1890 ret = spi_init_queue(ctlr);
1892 dev_err(&ctlr->dev, "problem initializing queue\n");
1893 goto err_init_queue;
1895 ctlr->queued = true;
1896 ret = spi_start_queue(ctlr);
1898 dev_err(&ctlr->dev, "problem starting queue\n");
1899 goto err_start_queue;
1905 spi_destroy_queue(ctlr);
1911 * spi_flush_queue - Send all pending messages in the queue from the callers'
1913 * @ctlr: controller to process queue for
1915 * This should be used when one wants to ensure all pending messages have been
1916 * sent before doing something. Is used by the spi-mem code to make sure SPI
1917 * memory operations do not preempt regular SPI transfers that have been queued
1918 * before the spi-mem operation.
1920 void spi_flush_queue(struct spi_controller *ctlr)
1922 if (ctlr->transfer == spi_queued_transfer)
1923 __spi_pump_messages(ctlr, false);
1926 /*-------------------------------------------------------------------------*/
1928 #if defined(CONFIG_OF)
1929 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1930 struct device_node *nc)
1935 /* Mode (clock phase/polarity/etc.) */
1936 if (of_property_read_bool(nc, "spi-cpha"))
1937 spi->mode |= SPI_CPHA;
1938 if (of_property_read_bool(nc, "spi-cpol"))
1939 spi->mode |= SPI_CPOL;
1940 if (of_property_read_bool(nc, "spi-3wire"))
1941 spi->mode |= SPI_3WIRE;
1942 if (of_property_read_bool(nc, "spi-lsb-first"))
1943 spi->mode |= SPI_LSB_FIRST;
1944 if (of_property_read_bool(nc, "spi-cs-high"))
1945 spi->mode |= SPI_CS_HIGH;
1947 /* Device DUAL/QUAD mode */
1948 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1951 spi->mode |= SPI_NO_TX;
1956 spi->mode |= SPI_TX_DUAL;
1959 spi->mode |= SPI_TX_QUAD;
1962 spi->mode |= SPI_TX_OCTAL;
1965 dev_warn(&ctlr->dev,
1966 "spi-tx-bus-width %d not supported\n",
1972 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1975 spi->mode |= SPI_NO_RX;
1980 spi->mode |= SPI_RX_DUAL;
1983 spi->mode |= SPI_RX_QUAD;
1986 spi->mode |= SPI_RX_OCTAL;
1989 dev_warn(&ctlr->dev,
1990 "spi-rx-bus-width %d not supported\n",
1996 if (spi_controller_is_slave(ctlr)) {
1997 if (!of_node_name_eq(nc, "slave")) {
1998 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2005 /* Device address */
2006 rc = of_property_read_u32(nc, "reg", &value);
2008 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2012 spi->chip_select = value;
2015 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2016 spi->max_speed_hz = value;
2021 static struct spi_device *
2022 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2024 struct spi_device *spi;
2027 /* Alloc an spi_device */
2028 spi = spi_alloc_device(ctlr);
2030 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2035 /* Select device driver */
2036 rc = of_modalias_node(nc, spi->modalias,
2037 sizeof(spi->modalias));
2039 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2043 rc = of_spi_parse_dt(ctlr, spi, nc);
2047 /* Store a pointer to the node in the device structure */
2049 spi->dev.of_node = nc;
2051 /* Register the new device */
2052 rc = spi_add_device(spi);
2054 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2055 goto err_of_node_put;
2068 * of_register_spi_devices() - Register child devices onto the SPI bus
2069 * @ctlr: Pointer to spi_controller device
2071 * Registers an spi_device for each child node of controller node which
2072 * represents a valid SPI slave.
2074 static void of_register_spi_devices(struct spi_controller *ctlr)
2076 struct spi_device *spi;
2077 struct device_node *nc;
2079 if (!ctlr->dev.of_node)
2082 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2083 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2085 spi = of_register_spi_device(ctlr, nc);
2087 dev_warn(&ctlr->dev,
2088 "Failed to create SPI device for %pOF\n", nc);
2089 of_node_clear_flag(nc, OF_POPULATED);
2094 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2098 struct acpi_spi_lookup {
2099 struct spi_controller *ctlr;
2107 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2108 struct acpi_spi_lookup *lookup)
2110 const union acpi_object *obj;
2112 if (!x86_apple_machine)
2115 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2116 && obj->buffer.length >= 4)
2117 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2119 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2120 && obj->buffer.length == 8)
2121 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2123 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2124 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2125 lookup->mode |= SPI_LSB_FIRST;
2127 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2128 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2129 lookup->mode |= SPI_CPOL;
2131 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2132 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2133 lookup->mode |= SPI_CPHA;
2136 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2138 struct acpi_spi_lookup *lookup = data;
2139 struct spi_controller *ctlr = lookup->ctlr;
2141 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2142 struct acpi_resource_spi_serialbus *sb;
2143 acpi_handle parent_handle;
2146 sb = &ares->data.spi_serial_bus;
2147 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2149 status = acpi_get_handle(NULL,
2150 sb->resource_source.string_ptr,
2153 if (ACPI_FAILURE(status) ||
2154 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2158 * ACPI DeviceSelection numbering is handled by the
2159 * host controller driver in Windows and can vary
2160 * from driver to driver. In Linux we always expect
2161 * 0 .. max - 1 so we need to ask the driver to
2162 * translate between the two schemes.
2164 if (ctlr->fw_translate_cs) {
2165 int cs = ctlr->fw_translate_cs(ctlr,
2166 sb->device_selection);
2169 lookup->chip_select = cs;
2171 lookup->chip_select = sb->device_selection;
2174 lookup->max_speed_hz = sb->connection_speed;
2175 lookup->bits_per_word = sb->data_bit_length;
2177 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2178 lookup->mode |= SPI_CPHA;
2179 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2180 lookup->mode |= SPI_CPOL;
2181 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2182 lookup->mode |= SPI_CS_HIGH;
2184 } else if (lookup->irq < 0) {
2187 if (acpi_dev_resource_interrupt(ares, 0, &r))
2188 lookup->irq = r.start;
2191 /* Always tell the ACPI core to skip this resource */
2195 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2196 struct acpi_device *adev)
2198 acpi_handle parent_handle = NULL;
2199 struct list_head resource_list;
2200 struct acpi_spi_lookup lookup = {};
2201 struct spi_device *spi;
2204 if (acpi_bus_get_status(adev) || !adev->status.present ||
2205 acpi_device_enumerated(adev))
2211 INIT_LIST_HEAD(&resource_list);
2212 ret = acpi_dev_get_resources(adev, &resource_list,
2213 acpi_spi_add_resource, &lookup);
2214 acpi_dev_free_resource_list(&resource_list);
2217 /* found SPI in _CRS but it points to another controller */
2220 if (!lookup.max_speed_hz &&
2221 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2222 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2223 /* Apple does not use _CRS but nested devices for SPI slaves */
2224 acpi_spi_parse_apple_properties(adev, &lookup);
2227 if (!lookup.max_speed_hz)
2230 spi = spi_alloc_device(ctlr);
2232 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2233 dev_name(&adev->dev));
2234 return AE_NO_MEMORY;
2238 ACPI_COMPANION_SET(&spi->dev, adev);
2239 spi->max_speed_hz = lookup.max_speed_hz;
2240 spi->mode |= lookup.mode;
2241 spi->irq = lookup.irq;
2242 spi->bits_per_word = lookup.bits_per_word;
2243 spi->chip_select = lookup.chip_select;
2245 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2246 sizeof(spi->modalias));
2249 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2251 acpi_device_set_enumerated(adev);
2253 adev->power.flags.ignore_parent = true;
2254 if (spi_add_device(spi)) {
2255 adev->power.flags.ignore_parent = false;
2256 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2257 dev_name(&adev->dev));
2264 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2265 void *data, void **return_value)
2267 struct spi_controller *ctlr = data;
2268 struct acpi_device *adev;
2270 if (acpi_bus_get_device(handle, &adev))
2273 return acpi_register_spi_device(ctlr, adev);
2276 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2278 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2283 handle = ACPI_HANDLE(ctlr->dev.parent);
2287 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2288 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2289 acpi_spi_add_device, NULL, ctlr, NULL);
2290 if (ACPI_FAILURE(status))
2291 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2294 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2295 #endif /* CONFIG_ACPI */
2297 static void spi_controller_release(struct device *dev)
2299 struct spi_controller *ctlr;
2301 ctlr = container_of(dev, struct spi_controller, dev);
2305 static struct class spi_master_class = {
2306 .name = "spi_master",
2307 .owner = THIS_MODULE,
2308 .dev_release = spi_controller_release,
2309 .dev_groups = spi_master_groups,
2312 #ifdef CONFIG_SPI_SLAVE
2314 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2316 * @spi: device used for the current transfer
2318 int spi_slave_abort(struct spi_device *spi)
2320 struct spi_controller *ctlr = spi->controller;
2322 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2323 return ctlr->slave_abort(ctlr);
2327 EXPORT_SYMBOL_GPL(spi_slave_abort);
2329 static int match_true(struct device *dev, void *data)
2334 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2337 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2339 struct device *child;
2341 child = device_find_child(&ctlr->dev, NULL, match_true);
2342 return sprintf(buf, "%s\n",
2343 child ? to_spi_device(child)->modalias : NULL);
2346 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2347 const char *buf, size_t count)
2349 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2351 struct spi_device *spi;
2352 struct device *child;
2356 rc = sscanf(buf, "%31s", name);
2357 if (rc != 1 || !name[0])
2360 child = device_find_child(&ctlr->dev, NULL, match_true);
2362 /* Remove registered slave */
2363 device_unregister(child);
2367 if (strcmp(name, "(null)")) {
2368 /* Register new slave */
2369 spi = spi_alloc_device(ctlr);
2373 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2375 rc = spi_add_device(spi);
2385 static DEVICE_ATTR_RW(slave);
2387 static struct attribute *spi_slave_attrs[] = {
2388 &dev_attr_slave.attr,
2392 static const struct attribute_group spi_slave_group = {
2393 .attrs = spi_slave_attrs,
2396 static const struct attribute_group *spi_slave_groups[] = {
2397 &spi_controller_statistics_group,
2402 static struct class spi_slave_class = {
2403 .name = "spi_slave",
2404 .owner = THIS_MODULE,
2405 .dev_release = spi_controller_release,
2406 .dev_groups = spi_slave_groups,
2409 extern struct class spi_slave_class; /* dummy */
2413 * __spi_alloc_controller - allocate an SPI master or slave controller
2414 * @dev: the controller, possibly using the platform_bus
2415 * @size: how much zeroed driver-private data to allocate; the pointer to this
2416 * memory is in the driver_data field of the returned device, accessible
2417 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2418 * drivers granting DMA access to portions of their private data need to
2419 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2420 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2421 * slave (true) controller
2422 * Context: can sleep
2424 * This call is used only by SPI controller drivers, which are the
2425 * only ones directly touching chip registers. It's how they allocate
2426 * an spi_controller structure, prior to calling spi_register_controller().
2428 * This must be called from context that can sleep.
2430 * The caller is responsible for assigning the bus number and initializing the
2431 * controller's methods before calling spi_register_controller(); and (after
2432 * errors adding the device) calling spi_controller_put() to prevent a memory
2435 * Return: the SPI controller structure on success, else NULL.
2437 struct spi_controller *__spi_alloc_controller(struct device *dev,
2438 unsigned int size, bool slave)
2440 struct spi_controller *ctlr;
2441 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2446 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2450 device_initialize(&ctlr->dev);
2452 ctlr->num_chipselect = 1;
2453 ctlr->slave = slave;
2454 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2455 ctlr->dev.class = &spi_slave_class;
2457 ctlr->dev.class = &spi_master_class;
2458 ctlr->dev.parent = dev;
2459 pm_suspend_ignore_children(&ctlr->dev, true);
2460 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2464 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2466 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2468 spi_controller_put(*(struct spi_controller **)ctlr);
2472 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2473 * @dev: physical device of SPI controller
2474 * @size: how much zeroed driver-private data to allocate
2475 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2476 * Context: can sleep
2478 * Allocate an SPI controller and automatically release a reference on it
2479 * when @dev is unbound from its driver. Drivers are thus relieved from
2480 * having to call spi_controller_put().
2482 * The arguments to this function are identical to __spi_alloc_controller().
2484 * Return: the SPI controller structure on success, else NULL.
2486 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2490 struct spi_controller **ptr, *ctlr;
2492 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2497 ctlr = __spi_alloc_controller(dev, size, slave);
2500 devres_add(dev, ptr);
2507 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2510 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2513 struct device_node *np = ctlr->dev.of_node;
2518 nb = of_gpio_named_count(np, "cs-gpios");
2519 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2521 /* Return error only for an incorrectly formed cs-gpios property */
2522 if (nb == 0 || nb == -ENOENT)
2527 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2529 ctlr->cs_gpios = cs;
2531 if (!ctlr->cs_gpios)
2534 for (i = 0; i < ctlr->num_chipselect; i++)
2537 for (i = 0; i < nb; i++)
2538 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2543 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2550 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2551 * @ctlr: The SPI master to grab GPIO descriptors for
2553 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2556 struct gpio_desc **cs;
2557 struct device *dev = &ctlr->dev;
2558 unsigned long native_cs_mask = 0;
2559 unsigned int num_cs_gpios = 0;
2561 nb = gpiod_count(dev, "cs");
2562 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2564 /* No GPIOs at all is fine, else return the error */
2565 if (nb == 0 || nb == -ENOENT)
2570 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2574 ctlr->cs_gpiods = cs;
2576 for (i = 0; i < nb; i++) {
2578 * Most chipselects are active low, the inverted
2579 * semantics are handled by special quirks in gpiolib,
2580 * so initializing them GPIOD_OUT_LOW here means
2581 * "unasserted", in most cases this will drive the physical
2584 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2587 return PTR_ERR(cs[i]);
2591 * If we find a CS GPIO, name it after the device and
2596 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2600 gpiod_set_consumer_name(cs[i], gpioname);
2605 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2606 dev_err(dev, "Invalid native chip select %d\n", i);
2609 native_cs_mask |= BIT(i);
2612 ctlr->unused_native_cs = ffz(native_cs_mask);
2613 if (num_cs_gpios && ctlr->max_native_cs &&
2614 ctlr->unused_native_cs >= ctlr->max_native_cs) {
2615 dev_err(dev, "No unused native chip select available\n");
2622 static int spi_controller_check_ops(struct spi_controller *ctlr)
2625 * The controller may implement only the high-level SPI-memory like
2626 * operations if it does not support regular SPI transfers, and this is
2628 * If ->mem_ops is NULL, we request that at least one of the
2629 * ->transfer_xxx() method be implemented.
2631 if (ctlr->mem_ops) {
2632 if (!ctlr->mem_ops->exec_op)
2634 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2635 !ctlr->transfer_one_message) {
2643 * spi_register_controller - register SPI master or slave controller
2644 * @ctlr: initialized master, originally from spi_alloc_master() or
2646 * Context: can sleep
2648 * SPI controllers connect to their drivers using some non-SPI bus,
2649 * such as the platform bus. The final stage of probe() in that code
2650 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2652 * SPI controllers use board specific (often SOC specific) bus numbers,
2653 * and board-specific addressing for SPI devices combines those numbers
2654 * with chip select numbers. Since SPI does not directly support dynamic
2655 * device identification, boards need configuration tables telling which
2656 * chip is at which address.
2658 * This must be called from context that can sleep. It returns zero on
2659 * success, else a negative error code (dropping the controller's refcount).
2660 * After a successful return, the caller is responsible for calling
2661 * spi_unregister_controller().
2663 * Return: zero on success, else a negative error code.
2665 int spi_register_controller(struct spi_controller *ctlr)
2667 struct device *dev = ctlr->dev.parent;
2668 struct boardinfo *bi;
2670 int id, first_dynamic;
2676 * Make sure all necessary hooks are implemented before registering
2677 * the SPI controller.
2679 status = spi_controller_check_ops(ctlr);
2683 if (ctlr->bus_num >= 0) {
2684 /* devices with a fixed bus num must check-in with the num */
2685 mutex_lock(&board_lock);
2686 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2687 ctlr->bus_num + 1, GFP_KERNEL);
2688 mutex_unlock(&board_lock);
2689 if (WARN(id < 0, "couldn't get idr"))
2690 return id == -ENOSPC ? -EBUSY : id;
2692 } else if (ctlr->dev.of_node) {
2693 /* allocate dynamic bus number using Linux idr */
2694 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2697 mutex_lock(&board_lock);
2698 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2699 ctlr->bus_num + 1, GFP_KERNEL);
2700 mutex_unlock(&board_lock);
2701 if (WARN(id < 0, "couldn't get idr"))
2702 return id == -ENOSPC ? -EBUSY : id;
2705 if (ctlr->bus_num < 0) {
2706 first_dynamic = of_alias_get_highest_id("spi");
2707 if (first_dynamic < 0)
2712 mutex_lock(&board_lock);
2713 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2715 mutex_unlock(&board_lock);
2716 if (WARN(id < 0, "couldn't get idr"))
2720 INIT_LIST_HEAD(&ctlr->queue);
2721 spin_lock_init(&ctlr->queue_lock);
2722 spin_lock_init(&ctlr->bus_lock_spinlock);
2723 mutex_init(&ctlr->bus_lock_mutex);
2724 mutex_init(&ctlr->io_mutex);
2725 ctlr->bus_lock_flag = 0;
2726 init_completion(&ctlr->xfer_completion);
2727 if (!ctlr->max_dma_len)
2728 ctlr->max_dma_len = INT_MAX;
2730 /* register the device, then userspace will see it.
2731 * registration fails if the bus ID is in use.
2733 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2735 if (!spi_controller_is_slave(ctlr)) {
2736 if (ctlr->use_gpio_descriptors) {
2737 status = spi_get_gpio_descs(ctlr);
2741 * A controller using GPIO descriptors always
2742 * supports SPI_CS_HIGH if need be.
2744 ctlr->mode_bits |= SPI_CS_HIGH;
2746 /* Legacy code path for GPIOs from DT */
2747 status = of_spi_get_gpio_numbers(ctlr);
2754 * Even if it's just one always-selected device, there must
2755 * be at least one chipselect.
2757 if (!ctlr->num_chipselect) {
2762 status = device_add(&ctlr->dev);
2765 dev_dbg(dev, "registered %s %s\n",
2766 spi_controller_is_slave(ctlr) ? "slave" : "master",
2767 dev_name(&ctlr->dev));
2770 * If we're using a queued driver, start the queue. Note that we don't
2771 * need the queueing logic if the driver is only supporting high-level
2772 * memory operations.
2774 if (ctlr->transfer) {
2775 dev_info(dev, "controller is unqueued, this is deprecated\n");
2776 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2777 status = spi_controller_initialize_queue(ctlr);
2779 device_del(&ctlr->dev);
2783 /* add statistics */
2784 spin_lock_init(&ctlr->statistics.lock);
2786 mutex_lock(&board_lock);
2787 list_add_tail(&ctlr->list, &spi_controller_list);
2788 list_for_each_entry(bi, &board_list, list)
2789 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2790 mutex_unlock(&board_lock);
2792 /* Register devices from the device tree and ACPI */
2793 of_register_spi_devices(ctlr);
2794 acpi_register_spi_devices(ctlr);
2798 mutex_lock(&board_lock);
2799 idr_remove(&spi_master_idr, ctlr->bus_num);
2800 mutex_unlock(&board_lock);
2803 EXPORT_SYMBOL_GPL(spi_register_controller);
2805 static void devm_spi_unregister(struct device *dev, void *res)
2807 spi_unregister_controller(*(struct spi_controller **)res);
2811 * devm_spi_register_controller - register managed SPI master or slave
2813 * @dev: device managing SPI controller
2814 * @ctlr: initialized controller, originally from spi_alloc_master() or
2816 * Context: can sleep
2818 * Register a SPI device as with spi_register_controller() which will
2819 * automatically be unregistered and freed.
2821 * Return: zero on success, else a negative error code.
2823 int devm_spi_register_controller(struct device *dev,
2824 struct spi_controller *ctlr)
2826 struct spi_controller **ptr;
2829 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2833 ret = spi_register_controller(ctlr);
2836 devres_add(dev, ptr);
2843 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2845 static int devm_spi_match_controller(struct device *dev, void *res, void *ctlr)
2847 return *(struct spi_controller **)res == ctlr;
2850 static int __unregister(struct device *dev, void *null)
2852 spi_unregister_device(to_spi_device(dev));
2857 * spi_unregister_controller - unregister SPI master or slave controller
2858 * @ctlr: the controller being unregistered
2859 * Context: can sleep
2861 * This call is used only by SPI controller drivers, which are the
2862 * only ones directly touching chip registers.
2864 * This must be called from context that can sleep.
2866 * Note that this function also drops a reference to the controller.
2868 void spi_unregister_controller(struct spi_controller *ctlr)
2870 struct spi_controller *found;
2871 int id = ctlr->bus_num;
2873 /* Prevent addition of new devices, unregister existing ones */
2874 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2875 mutex_lock(&spi_add_lock);
2877 device_for_each_child(&ctlr->dev, NULL, __unregister);
2879 /* First make sure that this controller was ever added */
2880 mutex_lock(&board_lock);
2881 found = idr_find(&spi_master_idr, id);
2882 mutex_unlock(&board_lock);
2884 if (spi_destroy_queue(ctlr))
2885 dev_err(&ctlr->dev, "queue remove failed\n");
2887 mutex_lock(&board_lock);
2888 list_del(&ctlr->list);
2889 mutex_unlock(&board_lock);
2891 device_del(&ctlr->dev);
2893 /* Release the last reference on the controller if its driver
2894 * has not yet been converted to devm_spi_alloc_master/slave().
2896 if (!devres_find(ctlr->dev.parent, devm_spi_release_controller,
2897 devm_spi_match_controller, ctlr))
2898 put_device(&ctlr->dev);
2901 mutex_lock(&board_lock);
2903 idr_remove(&spi_master_idr, id);
2904 mutex_unlock(&board_lock);
2906 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2907 mutex_unlock(&spi_add_lock);
2909 EXPORT_SYMBOL_GPL(spi_unregister_controller);
2911 int spi_controller_suspend(struct spi_controller *ctlr)
2915 /* Basically no-ops for non-queued controllers */
2919 ret = spi_stop_queue(ctlr);
2921 dev_err(&ctlr->dev, "queue stop failed\n");
2925 EXPORT_SYMBOL_GPL(spi_controller_suspend);
2927 int spi_controller_resume(struct spi_controller *ctlr)
2934 ret = spi_start_queue(ctlr);
2936 dev_err(&ctlr->dev, "queue restart failed\n");
2940 EXPORT_SYMBOL_GPL(spi_controller_resume);
2942 static int __spi_controller_match(struct device *dev, const void *data)
2944 struct spi_controller *ctlr;
2945 const u16 *bus_num = data;
2947 ctlr = container_of(dev, struct spi_controller, dev);
2948 return ctlr->bus_num == *bus_num;
2952 * spi_busnum_to_master - look up master associated with bus_num
2953 * @bus_num: the master's bus number
2954 * Context: can sleep
2956 * This call may be used with devices that are registered after
2957 * arch init time. It returns a refcounted pointer to the relevant
2958 * spi_controller (which the caller must release), or NULL if there is
2959 * no such master registered.
2961 * Return: the SPI master structure on success, else NULL.
2963 struct spi_controller *spi_busnum_to_master(u16 bus_num)
2966 struct spi_controller *ctlr = NULL;
2968 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2969 __spi_controller_match);
2971 ctlr = container_of(dev, struct spi_controller, dev);
2972 /* reference got in class_find_device */
2975 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2977 /*-------------------------------------------------------------------------*/
2979 /* Core methods for SPI resource management */
2982 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2983 * during the processing of a spi_message while using
2985 * @spi: the spi device for which we allocate memory
2986 * @release: the release code to execute for this resource
2987 * @size: size to alloc and return
2988 * @gfp: GFP allocation flags
2990 * Return: the pointer to the allocated data
2992 * This may get enhanced in the future to allocate from a memory pool
2993 * of the @spi_device or @spi_controller to avoid repeated allocations.
2995 void *spi_res_alloc(struct spi_device *spi,
2996 spi_res_release_t release,
2997 size_t size, gfp_t gfp)
2999 struct spi_res *sres;
3001 sres = kzalloc(sizeof(*sres) + size, gfp);
3005 INIT_LIST_HEAD(&sres->entry);
3006 sres->release = release;
3010 EXPORT_SYMBOL_GPL(spi_res_alloc);
3013 * spi_res_free - free an spi resource
3014 * @res: pointer to the custom data of a resource
3017 void spi_res_free(void *res)
3019 struct spi_res *sres = container_of(res, struct spi_res, data);
3024 WARN_ON(!list_empty(&sres->entry));
3027 EXPORT_SYMBOL_GPL(spi_res_free);
3030 * spi_res_add - add a spi_res to the spi_message
3031 * @message: the spi message
3032 * @res: the spi_resource
3034 void spi_res_add(struct spi_message *message, void *res)
3036 struct spi_res *sres = container_of(res, struct spi_res, data);
3038 WARN_ON(!list_empty(&sres->entry));
3039 list_add_tail(&sres->entry, &message->resources);
3041 EXPORT_SYMBOL_GPL(spi_res_add);
3044 * spi_res_release - release all spi resources for this message
3045 * @ctlr: the @spi_controller
3046 * @message: the @spi_message
3048 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3050 struct spi_res *res, *tmp;
3052 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3054 res->release(ctlr, message, res->data);
3056 list_del(&res->entry);
3061 EXPORT_SYMBOL_GPL(spi_res_release);
3063 /*-------------------------------------------------------------------------*/
3065 /* Core methods for spi_message alterations */
3067 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3068 struct spi_message *msg,
3071 struct spi_replaced_transfers *rxfer = res;
3074 /* call extra callback if requested */
3076 rxfer->release(ctlr, msg, res);
3078 /* insert replaced transfers back into the message */
3079 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3081 /* remove the formerly inserted entries */
3082 for (i = 0; i < rxfer->inserted; i++)
3083 list_del(&rxfer->inserted_transfers[i].transfer_list);
3087 * spi_replace_transfers - replace transfers with several transfers
3088 * and register change with spi_message.resources
3089 * @msg: the spi_message we work upon
3090 * @xfer_first: the first spi_transfer we want to replace
3091 * @remove: number of transfers to remove
3092 * @insert: the number of transfers we want to insert instead
3093 * @release: extra release code necessary in some circumstances
3094 * @extradatasize: extra data to allocate (with alignment guarantees
3095 * of struct @spi_transfer)
3098 * Returns: pointer to @spi_replaced_transfers,
3099 * PTR_ERR(...) in case of errors.
3101 struct spi_replaced_transfers *spi_replace_transfers(
3102 struct spi_message *msg,
3103 struct spi_transfer *xfer_first,
3106 spi_replaced_release_t release,
3107 size_t extradatasize,
3110 struct spi_replaced_transfers *rxfer;
3111 struct spi_transfer *xfer;
3114 /* allocate the structure using spi_res */
3115 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3116 struct_size(rxfer, inserted_transfers, insert)
3120 return ERR_PTR(-ENOMEM);
3122 /* the release code to invoke before running the generic release */
3123 rxfer->release = release;
3125 /* assign extradata */
3128 &rxfer->inserted_transfers[insert];
3130 /* init the replaced_transfers list */
3131 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3133 /* assign the list_entry after which we should reinsert
3134 * the @replaced_transfers - it may be spi_message.messages!
3136 rxfer->replaced_after = xfer_first->transfer_list.prev;
3138 /* remove the requested number of transfers */
3139 for (i = 0; i < remove; i++) {
3140 /* if the entry after replaced_after it is msg->transfers
3141 * then we have been requested to remove more transfers
3142 * than are in the list
3144 if (rxfer->replaced_after->next == &msg->transfers) {
3145 dev_err(&msg->spi->dev,
3146 "requested to remove more spi_transfers than are available\n");
3147 /* insert replaced transfers back into the message */
3148 list_splice(&rxfer->replaced_transfers,
3149 rxfer->replaced_after);
3151 /* free the spi_replace_transfer structure */
3152 spi_res_free(rxfer);
3154 /* and return with an error */
3155 return ERR_PTR(-EINVAL);
3158 /* remove the entry after replaced_after from list of
3159 * transfers and add it to list of replaced_transfers
3161 list_move_tail(rxfer->replaced_after->next,
3162 &rxfer->replaced_transfers);
3165 /* create copy of the given xfer with identical settings
3166 * based on the first transfer to get removed
3168 for (i = 0; i < insert; i++) {
3169 /* we need to run in reverse order */
3170 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3172 /* copy all spi_transfer data */
3173 memcpy(xfer, xfer_first, sizeof(*xfer));
3176 list_add(&xfer->transfer_list, rxfer->replaced_after);
3178 /* clear cs_change and delay for all but the last */
3180 xfer->cs_change = false;
3181 xfer->delay_usecs = 0;
3182 xfer->delay.value = 0;
3186 /* set up inserted */
3187 rxfer->inserted = insert;
3189 /* and register it with spi_res/spi_message */
3190 spi_res_add(msg, rxfer);
3194 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3196 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3197 struct spi_message *msg,
3198 struct spi_transfer **xferp,
3202 struct spi_transfer *xfer = *xferp, *xfers;
3203 struct spi_replaced_transfers *srt;
3207 /* calculate how many we have to replace */
3208 count = DIV_ROUND_UP(xfer->len, maxsize);
3210 /* create replacement */
3211 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3213 return PTR_ERR(srt);
3214 xfers = srt->inserted_transfers;
3216 /* now handle each of those newly inserted spi_transfers
3217 * note that the replacements spi_transfers all are preset
3218 * to the same values as *xferp, so tx_buf, rx_buf and len
3219 * are all identical (as well as most others)
3220 * so we just have to fix up len and the pointers.
3222 * this also includes support for the depreciated
3223 * spi_message.is_dma_mapped interface
3226 /* the first transfer just needs the length modified, so we
3227 * run it outside the loop
3229 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3231 /* all the others need rx_buf/tx_buf also set */
3232 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3233 /* update rx_buf, tx_buf and dma */
3234 if (xfers[i].rx_buf)
3235 xfers[i].rx_buf += offset;
3236 if (xfers[i].rx_dma)
3237 xfers[i].rx_dma += offset;
3238 if (xfers[i].tx_buf)
3239 xfers[i].tx_buf += offset;
3240 if (xfers[i].tx_dma)
3241 xfers[i].tx_dma += offset;
3244 xfers[i].len = min(maxsize, xfers[i].len - offset);
3247 /* we set up xferp to the last entry we have inserted,
3248 * so that we skip those already split transfers
3250 *xferp = &xfers[count - 1];
3252 /* increment statistics counters */
3253 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3254 transfers_split_maxsize);
3255 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3256 transfers_split_maxsize);
3262 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3263 * when an individual transfer exceeds a
3265 * @ctlr: the @spi_controller for this transfer
3266 * @msg: the @spi_message to transform
3267 * @maxsize: the maximum when to apply this
3268 * @gfp: GFP allocation flags
3270 * Return: status of transformation
3272 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3273 struct spi_message *msg,
3277 struct spi_transfer *xfer;
3280 /* iterate over the transfer_list,
3281 * but note that xfer is advanced to the last transfer inserted
3282 * to avoid checking sizes again unnecessarily (also xfer does
3283 * potentiall belong to a different list by the time the
3284 * replacement has happened
3286 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3287 if (xfer->len > maxsize) {
3288 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3297 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3299 /*-------------------------------------------------------------------------*/
3301 /* Core methods for SPI controller protocol drivers. Some of the
3302 * other core methods are currently defined as inline functions.
3305 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3308 if (ctlr->bits_per_word_mask) {
3309 /* Only 32 bits fit in the mask */
3310 if (bits_per_word > 32)
3312 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3320 * spi_setup - setup SPI mode and clock rate
3321 * @spi: the device whose settings are being modified
3322 * Context: can sleep, and no requests are queued to the device
3324 * SPI protocol drivers may need to update the transfer mode if the
3325 * device doesn't work with its default. They may likewise need
3326 * to update clock rates or word sizes from initial values. This function
3327 * changes those settings, and must be called from a context that can sleep.
3328 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3329 * effect the next time the device is selected and data is transferred to
3330 * or from it. When this function returns, the spi device is deselected.
3332 * Note that this call will fail if the protocol driver specifies an option
3333 * that the underlying controller or its driver does not support. For
3334 * example, not all hardware supports wire transfers using nine bit words,
3335 * LSB-first wire encoding, or active-high chipselects.
3337 * Return: zero on success, else a negative error code.
3339 int spi_setup(struct spi_device *spi)
3341 unsigned bad_bits, ugly_bits;
3345 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3346 * are set at the same time
3348 if ((hweight_long(spi->mode &
3349 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3350 (hweight_long(spi->mode &
3351 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3353 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3356 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3358 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3359 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3360 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3362 /* help drivers fail *cleanly* when they need options
3363 * that aren't supported with their current controller
3364 * SPI_CS_WORD has a fallback software implementation,
3365 * so it is ignored here.
3367 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3368 SPI_NO_TX | SPI_NO_RX);
3369 /* nothing prevents from working with active-high CS in case if it
3370 * is driven by GPIO.
3372 if (gpio_is_valid(spi->cs_gpio))
3373 bad_bits &= ~SPI_CS_HIGH;
3374 ugly_bits = bad_bits &
3375 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3376 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3379 "setup: ignoring unsupported mode bits %x\n",
3381 spi->mode &= ~ugly_bits;
3382 bad_bits &= ~ugly_bits;
3385 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3390 if (!spi->bits_per_word)
3391 spi->bits_per_word = 8;
3393 status = __spi_validate_bits_per_word(spi->controller,
3394 spi->bits_per_word);
3398 if (spi->controller->max_speed_hz &&
3399 (!spi->max_speed_hz ||
3400 spi->max_speed_hz > spi->controller->max_speed_hz))
3401 spi->max_speed_hz = spi->controller->max_speed_hz;
3403 mutex_lock(&spi->controller->io_mutex);
3405 if (spi->controller->setup)
3406 status = spi->controller->setup(spi);
3408 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3409 status = pm_runtime_get_sync(spi->controller->dev.parent);
3411 mutex_unlock(&spi->controller->io_mutex);
3412 pm_runtime_put_noidle(spi->controller->dev.parent);
3413 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3419 * We do not want to return positive value from pm_runtime_get,
3420 * there are many instances of devices calling spi_setup() and
3421 * checking for a non-zero return value instead of a negative
3426 spi_set_cs(spi, false);
3427 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3428 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3430 spi_set_cs(spi, false);
3433 mutex_unlock(&spi->controller->io_mutex);
3435 if (spi->rt && !spi->controller->rt) {
3436 spi->controller->rt = true;
3437 spi_set_thread_rt(spi->controller);
3440 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3441 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
3442 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3443 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3444 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3445 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3446 spi->bits_per_word, spi->max_speed_hz,
3451 EXPORT_SYMBOL_GPL(spi_setup);
3454 * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3455 * @spi: the device that requires specific CS timing configuration
3456 * @setup: CS setup time specified via @spi_delay
3457 * @hold: CS hold time specified via @spi_delay
3458 * @inactive: CS inactive delay between transfers specified via @spi_delay
3460 * Return: zero on success, else a negative error code.
3462 int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
3463 struct spi_delay *hold, struct spi_delay *inactive)
3465 struct device *parent = spi->controller->dev.parent;
3469 if (spi->controller->set_cs_timing &&
3470 !(spi->cs_gpiod || gpio_is_valid(spi->cs_gpio))) {
3471 if (spi->controller->auto_runtime_pm) {
3472 status = pm_runtime_get_sync(parent);
3474 pm_runtime_put_noidle(parent);
3475 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3480 status = spi->controller->set_cs_timing(spi, setup,
3482 pm_runtime_mark_last_busy(parent);
3483 pm_runtime_put_autosuspend(parent);
3486 return spi->controller->set_cs_timing(spi, setup, hold,
3491 if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
3492 (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
3493 (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
3495 "Clock-cycle delays for CS not supported in SW mode\n");
3499 len = sizeof(struct spi_delay);
3501 /* copy delays to controller */
3503 memcpy(&spi->controller->cs_setup, setup, len);
3505 memset(&spi->controller->cs_setup, 0, len);
3508 memcpy(&spi->controller->cs_hold, hold, len);
3510 memset(&spi->controller->cs_hold, 0, len);
3513 memcpy(&spi->controller->cs_inactive, inactive, len);
3515 memset(&spi->controller->cs_inactive, 0, len);
3519 EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3521 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3522 struct spi_device *spi)
3526 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3530 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3534 if (delay1 < delay2)
3535 memcpy(&xfer->word_delay, &spi->word_delay,
3536 sizeof(xfer->word_delay));
3541 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3543 struct spi_controller *ctlr = spi->controller;
3544 struct spi_transfer *xfer;
3547 if (list_empty(&message->transfers))
3550 /* If an SPI controller does not support toggling the CS line on each
3551 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3552 * for the CS line, we can emulate the CS-per-word hardware function by
3553 * splitting transfers into one-word transfers and ensuring that
3554 * cs_change is set for each transfer.
3556 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3558 gpio_is_valid(spi->cs_gpio))) {
3562 maxsize = (spi->bits_per_word + 7) / 8;
3564 /* spi_split_transfers_maxsize() requires message->spi */
3567 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3572 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3573 /* don't change cs_change on the last entry in the list */
3574 if (list_is_last(&xfer->transfer_list, &message->transfers))
3576 xfer->cs_change = 1;
3580 /* Half-duplex links include original MicroWire, and ones with
3581 * only one data pin like SPI_3WIRE (switches direction) or where
3582 * either MOSI or MISO is missing. They can also be caused by
3583 * software limitations.
3585 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3586 (spi->mode & SPI_3WIRE)) {
3587 unsigned flags = ctlr->flags;
3589 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3590 if (xfer->rx_buf && xfer->tx_buf)
3592 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3594 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3600 * Set transfer bits_per_word and max speed as spi device default if
3601 * it is not set for this transfer.
3602 * Set transfer tx_nbits and rx_nbits as single transfer default
3603 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3604 * Ensure transfer word_delay is at least as long as that required by
3607 message->frame_length = 0;
3608 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3609 xfer->effective_speed_hz = 0;
3610 message->frame_length += xfer->len;
3611 if (!xfer->bits_per_word)
3612 xfer->bits_per_word = spi->bits_per_word;
3614 if (!xfer->speed_hz)
3615 xfer->speed_hz = spi->max_speed_hz;
3617 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3618 xfer->speed_hz = ctlr->max_speed_hz;
3620 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3624 * SPI transfer length should be multiple of SPI word size
3625 * where SPI word size should be power-of-two multiple
3627 if (xfer->bits_per_word <= 8)
3629 else if (xfer->bits_per_word <= 16)
3634 /* No partial transfers accepted */
3635 if (xfer->len % w_size)
3638 if (xfer->speed_hz && ctlr->min_speed_hz &&
3639 xfer->speed_hz < ctlr->min_speed_hz)
3642 if (xfer->tx_buf && !xfer->tx_nbits)
3643 xfer->tx_nbits = SPI_NBITS_SINGLE;
3644 if (xfer->rx_buf && !xfer->rx_nbits)
3645 xfer->rx_nbits = SPI_NBITS_SINGLE;
3646 /* check transfer tx/rx_nbits:
3647 * 1. check the value matches one of single, dual and quad
3648 * 2. check tx/rx_nbits match the mode in spi_device
3651 if (spi->mode & SPI_NO_TX)
3653 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3654 xfer->tx_nbits != SPI_NBITS_DUAL &&
3655 xfer->tx_nbits != SPI_NBITS_QUAD)
3657 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3658 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3660 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3661 !(spi->mode & SPI_TX_QUAD))
3664 /* check transfer rx_nbits */
3666 if (spi->mode & SPI_NO_RX)
3668 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3669 xfer->rx_nbits != SPI_NBITS_DUAL &&
3670 xfer->rx_nbits != SPI_NBITS_QUAD)
3672 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3673 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3675 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3676 !(spi->mode & SPI_RX_QUAD))
3680 if (_spi_xfer_word_delay_update(xfer, spi))
3684 message->status = -EINPROGRESS;
3689 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3691 struct spi_controller *ctlr = spi->controller;
3692 struct spi_transfer *xfer;
3695 * Some controllers do not support doing regular SPI transfers. Return
3696 * ENOTSUPP when this is the case.
3698 if (!ctlr->transfer)
3703 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3704 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3706 trace_spi_message_submit(message);
3708 if (!ctlr->ptp_sts_supported) {
3709 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3710 xfer->ptp_sts_word_pre = 0;
3711 ptp_read_system_prets(xfer->ptp_sts);
3715 return ctlr->transfer(spi, message);
3719 * spi_async - asynchronous SPI transfer
3720 * @spi: device with which data will be exchanged
3721 * @message: describes the data transfers, including completion callback
3722 * Context: any (irqs may be blocked, etc)
3724 * This call may be used in_irq and other contexts which can't sleep,
3725 * as well as from task contexts which can sleep.
3727 * The completion callback is invoked in a context which can't sleep.
3728 * Before that invocation, the value of message->status is undefined.
3729 * When the callback is issued, message->status holds either zero (to
3730 * indicate complete success) or a negative error code. After that
3731 * callback returns, the driver which issued the transfer request may
3732 * deallocate the associated memory; it's no longer in use by any SPI
3733 * core or controller driver code.
3735 * Note that although all messages to a spi_device are handled in
3736 * FIFO order, messages may go to different devices in other orders.
3737 * Some device might be higher priority, or have various "hard" access
3738 * time requirements, for example.
3740 * On detection of any fault during the transfer, processing of
3741 * the entire message is aborted, and the device is deselected.
3742 * Until returning from the associated message completion callback,
3743 * no other spi_message queued to that device will be processed.
3744 * (This rule applies equally to all the synchronous transfer calls,
3745 * which are wrappers around this core asynchronous primitive.)
3747 * Return: zero on success, else a negative error code.
3749 int spi_async(struct spi_device *spi, struct spi_message *message)
3751 struct spi_controller *ctlr = spi->controller;
3753 unsigned long flags;
3755 ret = __spi_validate(spi, message);
3759 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3761 if (ctlr->bus_lock_flag)
3764 ret = __spi_async(spi, message);
3766 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3770 EXPORT_SYMBOL_GPL(spi_async);
3773 * spi_async_locked - version of spi_async with exclusive bus usage
3774 * @spi: device with which data will be exchanged
3775 * @message: describes the data transfers, including completion callback
3776 * Context: any (irqs may be blocked, etc)
3778 * This call may be used in_irq and other contexts which can't sleep,
3779 * as well as from task contexts which can sleep.
3781 * The completion callback is invoked in a context which can't sleep.
3782 * Before that invocation, the value of message->status is undefined.
3783 * When the callback is issued, message->status holds either zero (to
3784 * indicate complete success) or a negative error code. After that
3785 * callback returns, the driver which issued the transfer request may
3786 * deallocate the associated memory; it's no longer in use by any SPI
3787 * core or controller driver code.
3789 * Note that although all messages to a spi_device are handled in
3790 * FIFO order, messages may go to different devices in other orders.
3791 * Some device might be higher priority, or have various "hard" access
3792 * time requirements, for example.
3794 * On detection of any fault during the transfer, processing of
3795 * the entire message is aborted, and the device is deselected.
3796 * Until returning from the associated message completion callback,
3797 * no other spi_message queued to that device will be processed.
3798 * (This rule applies equally to all the synchronous transfer calls,
3799 * which are wrappers around this core asynchronous primitive.)
3801 * Return: zero on success, else a negative error code.
3803 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3805 struct spi_controller *ctlr = spi->controller;
3807 unsigned long flags;
3809 ret = __spi_validate(spi, message);
3813 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3815 ret = __spi_async(spi, message);
3817 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3822 EXPORT_SYMBOL_GPL(spi_async_locked);
3824 /*-------------------------------------------------------------------------*/
3826 /* Utility methods for SPI protocol drivers, layered on
3827 * top of the core. Some other utility methods are defined as
3831 static void spi_complete(void *arg)
3836 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3838 DECLARE_COMPLETION_ONSTACK(done);
3840 struct spi_controller *ctlr = spi->controller;
3841 unsigned long flags;
3843 status = __spi_validate(spi, message);
3847 message->complete = spi_complete;
3848 message->context = &done;
3851 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3852 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3854 /* If we're not using the legacy transfer method then we will
3855 * try to transfer in the calling context so special case.
3856 * This code would be less tricky if we could remove the
3857 * support for driver implemented message queues.
3859 if (ctlr->transfer == spi_queued_transfer) {
3860 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3862 trace_spi_message_submit(message);
3864 status = __spi_queued_transfer(spi, message, false);
3866 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3868 status = spi_async_locked(spi, message);
3872 /* Push out the messages in the calling context if we
3875 if (ctlr->transfer == spi_queued_transfer) {
3876 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3877 spi_sync_immediate);
3878 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3879 spi_sync_immediate);
3880 __spi_pump_messages(ctlr, false);
3883 wait_for_completion(&done);
3884 status = message->status;
3886 message->context = NULL;
3891 * spi_sync - blocking/synchronous SPI data transfers
3892 * @spi: device with which data will be exchanged
3893 * @message: describes the data transfers
3894 * Context: can sleep
3896 * This call may only be used from a context that may sleep. The sleep
3897 * is non-interruptible, and has no timeout. Low-overhead controller
3898 * drivers may DMA directly into and out of the message buffers.
3900 * Note that the SPI device's chip select is active during the message,
3901 * and then is normally disabled between messages. Drivers for some
3902 * frequently-used devices may want to minimize costs of selecting a chip,
3903 * by leaving it selected in anticipation that the next message will go
3904 * to the same chip. (That may increase power usage.)
3906 * Also, the caller is guaranteeing that the memory associated with the
3907 * message will not be freed before this call returns.
3909 * Return: zero on success, else a negative error code.
3911 int spi_sync(struct spi_device *spi, struct spi_message *message)
3915 mutex_lock(&spi->controller->bus_lock_mutex);
3916 ret = __spi_sync(spi, message);
3917 mutex_unlock(&spi->controller->bus_lock_mutex);
3921 EXPORT_SYMBOL_GPL(spi_sync);
3924 * spi_sync_locked - version of spi_sync with exclusive bus usage
3925 * @spi: device with which data will be exchanged
3926 * @message: describes the data transfers
3927 * Context: can sleep
3929 * This call may only be used from a context that may sleep. The sleep
3930 * is non-interruptible, and has no timeout. Low-overhead controller
3931 * drivers may DMA directly into and out of the message buffers.
3933 * This call should be used by drivers that require exclusive access to the
3934 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3935 * be released by a spi_bus_unlock call when the exclusive access is over.
3937 * Return: zero on success, else a negative error code.
3939 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3941 return __spi_sync(spi, message);
3943 EXPORT_SYMBOL_GPL(spi_sync_locked);
3946 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3947 * @ctlr: SPI bus master that should be locked for exclusive bus access
3948 * Context: can sleep
3950 * This call may only be used from a context that may sleep. The sleep
3951 * is non-interruptible, and has no timeout.
3953 * This call should be used by drivers that require exclusive access to the
3954 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3955 * exclusive access is over. Data transfer must be done by spi_sync_locked
3956 * and spi_async_locked calls when the SPI bus lock is held.
3958 * Return: always zero.
3960 int spi_bus_lock(struct spi_controller *ctlr)
3962 unsigned long flags;
3964 mutex_lock(&ctlr->bus_lock_mutex);
3966 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3967 ctlr->bus_lock_flag = 1;
3968 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3970 /* mutex remains locked until spi_bus_unlock is called */
3974 EXPORT_SYMBOL_GPL(spi_bus_lock);
3977 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3978 * @ctlr: SPI bus master that was locked for exclusive bus access
3979 * Context: can sleep
3981 * This call may only be used from a context that may sleep. The sleep
3982 * is non-interruptible, and has no timeout.
3984 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3987 * Return: always zero.
3989 int spi_bus_unlock(struct spi_controller *ctlr)
3991 ctlr->bus_lock_flag = 0;
3993 mutex_unlock(&ctlr->bus_lock_mutex);
3997 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3999 /* portable code must never pass more than 32 bytes */
4000 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4005 * spi_write_then_read - SPI synchronous write followed by read
4006 * @spi: device with which data will be exchanged
4007 * @txbuf: data to be written (need not be dma-safe)
4008 * @n_tx: size of txbuf, in bytes
4009 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4010 * @n_rx: size of rxbuf, in bytes
4011 * Context: can sleep
4013 * This performs a half duplex MicroWire style transaction with the
4014 * device, sending txbuf and then reading rxbuf. The return value
4015 * is zero for success, else a negative errno status code.
4016 * This call may only be used from a context that may sleep.
4018 * Parameters to this routine are always copied using a small buffer.
4019 * Performance-sensitive or bulk transfer code should instead use
4020 * spi_{async,sync}() calls with dma-safe buffers.
4022 * Return: zero on success, else a negative error code.
4024 int spi_write_then_read(struct spi_device *spi,
4025 const void *txbuf, unsigned n_tx,
4026 void *rxbuf, unsigned n_rx)
4028 static DEFINE_MUTEX(lock);
4031 struct spi_message message;
4032 struct spi_transfer x[2];
4035 /* Use preallocated DMA-safe buffer if we can. We can't avoid
4036 * copying here, (as a pure convenience thing), but we can
4037 * keep heap costs out of the hot path unless someone else is
4038 * using the pre-allocated buffer or the transfer is too large.
4040 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4041 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4042 GFP_KERNEL | GFP_DMA);
4049 spi_message_init(&message);
4050 memset(x, 0, sizeof(x));
4053 spi_message_add_tail(&x[0], &message);
4057 spi_message_add_tail(&x[1], &message);
4060 memcpy(local_buf, txbuf, n_tx);
4061 x[0].tx_buf = local_buf;
4062 x[1].rx_buf = local_buf + n_tx;
4065 status = spi_sync(spi, &message);
4067 memcpy(rxbuf, x[1].rx_buf, n_rx);
4069 if (x[0].tx_buf == buf)
4070 mutex_unlock(&lock);
4076 EXPORT_SYMBOL_GPL(spi_write_then_read);
4078 /*-------------------------------------------------------------------------*/
4080 #if IS_ENABLED(CONFIG_OF)
4081 /* must call put_device() when done with returned spi_device device */
4082 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4084 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4086 return dev ? to_spi_device(dev) : NULL;
4088 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4089 #endif /* IS_ENABLED(CONFIG_OF) */
4091 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4092 /* the spi controllers are not using spi_bus, so we find it with another way */
4093 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4097 dev = class_find_device_by_of_node(&spi_master_class, node);
4098 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4099 dev = class_find_device_by_of_node(&spi_slave_class, node);
4103 /* reference got in class_find_device */
4104 return container_of(dev, struct spi_controller, dev);
4107 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4110 struct of_reconfig_data *rd = arg;
4111 struct spi_controller *ctlr;
4112 struct spi_device *spi;
4114 switch (of_reconfig_get_state_change(action, arg)) {
4115 case OF_RECONFIG_CHANGE_ADD:
4116 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4118 return NOTIFY_OK; /* not for us */
4120 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4121 put_device(&ctlr->dev);
4125 spi = of_register_spi_device(ctlr, rd->dn);
4126 put_device(&ctlr->dev);
4129 pr_err("%s: failed to create for '%pOF'\n",
4131 of_node_clear_flag(rd->dn, OF_POPULATED);
4132 return notifier_from_errno(PTR_ERR(spi));
4136 case OF_RECONFIG_CHANGE_REMOVE:
4137 /* already depopulated? */
4138 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4141 /* find our device by node */
4142 spi = of_find_spi_device_by_node(rd->dn);
4144 return NOTIFY_OK; /* no? not meant for us */
4146 /* unregister takes one ref away */
4147 spi_unregister_device(spi);
4149 /* and put the reference of the find */
4150 put_device(&spi->dev);
4157 static struct notifier_block spi_of_notifier = {
4158 .notifier_call = of_spi_notify,
4160 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4161 extern struct notifier_block spi_of_notifier;
4162 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4164 #if IS_ENABLED(CONFIG_ACPI)
4165 static int spi_acpi_controller_match(struct device *dev, const void *data)
4167 return ACPI_COMPANION(dev->parent) == data;
4170 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4174 dev = class_find_device(&spi_master_class, NULL, adev,
4175 spi_acpi_controller_match);
4176 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4177 dev = class_find_device(&spi_slave_class, NULL, adev,
4178 spi_acpi_controller_match);
4182 return container_of(dev, struct spi_controller, dev);
4185 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4189 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4190 return to_spi_device(dev);
4193 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4196 struct acpi_device *adev = arg;
4197 struct spi_controller *ctlr;
4198 struct spi_device *spi;
4201 case ACPI_RECONFIG_DEVICE_ADD:
4202 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4206 acpi_register_spi_device(ctlr, adev);
4207 put_device(&ctlr->dev);
4209 case ACPI_RECONFIG_DEVICE_REMOVE:
4210 if (!acpi_device_enumerated(adev))
4213 spi = acpi_spi_find_device_by_adev(adev);
4217 spi_unregister_device(spi);
4218 put_device(&spi->dev);
4225 static struct notifier_block spi_acpi_notifier = {
4226 .notifier_call = acpi_spi_notify,
4229 extern struct notifier_block spi_acpi_notifier;
4232 static int __init spi_init(void)
4236 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4242 status = bus_register(&spi_bus_type);
4246 status = class_register(&spi_master_class);
4250 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4251 status = class_register(&spi_slave_class);
4256 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4257 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4258 if (IS_ENABLED(CONFIG_ACPI))
4259 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4264 class_unregister(&spi_master_class);
4266 bus_unregister(&spi_bus_type);
4274 /* board_info is normally registered in arch_initcall(),
4275 * but even essential drivers wait till later
4277 * REVISIT only boardinfo really needs static linking. the rest (device and
4278 * driver registration) _could_ be dynamically linked (modular) ... costs
4279 * include needing to have boardinfo data structures be much more public.
4281 postcore_initcall(spi_init);