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/gpio/consumer.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/pm_domain.h>
24 #include <linux/property.h>
25 #include <linux/export.h>
26 #include <linux/sched/rt.h>
27 #include <uapi/linux/sched/types.h>
28 #include <linux/delay.h>
29 #include <linux/kthread.h>
30 #include <linux/ioport.h>
31 #include <linux/acpi.h>
32 #include <linux/highmem.h>
33 #include <linux/idr.h>
34 #include <linux/platform_data/x86/apple.h>
35 #include <linux/ptp_clock_kernel.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/spi.h>
39 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
42 #include "internals.h"
44 static DEFINE_IDR(spi_master_idr);
46 static void spidev_release(struct device *dev)
48 struct spi_device *spi = to_spi_device(dev);
50 spi_controller_put(spi->controller);
51 kfree(spi->driver_override);
56 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
58 const struct spi_device *spi = to_spi_device(dev);
61 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
65 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
67 static DEVICE_ATTR_RO(modalias);
69 static ssize_t driver_override_store(struct device *dev,
70 struct device_attribute *a,
71 const char *buf, size_t count)
73 struct spi_device *spi = to_spi_device(dev);
76 ret = driver_set_override(dev, &spi->driver_override, buf, count);
83 static ssize_t driver_override_show(struct device *dev,
84 struct device_attribute *a, char *buf)
86 const struct spi_device *spi = to_spi_device(dev);
90 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
94 static DEVICE_ATTR_RW(driver_override);
96 #define SPI_STATISTICS_ATTRS(field, file) \
97 static ssize_t spi_controller_##field##_show(struct device *dev, \
98 struct device_attribute *attr, \
101 struct spi_controller *ctlr = container_of(dev, \
102 struct spi_controller, dev); \
103 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
105 static struct device_attribute dev_attr_spi_controller_##field = { \
106 .attr = { .name = file, .mode = 0444 }, \
107 .show = spi_controller_##field##_show, \
109 static ssize_t spi_device_##field##_show(struct device *dev, \
110 struct device_attribute *attr, \
113 struct spi_device *spi = to_spi_device(dev); \
114 return spi_statistics_##field##_show(&spi->statistics, buf); \
116 static struct device_attribute dev_attr_spi_device_##field = { \
117 .attr = { .name = file, .mode = 0444 }, \
118 .show = spi_device_##field##_show, \
121 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
122 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
125 unsigned long flags; \
127 spin_lock_irqsave(&stat->lock, flags); \
128 len = sysfs_emit(buf, format_string "\n", stat->field); \
129 spin_unlock_irqrestore(&stat->lock, flags); \
132 SPI_STATISTICS_ATTRS(name, file)
134 #define SPI_STATISTICS_SHOW(field, format_string) \
135 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
136 field, format_string)
138 SPI_STATISTICS_SHOW(messages, "%lu");
139 SPI_STATISTICS_SHOW(transfers, "%lu");
140 SPI_STATISTICS_SHOW(errors, "%lu");
141 SPI_STATISTICS_SHOW(timedout, "%lu");
143 SPI_STATISTICS_SHOW(spi_sync, "%lu");
144 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
145 SPI_STATISTICS_SHOW(spi_async, "%lu");
147 SPI_STATISTICS_SHOW(bytes, "%llu");
148 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
149 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
151 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
152 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
153 "transfer_bytes_histo_" number, \
154 transfer_bytes_histo[index], "%lu")
155 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
156 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
157 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
158 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
159 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
160 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
161 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
162 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
163 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
164 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
165 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
166 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
167 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
168 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
169 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
170 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
171 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
173 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
175 static struct attribute *spi_dev_attrs[] = {
176 &dev_attr_modalias.attr,
177 &dev_attr_driver_override.attr,
181 static const struct attribute_group spi_dev_group = {
182 .attrs = spi_dev_attrs,
185 static struct attribute *spi_device_statistics_attrs[] = {
186 &dev_attr_spi_device_messages.attr,
187 &dev_attr_spi_device_transfers.attr,
188 &dev_attr_spi_device_errors.attr,
189 &dev_attr_spi_device_timedout.attr,
190 &dev_attr_spi_device_spi_sync.attr,
191 &dev_attr_spi_device_spi_sync_immediate.attr,
192 &dev_attr_spi_device_spi_async.attr,
193 &dev_attr_spi_device_bytes.attr,
194 &dev_attr_spi_device_bytes_rx.attr,
195 &dev_attr_spi_device_bytes_tx.attr,
196 &dev_attr_spi_device_transfer_bytes_histo0.attr,
197 &dev_attr_spi_device_transfer_bytes_histo1.attr,
198 &dev_attr_spi_device_transfer_bytes_histo2.attr,
199 &dev_attr_spi_device_transfer_bytes_histo3.attr,
200 &dev_attr_spi_device_transfer_bytes_histo4.attr,
201 &dev_attr_spi_device_transfer_bytes_histo5.attr,
202 &dev_attr_spi_device_transfer_bytes_histo6.attr,
203 &dev_attr_spi_device_transfer_bytes_histo7.attr,
204 &dev_attr_spi_device_transfer_bytes_histo8.attr,
205 &dev_attr_spi_device_transfer_bytes_histo9.attr,
206 &dev_attr_spi_device_transfer_bytes_histo10.attr,
207 &dev_attr_spi_device_transfer_bytes_histo11.attr,
208 &dev_attr_spi_device_transfer_bytes_histo12.attr,
209 &dev_attr_spi_device_transfer_bytes_histo13.attr,
210 &dev_attr_spi_device_transfer_bytes_histo14.attr,
211 &dev_attr_spi_device_transfer_bytes_histo15.attr,
212 &dev_attr_spi_device_transfer_bytes_histo16.attr,
213 &dev_attr_spi_device_transfers_split_maxsize.attr,
217 static const struct attribute_group spi_device_statistics_group = {
218 .name = "statistics",
219 .attrs = spi_device_statistics_attrs,
222 static const struct attribute_group *spi_dev_groups[] = {
224 &spi_device_statistics_group,
228 static struct attribute *spi_controller_statistics_attrs[] = {
229 &dev_attr_spi_controller_messages.attr,
230 &dev_attr_spi_controller_transfers.attr,
231 &dev_attr_spi_controller_errors.attr,
232 &dev_attr_spi_controller_timedout.attr,
233 &dev_attr_spi_controller_spi_sync.attr,
234 &dev_attr_spi_controller_spi_sync_immediate.attr,
235 &dev_attr_spi_controller_spi_async.attr,
236 &dev_attr_spi_controller_bytes.attr,
237 &dev_attr_spi_controller_bytes_rx.attr,
238 &dev_attr_spi_controller_bytes_tx.attr,
239 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
240 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
241 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
242 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
243 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
244 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
245 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
246 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
247 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
248 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
249 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
250 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
251 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
252 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
253 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
254 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
255 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
256 &dev_attr_spi_controller_transfers_split_maxsize.attr,
260 static const struct attribute_group spi_controller_statistics_group = {
261 .name = "statistics",
262 .attrs = spi_controller_statistics_attrs,
265 static const struct attribute_group *spi_master_groups[] = {
266 &spi_controller_statistics_group,
270 static void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
271 struct spi_transfer *xfer,
272 struct spi_controller *ctlr)
275 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
280 spin_lock_irqsave(&stats->lock, flags);
283 stats->transfer_bytes_histo[l2len]++;
285 stats->bytes += xfer->len;
286 if ((xfer->tx_buf) &&
287 (xfer->tx_buf != ctlr->dummy_tx))
288 stats->bytes_tx += xfer->len;
289 if ((xfer->rx_buf) &&
290 (xfer->rx_buf != ctlr->dummy_rx))
291 stats->bytes_rx += xfer->len;
293 spin_unlock_irqrestore(&stats->lock, flags);
297 * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
298 * and the sysfs version makes coldplug work too.
300 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
302 while (id->name[0]) {
303 if (!strcmp(name, id->name))
310 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
312 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
314 return spi_match_id(sdrv->id_table, sdev->modalias);
316 EXPORT_SYMBOL_GPL(spi_get_device_id);
318 static int spi_match_device(struct device *dev, struct device_driver *drv)
320 const struct spi_device *spi = to_spi_device(dev);
321 const struct spi_driver *sdrv = to_spi_driver(drv);
323 /* Check override first, and if set, only use the named driver */
324 if (spi->driver_override)
325 return strcmp(spi->driver_override, drv->name) == 0;
327 /* Attempt an OF style match */
328 if (of_driver_match_device(dev, drv))
332 if (acpi_driver_match_device(dev, drv))
336 return !!spi_match_id(sdrv->id_table, spi->modalias);
338 return strcmp(spi->modalias, drv->name) == 0;
341 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
343 const struct spi_device *spi = to_spi_device(dev);
346 rc = acpi_device_uevent_modalias(dev, env);
350 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
353 static int spi_probe(struct device *dev)
355 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
356 struct spi_device *spi = to_spi_device(dev);
359 ret = of_clk_set_defaults(dev->of_node, false);
364 spi->irq = of_irq_get(dev->of_node, 0);
365 if (spi->irq == -EPROBE_DEFER)
366 return -EPROBE_DEFER;
371 ret = dev_pm_domain_attach(dev, true);
376 ret = sdrv->probe(spi);
378 dev_pm_domain_detach(dev, true);
384 static void spi_remove(struct device *dev)
386 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
389 sdrv->remove(to_spi_device(dev));
391 dev_pm_domain_detach(dev, true);
394 static void spi_shutdown(struct device *dev)
397 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
400 sdrv->shutdown(to_spi_device(dev));
404 struct bus_type spi_bus_type = {
406 .dev_groups = spi_dev_groups,
407 .match = spi_match_device,
408 .uevent = spi_uevent,
410 .remove = spi_remove,
411 .shutdown = spi_shutdown,
413 EXPORT_SYMBOL_GPL(spi_bus_type);
416 * __spi_register_driver - register a SPI driver
417 * @owner: owner module of the driver to register
418 * @sdrv: the driver to register
421 * Return: zero on success, else a negative error code.
423 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
425 sdrv->driver.owner = owner;
426 sdrv->driver.bus = &spi_bus_type;
429 * For Really Good Reasons we use spi: modaliases not of:
430 * modaliases for DT so module autoloading won't work if we
431 * don't have a spi_device_id as well as a compatible string.
433 if (sdrv->driver.of_match_table) {
434 const struct of_device_id *of_id;
436 for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
440 /* Strip off any vendor prefix */
441 of_name = strnchr(of_id->compatible,
442 sizeof(of_id->compatible), ',');
446 of_name = of_id->compatible;
448 if (sdrv->id_table) {
449 const struct spi_device_id *spi_id;
451 spi_id = spi_match_id(sdrv->id_table, of_name);
455 if (strcmp(sdrv->driver.name, of_name) == 0)
459 pr_warn("SPI driver %s has no spi_device_id for %s\n",
460 sdrv->driver.name, of_id->compatible);
464 return driver_register(&sdrv->driver);
466 EXPORT_SYMBOL_GPL(__spi_register_driver);
468 /*-------------------------------------------------------------------------*/
471 * SPI devices should normally not be created by SPI device drivers; that
472 * would make them board-specific. Similarly with SPI controller drivers.
473 * Device registration normally goes into like arch/.../mach.../board-YYY.c
474 * with other readonly (flashable) information about mainboard devices.
478 struct list_head list;
479 struct spi_board_info board_info;
482 static LIST_HEAD(board_list);
483 static LIST_HEAD(spi_controller_list);
486 * Used to protect add/del operation for board_info list and
487 * spi_controller list, and their matching process also used
488 * to protect object of type struct idr.
490 static DEFINE_MUTEX(board_lock);
493 * spi_alloc_device - Allocate a new SPI device
494 * @ctlr: Controller to which device is connected
497 * Allows a driver to allocate and initialize a spi_device without
498 * registering it immediately. This allows a driver to directly
499 * fill the spi_device with device parameters before calling
500 * spi_add_device() on it.
502 * Caller is responsible to call spi_add_device() on the returned
503 * spi_device structure to add it to the SPI controller. If the caller
504 * needs to discard the spi_device without adding it, then it should
505 * call spi_dev_put() on it.
507 * Return: a pointer to the new device, or NULL.
509 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
511 struct spi_device *spi;
513 if (!spi_controller_get(ctlr))
516 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
518 spi_controller_put(ctlr);
522 spi->master = spi->controller = ctlr;
523 spi->dev.parent = &ctlr->dev;
524 spi->dev.bus = &spi_bus_type;
525 spi->dev.release = spidev_release;
526 spi->mode = ctlr->buswidth_override_bits;
528 spin_lock_init(&spi->statistics.lock);
530 device_initialize(&spi->dev);
533 EXPORT_SYMBOL_GPL(spi_alloc_device);
535 static void spi_dev_set_name(struct spi_device *spi)
537 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
540 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
544 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
548 static int spi_dev_check(struct device *dev, void *data)
550 struct spi_device *spi = to_spi_device(dev);
551 struct spi_device *new_spi = data;
553 if (spi->controller == new_spi->controller &&
554 spi->chip_select == new_spi->chip_select)
559 static void spi_cleanup(struct spi_device *spi)
561 if (spi->controller->cleanup)
562 spi->controller->cleanup(spi);
565 static int __spi_add_device(struct spi_device *spi)
567 struct spi_controller *ctlr = spi->controller;
568 struct device *dev = ctlr->dev.parent;
572 * We need to make sure there's no other device with this
573 * chipselect **BEFORE** we call setup(), else we'll trash
576 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
578 dev_err(dev, "chipselect %d already in use\n",
583 /* Controller may unregister concurrently */
584 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
585 !device_is_registered(&ctlr->dev)) {
590 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
593 * Drivers may modify this initial i/o setup, but will
594 * normally rely on the device being setup. Devices
595 * using SPI_CS_HIGH can't coexist well otherwise...
597 status = spi_setup(spi);
599 dev_err(dev, "can't setup %s, status %d\n",
600 dev_name(&spi->dev), status);
604 /* Device may be bound to an active driver when this returns */
605 status = device_add(&spi->dev);
607 dev_err(dev, "can't add %s, status %d\n",
608 dev_name(&spi->dev), status);
611 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
618 * spi_add_device - Add spi_device allocated with spi_alloc_device
619 * @spi: spi_device to register
621 * Companion function to spi_alloc_device. Devices allocated with
622 * spi_alloc_device can be added onto the spi bus with this function.
624 * Return: 0 on success; negative errno on failure
626 int spi_add_device(struct spi_device *spi)
628 struct spi_controller *ctlr = spi->controller;
629 struct device *dev = ctlr->dev.parent;
632 /* Chipselects are numbered 0..max; validate. */
633 if (spi->chip_select >= ctlr->num_chipselect) {
634 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
635 ctlr->num_chipselect);
639 /* Set the bus ID string */
640 spi_dev_set_name(spi);
642 mutex_lock(&ctlr->add_lock);
643 status = __spi_add_device(spi);
644 mutex_unlock(&ctlr->add_lock);
647 EXPORT_SYMBOL_GPL(spi_add_device);
649 static int spi_add_device_locked(struct spi_device *spi)
651 struct spi_controller *ctlr = spi->controller;
652 struct device *dev = ctlr->dev.parent;
654 /* Chipselects are numbered 0..max; validate. */
655 if (spi->chip_select >= ctlr->num_chipselect) {
656 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
657 ctlr->num_chipselect);
661 /* Set the bus ID string */
662 spi_dev_set_name(spi);
664 WARN_ON(!mutex_is_locked(&ctlr->add_lock));
665 return __spi_add_device(spi);
669 * spi_new_device - instantiate one new SPI device
670 * @ctlr: Controller to which device is connected
671 * @chip: Describes the SPI device
674 * On typical mainboards, this is purely internal; and it's not needed
675 * after board init creates the hard-wired devices. Some development
676 * platforms may not be able to use spi_register_board_info though, and
677 * this is exported so that for example a USB or parport based adapter
678 * driver could add devices (which it would learn about out-of-band).
680 * Return: the new device, or NULL.
682 struct spi_device *spi_new_device(struct spi_controller *ctlr,
683 struct spi_board_info *chip)
685 struct spi_device *proxy;
689 * NOTE: caller did any chip->bus_num checks necessary.
691 * Also, unless we change the return value convention to use
692 * error-or-pointer (not NULL-or-pointer), troubleshootability
693 * suggests syslogged diagnostics are best here (ugh).
696 proxy = spi_alloc_device(ctlr);
700 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
702 proxy->chip_select = chip->chip_select;
703 proxy->max_speed_hz = chip->max_speed_hz;
704 proxy->mode = chip->mode;
705 proxy->irq = chip->irq;
706 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
707 proxy->dev.platform_data = (void *) chip->platform_data;
708 proxy->controller_data = chip->controller_data;
709 proxy->controller_state = NULL;
712 status = device_add_software_node(&proxy->dev, chip->swnode);
714 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
715 chip->modalias, status);
720 status = spi_add_device(proxy);
727 device_remove_software_node(&proxy->dev);
731 EXPORT_SYMBOL_GPL(spi_new_device);
734 * spi_unregister_device - unregister a single SPI device
735 * @spi: spi_device to unregister
737 * Start making the passed SPI device vanish. Normally this would be handled
738 * by spi_unregister_controller().
740 void spi_unregister_device(struct spi_device *spi)
745 if (spi->dev.of_node) {
746 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
747 of_node_put(spi->dev.of_node);
749 if (ACPI_COMPANION(&spi->dev))
750 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
751 device_remove_software_node(&spi->dev);
752 device_del(&spi->dev);
754 put_device(&spi->dev);
756 EXPORT_SYMBOL_GPL(spi_unregister_device);
758 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
759 struct spi_board_info *bi)
761 struct spi_device *dev;
763 if (ctlr->bus_num != bi->bus_num)
766 dev = spi_new_device(ctlr, bi);
768 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
773 * spi_register_board_info - register SPI devices for a given board
774 * @info: array of chip descriptors
775 * @n: how many descriptors are provided
778 * Board-specific early init code calls this (probably during arch_initcall)
779 * with segments of the SPI device table. Any device nodes are created later,
780 * after the relevant parent SPI controller (bus_num) is defined. We keep
781 * this table of devices forever, so that reloading a controller driver will
782 * not make Linux forget about these hard-wired devices.
784 * Other code can also call this, e.g. a particular add-on board might provide
785 * SPI devices through its expansion connector, so code initializing that board
786 * would naturally declare its SPI devices.
788 * The board info passed can safely be __initdata ... but be careful of
789 * any embedded pointers (platform_data, etc), they're copied as-is.
791 * Return: zero on success, else a negative error code.
793 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
795 struct boardinfo *bi;
801 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
805 for (i = 0; i < n; i++, bi++, info++) {
806 struct spi_controller *ctlr;
808 memcpy(&bi->board_info, info, sizeof(*info));
810 mutex_lock(&board_lock);
811 list_add_tail(&bi->list, &board_list);
812 list_for_each_entry(ctlr, &spi_controller_list, list)
813 spi_match_controller_to_boardinfo(ctlr,
815 mutex_unlock(&board_lock);
821 /*-------------------------------------------------------------------------*/
823 /* Core methods for SPI resource management */
826 * spi_res_alloc - allocate a spi resource that is life-cycle managed
827 * during the processing of a spi_message while using
829 * @spi: the spi device for which we allocate memory
830 * @release: the release code to execute for this resource
831 * @size: size to alloc and return
832 * @gfp: GFP allocation flags
834 * Return: the pointer to the allocated data
836 * This may get enhanced in the future to allocate from a memory pool
837 * of the @spi_device or @spi_controller to avoid repeated allocations.
839 static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
840 size_t size, gfp_t gfp)
842 struct spi_res *sres;
844 sres = kzalloc(sizeof(*sres) + size, gfp);
848 INIT_LIST_HEAD(&sres->entry);
849 sres->release = release;
855 * spi_res_free - free an spi resource
856 * @res: pointer to the custom data of a resource
858 static void spi_res_free(void *res)
860 struct spi_res *sres = container_of(res, struct spi_res, data);
865 WARN_ON(!list_empty(&sres->entry));
870 * spi_res_add - add a spi_res to the spi_message
871 * @message: the spi message
872 * @res: the spi_resource
874 static void spi_res_add(struct spi_message *message, void *res)
876 struct spi_res *sres = container_of(res, struct spi_res, data);
878 WARN_ON(!list_empty(&sres->entry));
879 list_add_tail(&sres->entry, &message->resources);
883 * spi_res_release - release all spi resources for this message
884 * @ctlr: the @spi_controller
885 * @message: the @spi_message
887 static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
889 struct spi_res *res, *tmp;
891 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
893 res->release(ctlr, message, res->data);
895 list_del(&res->entry);
901 /*-------------------------------------------------------------------------*/
903 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
905 bool activate = enable;
908 * Avoid calling into the driver (or doing delays) if the chip select
909 * isn't actually changing from the last time this was called.
911 if (!force && ((enable && spi->controller->last_cs == spi->chip_select) ||
912 (!enable && spi->controller->last_cs != spi->chip_select)) &&
913 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
916 trace_spi_set_cs(spi, activate);
918 spi->controller->last_cs = enable ? spi->chip_select : -1;
919 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
921 if ((spi->cs_gpiod || !spi->controller->set_cs_timing) && !activate) {
922 spi_delay_exec(&spi->cs_hold, NULL);
925 if (spi->mode & SPI_CS_HIGH)
929 if (!(spi->mode & SPI_NO_CS)) {
931 * Historically ACPI has no means of the GPIO polarity and
932 * thus the SPISerialBus() resource defines it on the per-chip
933 * basis. In order to avoid a chain of negations, the GPIO
934 * polarity is considered being Active High. Even for the cases
935 * when _DSD() is involved (in the updated versions of ACPI)
936 * the GPIO CS polarity must be defined Active High to avoid
937 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
940 if (has_acpi_companion(&spi->dev))
941 gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
943 /* Polarity handled by GPIO library */
944 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
946 /* Some SPI masters need both GPIO CS & slave_select */
947 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
948 spi->controller->set_cs)
949 spi->controller->set_cs(spi, !enable);
950 } else if (spi->controller->set_cs) {
951 spi->controller->set_cs(spi, !enable);
954 if (spi->cs_gpiod || !spi->controller->set_cs_timing) {
956 spi_delay_exec(&spi->cs_setup, NULL);
958 spi_delay_exec(&spi->cs_inactive, NULL);
962 #ifdef CONFIG_HAS_DMA
963 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
964 struct sg_table *sgt, void *buf, size_t len,
965 enum dma_data_direction dir)
967 const bool vmalloced_buf = is_vmalloc_addr(buf);
968 unsigned int max_seg_size = dma_get_max_seg_size(dev);
969 #ifdef CONFIG_HIGHMEM
970 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
971 (unsigned long)buf < (PKMAP_BASE +
972 (LAST_PKMAP * PAGE_SIZE)));
974 const bool kmap_buf = false;
978 struct page *vm_page;
979 struct scatterlist *sg;
984 if (vmalloced_buf || kmap_buf) {
985 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
986 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
987 } else if (virt_addr_valid(buf)) {
988 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
989 sgs = DIV_ROUND_UP(len, desc_len);
994 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
999 for (i = 0; i < sgs; i++) {
1001 if (vmalloced_buf || kmap_buf) {
1003 * Next scatterlist entry size is the minimum between
1004 * the desc_len and the remaining buffer length that
1007 min = min_t(size_t, desc_len,
1009 PAGE_SIZE - offset_in_page(buf)));
1011 vm_page = vmalloc_to_page(buf);
1013 vm_page = kmap_to_page(buf);
1018 sg_set_page(sg, vm_page,
1019 min, offset_in_page(buf));
1021 min = min_t(size_t, len, desc_len);
1023 sg_set_buf(sg, sg_buf, min);
1031 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
1044 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
1045 struct sg_table *sgt, enum dma_data_direction dir)
1047 if (sgt->orig_nents) {
1048 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
1053 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1055 struct device *tx_dev, *rx_dev;
1056 struct spi_transfer *xfer;
1063 tx_dev = ctlr->dma_tx->device->dev;
1064 else if (ctlr->dma_map_dev)
1065 tx_dev = ctlr->dma_map_dev;
1067 tx_dev = ctlr->dev.parent;
1070 rx_dev = ctlr->dma_rx->device->dev;
1071 else if (ctlr->dma_map_dev)
1072 rx_dev = ctlr->dma_map_dev;
1074 rx_dev = ctlr->dev.parent;
1076 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1077 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1080 if (xfer->tx_buf != NULL) {
1081 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
1082 (void *)xfer->tx_buf, xfer->len,
1088 if (xfer->rx_buf != NULL) {
1089 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
1090 xfer->rx_buf, xfer->len,
1093 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
1100 ctlr->cur_msg_mapped = true;
1105 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1107 struct spi_transfer *xfer;
1108 struct device *tx_dev, *rx_dev;
1110 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1114 tx_dev = ctlr->dma_tx->device->dev;
1115 else if (ctlr->dma_map_dev)
1116 tx_dev = ctlr->dma_map_dev;
1118 tx_dev = ctlr->dev.parent;
1121 rx_dev = ctlr->dma_rx->device->dev;
1122 else if (ctlr->dma_map_dev)
1123 rx_dev = ctlr->dma_map_dev;
1125 rx_dev = ctlr->dev.parent;
1127 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1128 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1131 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1132 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1135 ctlr->cur_msg_mapped = false;
1139 #else /* !CONFIG_HAS_DMA */
1140 static inline int __spi_map_msg(struct spi_controller *ctlr,
1141 struct spi_message *msg)
1146 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1147 struct spi_message *msg)
1151 #endif /* !CONFIG_HAS_DMA */
1153 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1154 struct spi_message *msg)
1156 struct spi_transfer *xfer;
1158 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1160 * Restore the original value of tx_buf or rx_buf if they are
1163 if (xfer->tx_buf == ctlr->dummy_tx)
1164 xfer->tx_buf = NULL;
1165 if (xfer->rx_buf == ctlr->dummy_rx)
1166 xfer->rx_buf = NULL;
1169 return __spi_unmap_msg(ctlr, msg);
1172 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1174 struct spi_transfer *xfer;
1176 unsigned int max_tx, max_rx;
1178 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1179 && !(msg->spi->mode & SPI_3WIRE)) {
1183 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1184 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1186 max_tx = max(xfer->len, max_tx);
1187 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1189 max_rx = max(xfer->len, max_rx);
1193 tmp = krealloc(ctlr->dummy_tx, max_tx,
1194 GFP_KERNEL | GFP_DMA | __GFP_ZERO);
1197 ctlr->dummy_tx = tmp;
1201 tmp = krealloc(ctlr->dummy_rx, max_rx,
1202 GFP_KERNEL | GFP_DMA);
1205 ctlr->dummy_rx = tmp;
1208 if (max_tx || max_rx) {
1209 list_for_each_entry(xfer, &msg->transfers,
1214 xfer->tx_buf = ctlr->dummy_tx;
1216 xfer->rx_buf = ctlr->dummy_rx;
1221 return __spi_map_msg(ctlr, msg);
1224 static int spi_transfer_wait(struct spi_controller *ctlr,
1225 struct spi_message *msg,
1226 struct spi_transfer *xfer)
1228 struct spi_statistics *statm = &ctlr->statistics;
1229 struct spi_statistics *stats = &msg->spi->statistics;
1230 u32 speed_hz = xfer->speed_hz;
1231 unsigned long long ms;
1233 if (spi_controller_is_slave(ctlr)) {
1234 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1235 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1243 * For each byte we wait for 8 cycles of the SPI clock.
1244 * Since speed is defined in Hz and we want milliseconds,
1245 * use respective multiplier, but before the division,
1246 * otherwise we may get 0 for short transfers.
1248 ms = 8LL * MSEC_PER_SEC * xfer->len;
1249 do_div(ms, speed_hz);
1252 * Increase it twice and add 200 ms tolerance, use
1253 * predefined maximum in case of overflow.
1259 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1260 msecs_to_jiffies(ms));
1263 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1264 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1265 dev_err(&msg->spi->dev,
1266 "SPI transfer timed out\n");
1274 static void _spi_transfer_delay_ns(u32 ns)
1278 if (ns <= NSEC_PER_USEC) {
1281 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1286 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1290 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1292 u32 delay = _delay->value;
1293 u32 unit = _delay->unit;
1300 case SPI_DELAY_UNIT_USECS:
1301 delay *= NSEC_PER_USEC;
1303 case SPI_DELAY_UNIT_NSECS:
1304 /* Nothing to do here */
1306 case SPI_DELAY_UNIT_SCK:
1307 /* clock cycles need to be obtained from spi_transfer */
1311 * If there is unknown effective speed, approximate it
1312 * by underestimating with half of the requested hz.
1314 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1318 /* Convert delay to nanoseconds */
1319 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1327 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1329 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1338 delay = spi_delay_to_ns(_delay, xfer);
1342 _spi_transfer_delay_ns(delay);
1346 EXPORT_SYMBOL_GPL(spi_delay_exec);
1348 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1349 struct spi_transfer *xfer)
1351 u32 default_delay_ns = 10 * NSEC_PER_USEC;
1352 u32 delay = xfer->cs_change_delay.value;
1353 u32 unit = xfer->cs_change_delay.unit;
1356 /* return early on "fast" mode - for everything but USECS */
1358 if (unit == SPI_DELAY_UNIT_USECS)
1359 _spi_transfer_delay_ns(default_delay_ns);
1363 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1365 dev_err_once(&msg->spi->dev,
1366 "Use of unsupported delay unit %i, using default of %luus\n",
1367 unit, default_delay_ns / NSEC_PER_USEC);
1368 _spi_transfer_delay_ns(default_delay_ns);
1373 * spi_transfer_one_message - Default implementation of transfer_one_message()
1375 * This is a standard implementation of transfer_one_message() for
1376 * drivers which implement a transfer_one() operation. It provides
1377 * standard handling of delays and chip select management.
1379 static int spi_transfer_one_message(struct spi_controller *ctlr,
1380 struct spi_message *msg)
1382 struct spi_transfer *xfer;
1383 bool keep_cs = false;
1385 struct spi_statistics *statm = &ctlr->statistics;
1386 struct spi_statistics *stats = &msg->spi->statistics;
1388 spi_set_cs(msg->spi, true, false);
1390 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1391 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1393 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1394 trace_spi_transfer_start(msg, xfer);
1396 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1397 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1399 if (!ctlr->ptp_sts_supported) {
1400 xfer->ptp_sts_word_pre = 0;
1401 ptp_read_system_prets(xfer->ptp_sts);
1404 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1405 reinit_completion(&ctlr->xfer_completion);
1408 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1410 if (ctlr->cur_msg_mapped &&
1411 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1412 __spi_unmap_msg(ctlr, msg);
1413 ctlr->fallback = true;
1414 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1418 SPI_STATISTICS_INCREMENT_FIELD(statm,
1420 SPI_STATISTICS_INCREMENT_FIELD(stats,
1422 dev_err(&msg->spi->dev,
1423 "SPI transfer failed: %d\n", ret);
1428 ret = spi_transfer_wait(ctlr, msg, xfer);
1434 dev_err(&msg->spi->dev,
1435 "Bufferless transfer has length %u\n",
1439 if (!ctlr->ptp_sts_supported) {
1440 ptp_read_system_postts(xfer->ptp_sts);
1441 xfer->ptp_sts_word_post = xfer->len;
1444 trace_spi_transfer_stop(msg, xfer);
1446 if (msg->status != -EINPROGRESS)
1449 spi_transfer_delay_exec(xfer);
1451 if (xfer->cs_change) {
1452 if (list_is_last(&xfer->transfer_list,
1456 spi_set_cs(msg->spi, false, false);
1457 _spi_transfer_cs_change_delay(msg, xfer);
1458 spi_set_cs(msg->spi, true, false);
1462 msg->actual_length += xfer->len;
1466 if (ret != 0 || !keep_cs)
1467 spi_set_cs(msg->spi, false, false);
1469 if (msg->status == -EINPROGRESS)
1472 if (msg->status && ctlr->handle_err)
1473 ctlr->handle_err(ctlr, msg);
1475 spi_finalize_current_message(ctlr);
1481 * spi_finalize_current_transfer - report completion of a transfer
1482 * @ctlr: the controller reporting completion
1484 * Called by SPI drivers using the core transfer_one_message()
1485 * implementation to notify it that the current interrupt driven
1486 * transfer has finished and the next one may be scheduled.
1488 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1490 complete(&ctlr->xfer_completion);
1492 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1494 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1496 if (ctlr->auto_runtime_pm) {
1497 pm_runtime_mark_last_busy(ctlr->dev.parent);
1498 pm_runtime_put_autosuspend(ctlr->dev.parent);
1503 * __spi_pump_messages - function which processes spi message queue
1504 * @ctlr: controller to process queue for
1505 * @in_kthread: true if we are in the context of the message pump thread
1507 * This function checks if there is any spi message in the queue that
1508 * needs processing and if so call out to the driver to initialize hardware
1509 * and transfer each message.
1511 * Note that it is called both from the kthread itself and also from
1512 * inside spi_sync(); the queue extraction handling at the top of the
1513 * function should deal with this safely.
1515 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1517 struct spi_transfer *xfer;
1518 struct spi_message *msg;
1519 bool was_busy = false;
1520 unsigned long flags;
1524 spin_lock_irqsave(&ctlr->queue_lock, flags);
1526 /* Make sure we are not already running a message */
1527 if (ctlr->cur_msg) {
1528 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1532 /* If another context is idling the device then defer */
1534 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1535 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1539 /* Check if the queue is idle */
1540 if (list_empty(&ctlr->queue) || !ctlr->running) {
1542 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1546 /* Defer any non-atomic teardown to the thread */
1548 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1549 !ctlr->unprepare_transfer_hardware) {
1550 spi_idle_runtime_pm(ctlr);
1552 trace_spi_controller_idle(ctlr);
1554 kthread_queue_work(ctlr->kworker,
1555 &ctlr->pump_messages);
1557 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1562 ctlr->idling = true;
1563 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1565 kfree(ctlr->dummy_rx);
1566 ctlr->dummy_rx = NULL;
1567 kfree(ctlr->dummy_tx);
1568 ctlr->dummy_tx = NULL;
1569 if (ctlr->unprepare_transfer_hardware &&
1570 ctlr->unprepare_transfer_hardware(ctlr))
1572 "failed to unprepare transfer hardware\n");
1573 spi_idle_runtime_pm(ctlr);
1574 trace_spi_controller_idle(ctlr);
1576 spin_lock_irqsave(&ctlr->queue_lock, flags);
1577 ctlr->idling = false;
1578 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1582 /* Extract head of queue */
1583 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1584 ctlr->cur_msg = msg;
1586 list_del_init(&msg->queue);
1591 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1593 mutex_lock(&ctlr->io_mutex);
1595 if (!was_busy && ctlr->auto_runtime_pm) {
1596 ret = pm_runtime_resume_and_get(ctlr->dev.parent);
1598 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1600 mutex_unlock(&ctlr->io_mutex);
1606 trace_spi_controller_busy(ctlr);
1608 if (!was_busy && ctlr->prepare_transfer_hardware) {
1609 ret = ctlr->prepare_transfer_hardware(ctlr);
1612 "failed to prepare transfer hardware: %d\n",
1615 if (ctlr->auto_runtime_pm)
1616 pm_runtime_put(ctlr->dev.parent);
1619 spi_finalize_current_message(ctlr);
1621 mutex_unlock(&ctlr->io_mutex);
1626 trace_spi_message_start(msg);
1628 if (ctlr->prepare_message) {
1629 ret = ctlr->prepare_message(ctlr, msg);
1631 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1634 spi_finalize_current_message(ctlr);
1637 ctlr->cur_msg_prepared = true;
1640 ret = spi_map_msg(ctlr, msg);
1643 spi_finalize_current_message(ctlr);
1647 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1648 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1649 xfer->ptp_sts_word_pre = 0;
1650 ptp_read_system_prets(xfer->ptp_sts);
1654 ret = ctlr->transfer_one_message(ctlr, msg);
1657 "failed to transfer one message from queue: %d\n",
1663 mutex_unlock(&ctlr->io_mutex);
1665 /* Prod the scheduler in case transfer_one() was busy waiting */
1671 * spi_pump_messages - kthread work function which processes spi message queue
1672 * @work: pointer to kthread work struct contained in the controller struct
1674 static void spi_pump_messages(struct kthread_work *work)
1676 struct spi_controller *ctlr =
1677 container_of(work, struct spi_controller, pump_messages);
1679 __spi_pump_messages(ctlr, true);
1683 * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1684 * @ctlr: Pointer to the spi_controller structure of the driver
1685 * @xfer: Pointer to the transfer being timestamped
1686 * @progress: How many words (not bytes) have been transferred so far
1687 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1688 * transfer, for less jitter in time measurement. Only compatible
1689 * with PIO drivers. If true, must follow up with
1690 * spi_take_timestamp_post or otherwise system will crash.
1691 * WARNING: for fully predictable results, the CPU frequency must
1692 * also be under control (governor).
1694 * This is a helper for drivers to collect the beginning of the TX timestamp
1695 * for the requested byte from the SPI transfer. The frequency with which this
1696 * function must be called (once per word, once for the whole transfer, once
1697 * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1698 * greater than or equal to the requested byte at the time of the call. The
1699 * timestamp is only taken once, at the first such call. It is assumed that
1700 * the driver advances its @tx buffer pointer monotonically.
1702 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1703 struct spi_transfer *xfer,
1704 size_t progress, bool irqs_off)
1709 if (xfer->timestamped)
1712 if (progress > xfer->ptp_sts_word_pre)
1715 /* Capture the resolution of the timestamp */
1716 xfer->ptp_sts_word_pre = progress;
1719 local_irq_save(ctlr->irq_flags);
1723 ptp_read_system_prets(xfer->ptp_sts);
1725 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1728 * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1729 * @ctlr: Pointer to the spi_controller structure of the driver
1730 * @xfer: Pointer to the transfer being timestamped
1731 * @progress: How many words (not bytes) have been transferred so far
1732 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1734 * This is a helper for drivers to collect the end of the TX timestamp for
1735 * the requested byte from the SPI transfer. Can be called with an arbitrary
1736 * frequency: only the first call where @tx exceeds or is equal to the
1737 * requested word will be timestamped.
1739 void spi_take_timestamp_post(struct spi_controller *ctlr,
1740 struct spi_transfer *xfer,
1741 size_t progress, bool irqs_off)
1746 if (xfer->timestamped)
1749 if (progress < xfer->ptp_sts_word_post)
1752 ptp_read_system_postts(xfer->ptp_sts);
1755 local_irq_restore(ctlr->irq_flags);
1759 /* Capture the resolution of the timestamp */
1760 xfer->ptp_sts_word_post = progress;
1762 xfer->timestamped = true;
1764 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1767 * spi_set_thread_rt - set the controller to pump at realtime priority
1768 * @ctlr: controller to boost priority of
1770 * This can be called because the controller requested realtime priority
1771 * (by setting the ->rt value before calling spi_register_controller()) or
1772 * because a device on the bus said that its transfers needed realtime
1775 * NOTE: at the moment if any device on a bus says it needs realtime then
1776 * the thread will be at realtime priority for all transfers on that
1777 * controller. If this eventually becomes a problem we may see if we can
1778 * find a way to boost the priority only temporarily during relevant
1781 static void spi_set_thread_rt(struct spi_controller *ctlr)
1783 dev_info(&ctlr->dev,
1784 "will run message pump with realtime priority\n");
1785 sched_set_fifo(ctlr->kworker->task);
1788 static int spi_init_queue(struct spi_controller *ctlr)
1790 ctlr->running = false;
1793 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1794 if (IS_ERR(ctlr->kworker)) {
1795 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1796 return PTR_ERR(ctlr->kworker);
1799 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1802 * Controller config will indicate if this controller should run the
1803 * message pump with high (realtime) priority to reduce the transfer
1804 * latency on the bus by minimising the delay between a transfer
1805 * request and the scheduling of the message pump thread. Without this
1806 * setting the message pump thread will remain at default priority.
1809 spi_set_thread_rt(ctlr);
1815 * spi_get_next_queued_message() - called by driver to check for queued
1817 * @ctlr: the controller to check for queued messages
1819 * If there are more messages in the queue, the next message is returned from
1822 * Return: the next message in the queue, else NULL if the queue is empty.
1824 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1826 struct spi_message *next;
1827 unsigned long flags;
1829 /* get a pointer to the next message, if any */
1830 spin_lock_irqsave(&ctlr->queue_lock, flags);
1831 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1833 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1837 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1840 * spi_finalize_current_message() - the current message is complete
1841 * @ctlr: the controller to return the message to
1843 * Called by the driver to notify the core that the message in the front of the
1844 * queue is complete and can be removed from the queue.
1846 void spi_finalize_current_message(struct spi_controller *ctlr)
1848 struct spi_transfer *xfer;
1849 struct spi_message *mesg;
1850 unsigned long flags;
1853 spin_lock_irqsave(&ctlr->queue_lock, flags);
1854 mesg = ctlr->cur_msg;
1855 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1857 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1858 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1859 ptp_read_system_postts(xfer->ptp_sts);
1860 xfer->ptp_sts_word_post = xfer->len;
1864 if (unlikely(ctlr->ptp_sts_supported))
1865 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1866 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1868 spi_unmap_msg(ctlr, mesg);
1871 * In the prepare_messages callback the SPI bus has the opportunity
1872 * to split a transfer to smaller chunks.
1874 * Release the split transfers here since spi_map_msg() is done on
1875 * the split transfers.
1877 spi_res_release(ctlr, mesg);
1879 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1880 ret = ctlr->unprepare_message(ctlr, mesg);
1882 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1887 spin_lock_irqsave(&ctlr->queue_lock, flags);
1888 ctlr->cur_msg = NULL;
1889 ctlr->cur_msg_prepared = false;
1890 ctlr->fallback = false;
1891 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1892 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1894 trace_spi_message_done(mesg);
1898 mesg->complete(mesg->context);
1900 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1902 static int spi_start_queue(struct spi_controller *ctlr)
1904 unsigned long flags;
1906 spin_lock_irqsave(&ctlr->queue_lock, flags);
1908 if (ctlr->running || ctlr->busy) {
1909 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1913 ctlr->running = true;
1914 ctlr->cur_msg = NULL;
1915 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1917 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1922 static int spi_stop_queue(struct spi_controller *ctlr)
1924 unsigned long flags;
1925 unsigned limit = 500;
1928 spin_lock_irqsave(&ctlr->queue_lock, flags);
1931 * This is a bit lame, but is optimized for the common execution path.
1932 * A wait_queue on the ctlr->busy could be used, but then the common
1933 * execution path (pump_messages) would be required to call wake_up or
1934 * friends on every SPI message. Do this instead.
1936 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1937 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1938 usleep_range(10000, 11000);
1939 spin_lock_irqsave(&ctlr->queue_lock, flags);
1942 if (!list_empty(&ctlr->queue) || ctlr->busy)
1945 ctlr->running = false;
1947 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1950 dev_warn(&ctlr->dev, "could not stop message queue\n");
1956 static int spi_destroy_queue(struct spi_controller *ctlr)
1960 ret = spi_stop_queue(ctlr);
1963 * kthread_flush_worker will block until all work is done.
1964 * If the reason that stop_queue timed out is that the work will never
1965 * finish, then it does no good to call flush/stop thread, so
1969 dev_err(&ctlr->dev, "problem destroying queue\n");
1973 kthread_destroy_worker(ctlr->kworker);
1978 static int __spi_queued_transfer(struct spi_device *spi,
1979 struct spi_message *msg,
1982 struct spi_controller *ctlr = spi->controller;
1983 unsigned long flags;
1985 spin_lock_irqsave(&ctlr->queue_lock, flags);
1987 if (!ctlr->running) {
1988 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1991 msg->actual_length = 0;
1992 msg->status = -EINPROGRESS;
1994 list_add_tail(&msg->queue, &ctlr->queue);
1995 if (!ctlr->busy && need_pump)
1996 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1998 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2003 * spi_queued_transfer - transfer function for queued transfers
2004 * @spi: spi device which is requesting transfer
2005 * @msg: spi message which is to handled is queued to driver queue
2007 * Return: zero on success, else a negative error code.
2009 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
2011 return __spi_queued_transfer(spi, msg, true);
2014 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2018 ctlr->transfer = spi_queued_transfer;
2019 if (!ctlr->transfer_one_message)
2020 ctlr->transfer_one_message = spi_transfer_one_message;
2022 /* Initialize and start queue */
2023 ret = spi_init_queue(ctlr);
2025 dev_err(&ctlr->dev, "problem initializing queue\n");
2026 goto err_init_queue;
2028 ctlr->queued = true;
2029 ret = spi_start_queue(ctlr);
2031 dev_err(&ctlr->dev, "problem starting queue\n");
2032 goto err_start_queue;
2038 spi_destroy_queue(ctlr);
2044 * spi_flush_queue - Send all pending messages in the queue from the callers'
2046 * @ctlr: controller to process queue for
2048 * This should be used when one wants to ensure all pending messages have been
2049 * sent before doing something. Is used by the spi-mem code to make sure SPI
2050 * memory operations do not preempt regular SPI transfers that have been queued
2051 * before the spi-mem operation.
2053 void spi_flush_queue(struct spi_controller *ctlr)
2055 if (ctlr->transfer == spi_queued_transfer)
2056 __spi_pump_messages(ctlr, false);
2059 /*-------------------------------------------------------------------------*/
2061 #if defined(CONFIG_OF)
2062 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2063 struct device_node *nc)
2068 /* Mode (clock phase/polarity/etc.) */
2069 if (of_property_read_bool(nc, "spi-cpha"))
2070 spi->mode |= SPI_CPHA;
2071 if (of_property_read_bool(nc, "spi-cpol"))
2072 spi->mode |= SPI_CPOL;
2073 if (of_property_read_bool(nc, "spi-3wire"))
2074 spi->mode |= SPI_3WIRE;
2075 if (of_property_read_bool(nc, "spi-lsb-first"))
2076 spi->mode |= SPI_LSB_FIRST;
2077 if (of_property_read_bool(nc, "spi-cs-high"))
2078 spi->mode |= SPI_CS_HIGH;
2080 /* Device DUAL/QUAD mode */
2081 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2084 spi->mode |= SPI_NO_TX;
2089 spi->mode |= SPI_TX_DUAL;
2092 spi->mode |= SPI_TX_QUAD;
2095 spi->mode |= SPI_TX_OCTAL;
2098 dev_warn(&ctlr->dev,
2099 "spi-tx-bus-width %d not supported\n",
2105 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2108 spi->mode |= SPI_NO_RX;
2113 spi->mode |= SPI_RX_DUAL;
2116 spi->mode |= SPI_RX_QUAD;
2119 spi->mode |= SPI_RX_OCTAL;
2122 dev_warn(&ctlr->dev,
2123 "spi-rx-bus-width %d not supported\n",
2129 if (spi_controller_is_slave(ctlr)) {
2130 if (!of_node_name_eq(nc, "slave")) {
2131 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2138 /* Device address */
2139 rc = of_property_read_u32(nc, "reg", &value);
2141 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2145 spi->chip_select = value;
2148 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2149 spi->max_speed_hz = value;
2154 static struct spi_device *
2155 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2157 struct spi_device *spi;
2160 /* Alloc an spi_device */
2161 spi = spi_alloc_device(ctlr);
2163 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2168 /* Select device driver */
2169 rc = of_modalias_node(nc, spi->modalias,
2170 sizeof(spi->modalias));
2172 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2176 rc = of_spi_parse_dt(ctlr, spi, nc);
2180 /* Store a pointer to the node in the device structure */
2182 spi->dev.of_node = nc;
2183 spi->dev.fwnode = of_fwnode_handle(nc);
2185 /* Register the new device */
2186 rc = spi_add_device(spi);
2188 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2189 goto err_of_node_put;
2202 * of_register_spi_devices() - Register child devices onto the SPI bus
2203 * @ctlr: Pointer to spi_controller device
2205 * Registers an spi_device for each child node of controller node which
2206 * represents a valid SPI slave.
2208 static void of_register_spi_devices(struct spi_controller *ctlr)
2210 struct spi_device *spi;
2211 struct device_node *nc;
2213 if (!ctlr->dev.of_node)
2216 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2217 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2219 spi = of_register_spi_device(ctlr, nc);
2221 dev_warn(&ctlr->dev,
2222 "Failed to create SPI device for %pOF\n", nc);
2223 of_node_clear_flag(nc, OF_POPULATED);
2228 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2232 * spi_new_ancillary_device() - Register ancillary SPI device
2233 * @spi: Pointer to the main SPI device registering the ancillary device
2234 * @chip_select: Chip Select of the ancillary device
2236 * Register an ancillary SPI device; for example some chips have a chip-select
2237 * for normal device usage and another one for setup/firmware upload.
2239 * This may only be called from main SPI device's probe routine.
2241 * Return: 0 on success; negative errno on failure
2243 struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2246 struct spi_device *ancillary;
2249 /* Alloc an spi_device */
2250 ancillary = spi_alloc_device(spi->controller);
2256 strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2258 /* Use provided chip-select for ancillary device */
2259 ancillary->chip_select = chip_select;
2261 /* Take over SPI mode/speed from SPI main device */
2262 ancillary->max_speed_hz = spi->max_speed_hz;
2263 ancillary->mode = spi->mode;
2265 /* Register the new device */
2266 rc = spi_add_device_locked(ancillary);
2268 dev_err(&spi->dev, "failed to register ancillary device\n");
2275 spi_dev_put(ancillary);
2278 EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2281 struct acpi_spi_lookup {
2282 struct spi_controller *ctlr;
2292 static int acpi_spi_count(struct acpi_resource *ares, void *data)
2294 struct acpi_resource_spi_serialbus *sb;
2297 if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2300 sb = &ares->data.spi_serial_bus;
2301 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2304 *count = *count + 1;
2310 * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2311 * @adev: ACPI device
2313 * Returns the number of SpiSerialBus resources in the ACPI-device's
2314 * resource-list; or a negative error code.
2316 int acpi_spi_count_resources(struct acpi_device *adev)
2322 ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2326 acpi_dev_free_resource_list(&r);
2330 EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2332 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2333 struct acpi_spi_lookup *lookup)
2335 const union acpi_object *obj;
2337 if (!x86_apple_machine)
2340 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2341 && obj->buffer.length >= 4)
2342 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2344 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2345 && obj->buffer.length == 8)
2346 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2348 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2349 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2350 lookup->mode |= SPI_LSB_FIRST;
2352 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2353 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2354 lookup->mode |= SPI_CPOL;
2356 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2357 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2358 lookup->mode |= SPI_CPHA;
2361 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
2363 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2365 struct acpi_spi_lookup *lookup = data;
2366 struct spi_controller *ctlr = lookup->ctlr;
2368 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2369 struct acpi_resource_spi_serialbus *sb;
2370 acpi_handle parent_handle;
2373 sb = &ares->data.spi_serial_bus;
2374 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2376 if (lookup->index != -1 && lookup->n++ != lookup->index)
2379 if (lookup->index == -1 && !ctlr)
2382 status = acpi_get_handle(NULL,
2383 sb->resource_source.string_ptr,
2386 if (ACPI_FAILURE(status))
2390 if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2393 struct acpi_device *adev;
2395 adev = acpi_fetch_acpi_dev(parent_handle);
2399 ctlr = acpi_spi_find_controller_by_adev(adev);
2403 lookup->ctlr = ctlr;
2407 * ACPI DeviceSelection numbering is handled by the
2408 * host controller driver in Windows and can vary
2409 * from driver to driver. In Linux we always expect
2410 * 0 .. max - 1 so we need to ask the driver to
2411 * translate between the two schemes.
2413 if (ctlr->fw_translate_cs) {
2414 int cs = ctlr->fw_translate_cs(ctlr,
2415 sb->device_selection);
2418 lookup->chip_select = cs;
2420 lookup->chip_select = sb->device_selection;
2423 lookup->max_speed_hz = sb->connection_speed;
2424 lookup->bits_per_word = sb->data_bit_length;
2426 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2427 lookup->mode |= SPI_CPHA;
2428 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2429 lookup->mode |= SPI_CPOL;
2430 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2431 lookup->mode |= SPI_CS_HIGH;
2433 } else if (lookup->irq < 0) {
2436 if (acpi_dev_resource_interrupt(ares, 0, &r))
2437 lookup->irq = r.start;
2440 /* Always tell the ACPI core to skip this resource */
2445 * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2446 * @ctlr: controller to which the spi device belongs
2447 * @adev: ACPI Device for the spi device
2448 * @index: Index of the spi resource inside the ACPI Node
2450 * This should be used to allocate a new spi device from and ACPI Node.
2451 * The caller is responsible for calling spi_add_device to register the spi device.
2453 * If ctlr is set to NULL, the Controller for the spi device will be looked up
2454 * using the resource.
2455 * If index is set to -1, index is not used.
2456 * Note: If index is -1, ctlr must be set.
2458 * Return: a pointer to the new device, or ERR_PTR on error.
2460 struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
2461 struct acpi_device *adev,
2464 acpi_handle parent_handle = NULL;
2465 struct list_head resource_list;
2466 struct acpi_spi_lookup lookup = {};
2467 struct spi_device *spi;
2470 if (!ctlr && index == -1)
2471 return ERR_PTR(-EINVAL);
2475 lookup.index = index;
2478 INIT_LIST_HEAD(&resource_list);
2479 ret = acpi_dev_get_resources(adev, &resource_list,
2480 acpi_spi_add_resource, &lookup);
2481 acpi_dev_free_resource_list(&resource_list);
2484 /* found SPI in _CRS but it points to another controller */
2485 return ERR_PTR(-ENODEV);
2487 if (!lookup.max_speed_hz &&
2488 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2489 ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
2490 /* Apple does not use _CRS but nested devices for SPI slaves */
2491 acpi_spi_parse_apple_properties(adev, &lookup);
2494 if (!lookup.max_speed_hz)
2495 return ERR_PTR(-ENODEV);
2497 spi = spi_alloc_device(lookup.ctlr);
2499 dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
2500 dev_name(&adev->dev));
2501 return ERR_PTR(-ENOMEM);
2504 ACPI_COMPANION_SET(&spi->dev, adev);
2505 spi->max_speed_hz = lookup.max_speed_hz;
2506 spi->mode |= lookup.mode;
2507 spi->irq = lookup.irq;
2508 spi->bits_per_word = lookup.bits_per_word;
2509 spi->chip_select = lookup.chip_select;
2513 EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2515 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2516 struct acpi_device *adev)
2518 struct spi_device *spi;
2520 if (acpi_bus_get_status(adev) || !adev->status.present ||
2521 acpi_device_enumerated(adev))
2524 spi = acpi_spi_device_alloc(ctlr, adev, -1);
2526 if (PTR_ERR(spi) == -ENOMEM)
2527 return AE_NO_MEMORY;
2532 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2533 sizeof(spi->modalias));
2536 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2538 acpi_device_set_enumerated(adev);
2540 adev->power.flags.ignore_parent = true;
2541 if (spi_add_device(spi)) {
2542 adev->power.flags.ignore_parent = false;
2543 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2544 dev_name(&adev->dev));
2551 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2552 void *data, void **return_value)
2554 struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
2555 struct spi_controller *ctlr = data;
2560 return acpi_register_spi_device(ctlr, adev);
2563 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2565 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2570 handle = ACPI_HANDLE(ctlr->dev.parent);
2574 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2575 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2576 acpi_spi_add_device, NULL, ctlr, NULL);
2577 if (ACPI_FAILURE(status))
2578 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2581 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2582 #endif /* CONFIG_ACPI */
2584 static void spi_controller_release(struct device *dev)
2586 struct spi_controller *ctlr;
2588 ctlr = container_of(dev, struct spi_controller, dev);
2592 static struct class spi_master_class = {
2593 .name = "spi_master",
2594 .owner = THIS_MODULE,
2595 .dev_release = spi_controller_release,
2596 .dev_groups = spi_master_groups,
2599 #ifdef CONFIG_SPI_SLAVE
2601 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2603 * @spi: device used for the current transfer
2605 int spi_slave_abort(struct spi_device *spi)
2607 struct spi_controller *ctlr = spi->controller;
2609 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2610 return ctlr->slave_abort(ctlr);
2614 EXPORT_SYMBOL_GPL(spi_slave_abort);
2616 static int match_true(struct device *dev, void *data)
2621 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2624 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2626 struct device *child;
2628 child = device_find_child(&ctlr->dev, NULL, match_true);
2629 return sprintf(buf, "%s\n",
2630 child ? to_spi_device(child)->modalias : NULL);
2633 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2634 const char *buf, size_t count)
2636 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2638 struct spi_device *spi;
2639 struct device *child;
2643 rc = sscanf(buf, "%31s", name);
2644 if (rc != 1 || !name[0])
2647 child = device_find_child(&ctlr->dev, NULL, match_true);
2649 /* Remove registered slave */
2650 device_unregister(child);
2654 if (strcmp(name, "(null)")) {
2655 /* Register new slave */
2656 spi = spi_alloc_device(ctlr);
2660 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2662 rc = spi_add_device(spi);
2672 static DEVICE_ATTR_RW(slave);
2674 static struct attribute *spi_slave_attrs[] = {
2675 &dev_attr_slave.attr,
2679 static const struct attribute_group spi_slave_group = {
2680 .attrs = spi_slave_attrs,
2683 static const struct attribute_group *spi_slave_groups[] = {
2684 &spi_controller_statistics_group,
2689 static struct class spi_slave_class = {
2690 .name = "spi_slave",
2691 .owner = THIS_MODULE,
2692 .dev_release = spi_controller_release,
2693 .dev_groups = spi_slave_groups,
2696 extern struct class spi_slave_class; /* dummy */
2700 * __spi_alloc_controller - allocate an SPI master or slave controller
2701 * @dev: the controller, possibly using the platform_bus
2702 * @size: how much zeroed driver-private data to allocate; the pointer to this
2703 * memory is in the driver_data field of the returned device, accessible
2704 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2705 * drivers granting DMA access to portions of their private data need to
2706 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2707 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2708 * slave (true) controller
2709 * Context: can sleep
2711 * This call is used only by SPI controller drivers, which are the
2712 * only ones directly touching chip registers. It's how they allocate
2713 * an spi_controller structure, prior to calling spi_register_controller().
2715 * This must be called from context that can sleep.
2717 * The caller is responsible for assigning the bus number and initializing the
2718 * controller's methods before calling spi_register_controller(); and (after
2719 * errors adding the device) calling spi_controller_put() to prevent a memory
2722 * Return: the SPI controller structure on success, else NULL.
2724 struct spi_controller *__spi_alloc_controller(struct device *dev,
2725 unsigned int size, bool slave)
2727 struct spi_controller *ctlr;
2728 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2733 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2737 device_initialize(&ctlr->dev);
2738 INIT_LIST_HEAD(&ctlr->queue);
2739 spin_lock_init(&ctlr->queue_lock);
2740 spin_lock_init(&ctlr->bus_lock_spinlock);
2741 mutex_init(&ctlr->bus_lock_mutex);
2742 mutex_init(&ctlr->io_mutex);
2743 mutex_init(&ctlr->add_lock);
2745 ctlr->num_chipselect = 1;
2746 ctlr->slave = slave;
2747 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2748 ctlr->dev.class = &spi_slave_class;
2750 ctlr->dev.class = &spi_master_class;
2751 ctlr->dev.parent = dev;
2752 pm_suspend_ignore_children(&ctlr->dev, true);
2753 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2757 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2759 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2761 spi_controller_put(*(struct spi_controller **)ctlr);
2765 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2766 * @dev: physical device of SPI controller
2767 * @size: how much zeroed driver-private data to allocate
2768 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2769 * Context: can sleep
2771 * Allocate an SPI controller and automatically release a reference on it
2772 * when @dev is unbound from its driver. Drivers are thus relieved from
2773 * having to call spi_controller_put().
2775 * The arguments to this function are identical to __spi_alloc_controller().
2777 * Return: the SPI controller structure on success, else NULL.
2779 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2783 struct spi_controller **ptr, *ctlr;
2785 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2790 ctlr = __spi_alloc_controller(dev, size, slave);
2792 ctlr->devm_allocated = true;
2794 devres_add(dev, ptr);
2801 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2804 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2805 * @ctlr: The SPI master to grab GPIO descriptors for
2807 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2810 struct gpio_desc **cs;
2811 struct device *dev = &ctlr->dev;
2812 unsigned long native_cs_mask = 0;
2813 unsigned int num_cs_gpios = 0;
2815 nb = gpiod_count(dev, "cs");
2817 /* No GPIOs at all is fine, else return the error */
2823 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2825 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2829 ctlr->cs_gpiods = cs;
2831 for (i = 0; i < nb; i++) {
2833 * Most chipselects are active low, the inverted
2834 * semantics are handled by special quirks in gpiolib,
2835 * so initializing them GPIOD_OUT_LOW here means
2836 * "unasserted", in most cases this will drive the physical
2839 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2842 return PTR_ERR(cs[i]);
2846 * If we find a CS GPIO, name it after the device and
2851 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2855 gpiod_set_consumer_name(cs[i], gpioname);
2860 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2861 dev_err(dev, "Invalid native chip select %d\n", i);
2864 native_cs_mask |= BIT(i);
2867 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2869 if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2870 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2871 dev_err(dev, "No unused native chip select available\n");
2878 static int spi_controller_check_ops(struct spi_controller *ctlr)
2881 * The controller may implement only the high-level SPI-memory like
2882 * operations if it does not support regular SPI transfers, and this is
2884 * If ->mem_ops is NULL, we request that at least one of the
2885 * ->transfer_xxx() method be implemented.
2887 if (ctlr->mem_ops) {
2888 if (!ctlr->mem_ops->exec_op)
2890 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2891 !ctlr->transfer_one_message) {
2899 * spi_register_controller - register SPI master or slave controller
2900 * @ctlr: initialized master, originally from spi_alloc_master() or
2902 * Context: can sleep
2904 * SPI controllers connect to their drivers using some non-SPI bus,
2905 * such as the platform bus. The final stage of probe() in that code
2906 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2908 * SPI controllers use board specific (often SOC specific) bus numbers,
2909 * and board-specific addressing for SPI devices combines those numbers
2910 * with chip select numbers. Since SPI does not directly support dynamic
2911 * device identification, boards need configuration tables telling which
2912 * chip is at which address.
2914 * This must be called from context that can sleep. It returns zero on
2915 * success, else a negative error code (dropping the controller's refcount).
2916 * After a successful return, the caller is responsible for calling
2917 * spi_unregister_controller().
2919 * Return: zero on success, else a negative error code.
2921 int spi_register_controller(struct spi_controller *ctlr)
2923 struct device *dev = ctlr->dev.parent;
2924 struct boardinfo *bi;
2926 int id, first_dynamic;
2932 * Make sure all necessary hooks are implemented before registering
2933 * the SPI controller.
2935 status = spi_controller_check_ops(ctlr);
2939 if (ctlr->bus_num >= 0) {
2940 /* devices with a fixed bus num must check-in with the num */
2941 mutex_lock(&board_lock);
2942 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2943 ctlr->bus_num + 1, GFP_KERNEL);
2944 mutex_unlock(&board_lock);
2945 if (WARN(id < 0, "couldn't get idr"))
2946 return id == -ENOSPC ? -EBUSY : id;
2948 } else if (ctlr->dev.of_node) {
2949 /* allocate dynamic bus number using Linux idr */
2950 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2953 mutex_lock(&board_lock);
2954 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2955 ctlr->bus_num + 1, GFP_KERNEL);
2956 mutex_unlock(&board_lock);
2957 if (WARN(id < 0, "couldn't get idr"))
2958 return id == -ENOSPC ? -EBUSY : id;
2961 if (ctlr->bus_num < 0) {
2962 first_dynamic = of_alias_get_highest_id("spi");
2963 if (first_dynamic < 0)
2968 mutex_lock(&board_lock);
2969 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2971 mutex_unlock(&board_lock);
2972 if (WARN(id < 0, "couldn't get idr"))
2976 ctlr->bus_lock_flag = 0;
2977 init_completion(&ctlr->xfer_completion);
2978 if (!ctlr->max_dma_len)
2979 ctlr->max_dma_len = INT_MAX;
2982 * Register the device, then userspace will see it.
2983 * Registration fails if the bus ID is in use.
2985 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2987 if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
2988 status = spi_get_gpio_descs(ctlr);
2992 * A controller using GPIO descriptors always
2993 * supports SPI_CS_HIGH if need be.
2995 ctlr->mode_bits |= SPI_CS_HIGH;
2999 * Even if it's just one always-selected device, there must
3000 * be at least one chipselect.
3002 if (!ctlr->num_chipselect) {
3007 /* setting last_cs to -1 means no chip selected */
3010 status = device_add(&ctlr->dev);
3013 dev_dbg(dev, "registered %s %s\n",
3014 spi_controller_is_slave(ctlr) ? "slave" : "master",
3015 dev_name(&ctlr->dev));
3018 * If we're using a queued driver, start the queue. Note that we don't
3019 * need the queueing logic if the driver is only supporting high-level
3020 * memory operations.
3022 if (ctlr->transfer) {
3023 dev_info(dev, "controller is unqueued, this is deprecated\n");
3024 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
3025 status = spi_controller_initialize_queue(ctlr);
3027 device_del(&ctlr->dev);
3031 /* add statistics */
3032 spin_lock_init(&ctlr->statistics.lock);
3034 mutex_lock(&board_lock);
3035 list_add_tail(&ctlr->list, &spi_controller_list);
3036 list_for_each_entry(bi, &board_list, list)
3037 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
3038 mutex_unlock(&board_lock);
3040 /* Register devices from the device tree and ACPI */
3041 of_register_spi_devices(ctlr);
3042 acpi_register_spi_devices(ctlr);
3046 mutex_lock(&board_lock);
3047 idr_remove(&spi_master_idr, ctlr->bus_num);
3048 mutex_unlock(&board_lock);
3051 EXPORT_SYMBOL_GPL(spi_register_controller);
3053 static void devm_spi_unregister(void *ctlr)
3055 spi_unregister_controller(ctlr);
3059 * devm_spi_register_controller - register managed SPI master or slave
3061 * @dev: device managing SPI controller
3062 * @ctlr: initialized controller, originally from spi_alloc_master() or
3064 * Context: can sleep
3066 * Register a SPI device as with spi_register_controller() which will
3067 * automatically be unregistered and freed.
3069 * Return: zero on success, else a negative error code.
3071 int devm_spi_register_controller(struct device *dev,
3072 struct spi_controller *ctlr)
3076 ret = spi_register_controller(ctlr);
3080 return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
3082 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3084 static int __unregister(struct device *dev, void *null)
3086 spi_unregister_device(to_spi_device(dev));
3091 * spi_unregister_controller - unregister SPI master or slave controller
3092 * @ctlr: the controller being unregistered
3093 * Context: can sleep
3095 * This call is used only by SPI controller drivers, which are the
3096 * only ones directly touching chip registers.
3098 * This must be called from context that can sleep.
3100 * Note that this function also drops a reference to the controller.
3102 void spi_unregister_controller(struct spi_controller *ctlr)
3104 struct spi_controller *found;
3105 int id = ctlr->bus_num;
3107 /* Prevent addition of new devices, unregister existing ones */
3108 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3109 mutex_lock(&ctlr->add_lock);
3111 device_for_each_child(&ctlr->dev, NULL, __unregister);
3113 /* First make sure that this controller was ever added */
3114 mutex_lock(&board_lock);
3115 found = idr_find(&spi_master_idr, id);
3116 mutex_unlock(&board_lock);
3118 if (spi_destroy_queue(ctlr))
3119 dev_err(&ctlr->dev, "queue remove failed\n");
3121 mutex_lock(&board_lock);
3122 list_del(&ctlr->list);
3123 mutex_unlock(&board_lock);
3125 device_del(&ctlr->dev);
3128 mutex_lock(&board_lock);
3130 idr_remove(&spi_master_idr, id);
3131 mutex_unlock(&board_lock);
3133 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3134 mutex_unlock(&ctlr->add_lock);
3136 /* Release the last reference on the controller if its driver
3137 * has not yet been converted to devm_spi_alloc_master/slave().
3139 if (!ctlr->devm_allocated)
3140 put_device(&ctlr->dev);
3142 EXPORT_SYMBOL_GPL(spi_unregister_controller);
3144 int spi_controller_suspend(struct spi_controller *ctlr)
3148 /* Basically no-ops for non-queued controllers */
3152 ret = spi_stop_queue(ctlr);
3154 dev_err(&ctlr->dev, "queue stop failed\n");
3158 EXPORT_SYMBOL_GPL(spi_controller_suspend);
3160 int spi_controller_resume(struct spi_controller *ctlr)
3167 ret = spi_start_queue(ctlr);
3169 dev_err(&ctlr->dev, "queue restart failed\n");
3173 EXPORT_SYMBOL_GPL(spi_controller_resume);
3175 /*-------------------------------------------------------------------------*/
3177 /* Core methods for spi_message alterations */
3179 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3180 struct spi_message *msg,
3183 struct spi_replaced_transfers *rxfer = res;
3186 /* call extra callback if requested */
3188 rxfer->release(ctlr, msg, res);
3190 /* insert replaced transfers back into the message */
3191 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3193 /* remove the formerly inserted entries */
3194 for (i = 0; i < rxfer->inserted; i++)
3195 list_del(&rxfer->inserted_transfers[i].transfer_list);
3199 * spi_replace_transfers - replace transfers with several transfers
3200 * and register change with spi_message.resources
3201 * @msg: the spi_message we work upon
3202 * @xfer_first: the first spi_transfer we want to replace
3203 * @remove: number of transfers to remove
3204 * @insert: the number of transfers we want to insert instead
3205 * @release: extra release code necessary in some circumstances
3206 * @extradatasize: extra data to allocate (with alignment guarantees
3207 * of struct @spi_transfer)
3210 * Returns: pointer to @spi_replaced_transfers,
3211 * PTR_ERR(...) in case of errors.
3213 static struct spi_replaced_transfers *spi_replace_transfers(
3214 struct spi_message *msg,
3215 struct spi_transfer *xfer_first,
3218 spi_replaced_release_t release,
3219 size_t extradatasize,
3222 struct spi_replaced_transfers *rxfer;
3223 struct spi_transfer *xfer;
3226 /* allocate the structure using spi_res */
3227 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3228 struct_size(rxfer, inserted_transfers, insert)
3232 return ERR_PTR(-ENOMEM);
3234 /* the release code to invoke before running the generic release */
3235 rxfer->release = release;
3237 /* assign extradata */
3240 &rxfer->inserted_transfers[insert];
3242 /* init the replaced_transfers list */
3243 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3246 * Assign the list_entry after which we should reinsert
3247 * the @replaced_transfers - it may be spi_message.messages!
3249 rxfer->replaced_after = xfer_first->transfer_list.prev;
3251 /* remove the requested number of transfers */
3252 for (i = 0; i < remove; i++) {
3254 * If the entry after replaced_after it is msg->transfers
3255 * then we have been requested to remove more transfers
3256 * than are in the list.
3258 if (rxfer->replaced_after->next == &msg->transfers) {
3259 dev_err(&msg->spi->dev,
3260 "requested to remove more spi_transfers than are available\n");
3261 /* insert replaced transfers back into the message */
3262 list_splice(&rxfer->replaced_transfers,
3263 rxfer->replaced_after);
3265 /* free the spi_replace_transfer structure */
3266 spi_res_free(rxfer);
3268 /* and return with an error */
3269 return ERR_PTR(-EINVAL);
3273 * Remove the entry after replaced_after from list of
3274 * transfers and add it to list of replaced_transfers.
3276 list_move_tail(rxfer->replaced_after->next,
3277 &rxfer->replaced_transfers);
3281 * Create copy of the given xfer with identical settings
3282 * based on the first transfer to get removed.
3284 for (i = 0; i < insert; i++) {
3285 /* we need to run in reverse order */
3286 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3288 /* copy all spi_transfer data */
3289 memcpy(xfer, xfer_first, sizeof(*xfer));
3292 list_add(&xfer->transfer_list, rxfer->replaced_after);
3294 /* clear cs_change and delay for all but the last */
3296 xfer->cs_change = false;
3297 xfer->delay.value = 0;
3301 /* set up inserted */
3302 rxfer->inserted = insert;
3304 /* and register it with spi_res/spi_message */
3305 spi_res_add(msg, rxfer);
3310 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3311 struct spi_message *msg,
3312 struct spi_transfer **xferp,
3316 struct spi_transfer *xfer = *xferp, *xfers;
3317 struct spi_replaced_transfers *srt;
3321 /* calculate how many we have to replace */
3322 count = DIV_ROUND_UP(xfer->len, maxsize);
3324 /* create replacement */
3325 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3327 return PTR_ERR(srt);
3328 xfers = srt->inserted_transfers;
3331 * Now handle each of those newly inserted spi_transfers.
3332 * Note that the replacements spi_transfers all are preset
3333 * to the same values as *xferp, so tx_buf, rx_buf and len
3334 * are all identical (as well as most others)
3335 * so we just have to fix up len and the pointers.
3337 * This also includes support for the depreciated
3338 * spi_message.is_dma_mapped interface.
3342 * The first transfer just needs the length modified, so we
3343 * run it outside the loop.
3345 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3347 /* all the others need rx_buf/tx_buf also set */
3348 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3349 /* update rx_buf, tx_buf and dma */
3350 if (xfers[i].rx_buf)
3351 xfers[i].rx_buf += offset;
3352 if (xfers[i].rx_dma)
3353 xfers[i].rx_dma += offset;
3354 if (xfers[i].tx_buf)
3355 xfers[i].tx_buf += offset;
3356 if (xfers[i].tx_dma)
3357 xfers[i].tx_dma += offset;
3360 xfers[i].len = min(maxsize, xfers[i].len - offset);
3364 * We set up xferp to the last entry we have inserted,
3365 * so that we skip those already split transfers.
3367 *xferp = &xfers[count - 1];
3369 /* increment statistics counters */
3370 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3371 transfers_split_maxsize);
3372 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3373 transfers_split_maxsize);
3379 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3380 * when an individual transfer exceeds a
3382 * @ctlr: the @spi_controller for this transfer
3383 * @msg: the @spi_message to transform
3384 * @maxsize: the maximum when to apply this
3385 * @gfp: GFP allocation flags
3387 * Return: status of transformation
3389 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3390 struct spi_message *msg,
3394 struct spi_transfer *xfer;
3398 * Iterate over the transfer_list,
3399 * but note that xfer is advanced to the last transfer inserted
3400 * to avoid checking sizes again unnecessarily (also xfer does
3401 * potentially belong to a different list by the time the
3402 * replacement has happened).
3404 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3405 if (xfer->len > maxsize) {
3406 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3415 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3417 /*-------------------------------------------------------------------------*/
3419 /* Core methods for SPI controller protocol drivers. Some of the
3420 * other core methods are currently defined as inline functions.
3423 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3426 if (ctlr->bits_per_word_mask) {
3427 /* Only 32 bits fit in the mask */
3428 if (bits_per_word > 32)
3430 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3438 * spi_setup - setup SPI mode and clock rate
3439 * @spi: the device whose settings are being modified
3440 * Context: can sleep, and no requests are queued to the device
3442 * SPI protocol drivers may need to update the transfer mode if the
3443 * device doesn't work with its default. They may likewise need
3444 * to update clock rates or word sizes from initial values. This function
3445 * changes those settings, and must be called from a context that can sleep.
3446 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3447 * effect the next time the device is selected and data is transferred to
3448 * or from it. When this function returns, the spi device is deselected.
3450 * Note that this call will fail if the protocol driver specifies an option
3451 * that the underlying controller or its driver does not support. For
3452 * example, not all hardware supports wire transfers using nine bit words,
3453 * LSB-first wire encoding, or active-high chipselects.
3455 * Return: zero on success, else a negative error code.
3457 int spi_setup(struct spi_device *spi)
3459 unsigned bad_bits, ugly_bits;
3463 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3464 * are set at the same time.
3466 if ((hweight_long(spi->mode &
3467 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3468 (hweight_long(spi->mode &
3469 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3471 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3474 /* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3475 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3476 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3477 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3480 * Help drivers fail *cleanly* when they need options
3481 * that aren't supported with their current controller.
3482 * SPI_CS_WORD has a fallback software implementation,
3483 * so it is ignored here.
3485 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3486 SPI_NO_TX | SPI_NO_RX);
3487 ugly_bits = bad_bits &
3488 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3489 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3492 "setup: ignoring unsupported mode bits %x\n",
3494 spi->mode &= ~ugly_bits;
3495 bad_bits &= ~ugly_bits;
3498 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3503 if (!spi->bits_per_word) {
3504 spi->bits_per_word = 8;
3507 * Some controllers may not support the default 8 bits-per-word
3508 * so only perform the check when this is explicitly provided.
3510 status = __spi_validate_bits_per_word(spi->controller,
3511 spi->bits_per_word);
3516 if (spi->controller->max_speed_hz &&
3517 (!spi->max_speed_hz ||
3518 spi->max_speed_hz > spi->controller->max_speed_hz))
3519 spi->max_speed_hz = spi->controller->max_speed_hz;
3521 mutex_lock(&spi->controller->io_mutex);
3523 if (spi->controller->setup) {
3524 status = spi->controller->setup(spi);
3526 mutex_unlock(&spi->controller->io_mutex);
3527 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3533 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3534 status = pm_runtime_resume_and_get(spi->controller->dev.parent);
3536 mutex_unlock(&spi->controller->io_mutex);
3537 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3543 * We do not want to return positive value from pm_runtime_get,
3544 * there are many instances of devices calling spi_setup() and
3545 * checking for a non-zero return value instead of a negative
3550 spi_set_cs(spi, false, true);
3551 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3552 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3554 spi_set_cs(spi, false, true);
3557 mutex_unlock(&spi->controller->io_mutex);
3559 if (spi->rt && !spi->controller->rt) {
3560 spi->controller->rt = true;
3561 spi_set_thread_rt(spi->controller);
3564 trace_spi_setup(spi, status);
3566 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3567 spi->mode & SPI_MODE_X_MASK,
3568 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3569 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3570 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3571 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3572 spi->bits_per_word, spi->max_speed_hz,
3577 EXPORT_SYMBOL_GPL(spi_setup);
3579 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3580 struct spi_device *spi)
3584 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3588 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3592 if (delay1 < delay2)
3593 memcpy(&xfer->word_delay, &spi->word_delay,
3594 sizeof(xfer->word_delay));
3599 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3601 struct spi_controller *ctlr = spi->controller;
3602 struct spi_transfer *xfer;
3605 if (list_empty(&message->transfers))
3609 * If an SPI controller does not support toggling the CS line on each
3610 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3611 * for the CS line, we can emulate the CS-per-word hardware function by
3612 * splitting transfers into one-word transfers and ensuring that
3613 * cs_change is set for each transfer.
3615 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3620 maxsize = (spi->bits_per_word + 7) / 8;
3622 /* spi_split_transfers_maxsize() requires message->spi */
3625 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3630 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3631 /* don't change cs_change on the last entry in the list */
3632 if (list_is_last(&xfer->transfer_list, &message->transfers))
3634 xfer->cs_change = 1;
3639 * Half-duplex links include original MicroWire, and ones with
3640 * only one data pin like SPI_3WIRE (switches direction) or where
3641 * either MOSI or MISO is missing. They can also be caused by
3642 * software limitations.
3644 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3645 (spi->mode & SPI_3WIRE)) {
3646 unsigned flags = ctlr->flags;
3648 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3649 if (xfer->rx_buf && xfer->tx_buf)
3651 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3653 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3659 * Set transfer bits_per_word and max speed as spi device default if
3660 * it is not set for this transfer.
3661 * Set transfer tx_nbits and rx_nbits as single transfer default
3662 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3663 * Ensure transfer word_delay is at least as long as that required by
3666 message->frame_length = 0;
3667 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3668 xfer->effective_speed_hz = 0;
3669 message->frame_length += xfer->len;
3670 if (!xfer->bits_per_word)
3671 xfer->bits_per_word = spi->bits_per_word;
3673 if (!xfer->speed_hz)
3674 xfer->speed_hz = spi->max_speed_hz;
3676 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3677 xfer->speed_hz = ctlr->max_speed_hz;
3679 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3683 * SPI transfer length should be multiple of SPI word size
3684 * where SPI word size should be power-of-two multiple.
3686 if (xfer->bits_per_word <= 8)
3688 else if (xfer->bits_per_word <= 16)
3693 /* No partial transfers accepted */
3694 if (xfer->len % w_size)
3697 if (xfer->speed_hz && ctlr->min_speed_hz &&
3698 xfer->speed_hz < ctlr->min_speed_hz)
3701 if (xfer->tx_buf && !xfer->tx_nbits)
3702 xfer->tx_nbits = SPI_NBITS_SINGLE;
3703 if (xfer->rx_buf && !xfer->rx_nbits)
3704 xfer->rx_nbits = SPI_NBITS_SINGLE;
3706 * Check transfer tx/rx_nbits:
3707 * 1. check the value matches one of single, dual and quad
3708 * 2. check tx/rx_nbits match the mode in spi_device
3711 if (spi->mode & SPI_NO_TX)
3713 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3714 xfer->tx_nbits != SPI_NBITS_DUAL &&
3715 xfer->tx_nbits != SPI_NBITS_QUAD)
3717 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3718 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3720 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3721 !(spi->mode & SPI_TX_QUAD))
3724 /* check transfer rx_nbits */
3726 if (spi->mode & SPI_NO_RX)
3728 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3729 xfer->rx_nbits != SPI_NBITS_DUAL &&
3730 xfer->rx_nbits != SPI_NBITS_QUAD)
3732 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3733 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3735 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3736 !(spi->mode & SPI_RX_QUAD))
3740 if (_spi_xfer_word_delay_update(xfer, spi))
3744 message->status = -EINPROGRESS;
3749 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3751 struct spi_controller *ctlr = spi->controller;
3752 struct spi_transfer *xfer;
3755 * Some controllers do not support doing regular SPI transfers. Return
3756 * ENOTSUPP when this is the case.
3758 if (!ctlr->transfer)
3763 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3764 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3766 trace_spi_message_submit(message);
3768 if (!ctlr->ptp_sts_supported) {
3769 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3770 xfer->ptp_sts_word_pre = 0;
3771 ptp_read_system_prets(xfer->ptp_sts);
3775 return ctlr->transfer(spi, message);
3779 * spi_async - asynchronous SPI transfer
3780 * @spi: device with which data will be exchanged
3781 * @message: describes the data transfers, including completion callback
3782 * Context: any (irqs may be blocked, etc)
3784 * This call may be used in_irq and other contexts which can't sleep,
3785 * as well as from task contexts which can sleep.
3787 * The completion callback is invoked in a context which can't sleep.
3788 * Before that invocation, the value of message->status is undefined.
3789 * When the callback is issued, message->status holds either zero (to
3790 * indicate complete success) or a negative error code. After that
3791 * callback returns, the driver which issued the transfer request may
3792 * deallocate the associated memory; it's no longer in use by any SPI
3793 * core or controller driver code.
3795 * Note that although all messages to a spi_device are handled in
3796 * FIFO order, messages may go to different devices in other orders.
3797 * Some device might be higher priority, or have various "hard" access
3798 * time requirements, for example.
3800 * On detection of any fault during the transfer, processing of
3801 * the entire message is aborted, and the device is deselected.
3802 * Until returning from the associated message completion callback,
3803 * no other spi_message queued to that device will be processed.
3804 * (This rule applies equally to all the synchronous transfer calls,
3805 * which are wrappers around this core asynchronous primitive.)
3807 * Return: zero on success, else a negative error code.
3809 int spi_async(struct spi_device *spi, struct spi_message *message)
3811 struct spi_controller *ctlr = spi->controller;
3813 unsigned long flags;
3815 ret = __spi_validate(spi, message);
3819 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3821 if (ctlr->bus_lock_flag)
3824 ret = __spi_async(spi, message);
3826 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3830 EXPORT_SYMBOL_GPL(spi_async);
3833 * spi_async_locked - version of spi_async with exclusive bus usage
3834 * @spi: device with which data will be exchanged
3835 * @message: describes the data transfers, including completion callback
3836 * Context: any (irqs may be blocked, etc)
3838 * This call may be used in_irq and other contexts which can't sleep,
3839 * as well as from task contexts which can sleep.
3841 * The completion callback is invoked in a context which can't sleep.
3842 * Before that invocation, the value of message->status is undefined.
3843 * When the callback is issued, message->status holds either zero (to
3844 * indicate complete success) or a negative error code. After that
3845 * callback returns, the driver which issued the transfer request may
3846 * deallocate the associated memory; it's no longer in use by any SPI
3847 * core or controller driver code.
3849 * Note that although all messages to a spi_device are handled in
3850 * FIFO order, messages may go to different devices in other orders.
3851 * Some device might be higher priority, or have various "hard" access
3852 * time requirements, for example.
3854 * On detection of any fault during the transfer, processing of
3855 * the entire message is aborted, and the device is deselected.
3856 * Until returning from the associated message completion callback,
3857 * no other spi_message queued to that device will be processed.
3858 * (This rule applies equally to all the synchronous transfer calls,
3859 * which are wrappers around this core asynchronous primitive.)
3861 * Return: zero on success, else a negative error code.
3863 static int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3865 struct spi_controller *ctlr = spi->controller;
3867 unsigned long flags;
3869 ret = __spi_validate(spi, message);
3873 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3875 ret = __spi_async(spi, message);
3877 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3883 /*-------------------------------------------------------------------------*/
3886 * Utility methods for SPI protocol drivers, layered on
3887 * top of the core. Some other utility methods are defined as
3891 static void spi_complete(void *arg)
3896 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3898 DECLARE_COMPLETION_ONSTACK(done);
3900 struct spi_controller *ctlr = spi->controller;
3901 unsigned long flags;
3903 status = __spi_validate(spi, message);
3907 message->complete = spi_complete;
3908 message->context = &done;
3911 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3912 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3915 * If we're not using the legacy transfer method then we will
3916 * try to transfer in the calling context so special case.
3917 * This code would be less tricky if we could remove the
3918 * support for driver implemented message queues.
3920 if (ctlr->transfer == spi_queued_transfer) {
3921 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3923 trace_spi_message_submit(message);
3925 status = __spi_queued_transfer(spi, message, false);
3927 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3929 status = spi_async_locked(spi, message);
3933 /* Push out the messages in the calling context if we can */
3934 if (ctlr->transfer == spi_queued_transfer) {
3935 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3936 spi_sync_immediate);
3937 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3938 spi_sync_immediate);
3939 __spi_pump_messages(ctlr, false);
3942 wait_for_completion(&done);
3943 status = message->status;
3945 message->context = NULL;
3950 * spi_sync - blocking/synchronous SPI data transfers
3951 * @spi: device with which data will be exchanged
3952 * @message: describes the data transfers
3953 * Context: can sleep
3955 * This call may only be used from a context that may sleep. The sleep
3956 * is non-interruptible, and has no timeout. Low-overhead controller
3957 * drivers may DMA directly into and out of the message buffers.
3959 * Note that the SPI device's chip select is active during the message,
3960 * and then is normally disabled between messages. Drivers for some
3961 * frequently-used devices may want to minimize costs of selecting a chip,
3962 * by leaving it selected in anticipation that the next message will go
3963 * to the same chip. (That may increase power usage.)
3965 * Also, the caller is guaranteeing that the memory associated with the
3966 * message will not be freed before this call returns.
3968 * Return: zero on success, else a negative error code.
3970 int spi_sync(struct spi_device *spi, struct spi_message *message)
3974 mutex_lock(&spi->controller->bus_lock_mutex);
3975 ret = __spi_sync(spi, message);
3976 mutex_unlock(&spi->controller->bus_lock_mutex);
3980 EXPORT_SYMBOL_GPL(spi_sync);
3983 * spi_sync_locked - version of spi_sync with exclusive bus usage
3984 * @spi: device with which data will be exchanged
3985 * @message: describes the data transfers
3986 * Context: can sleep
3988 * This call may only be used from a context that may sleep. The sleep
3989 * is non-interruptible, and has no timeout. Low-overhead controller
3990 * drivers may DMA directly into and out of the message buffers.
3992 * This call should be used by drivers that require exclusive access to the
3993 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3994 * be released by a spi_bus_unlock call when the exclusive access is over.
3996 * Return: zero on success, else a negative error code.
3998 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4000 return __spi_sync(spi, message);
4002 EXPORT_SYMBOL_GPL(spi_sync_locked);
4005 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
4006 * @ctlr: SPI bus master that should be locked for exclusive bus access
4007 * Context: can sleep
4009 * This call may only be used from a context that may sleep. The sleep
4010 * is non-interruptible, and has no timeout.
4012 * This call should be used by drivers that require exclusive access to the
4013 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4014 * exclusive access is over. Data transfer must be done by spi_sync_locked
4015 * and spi_async_locked calls when the SPI bus lock is held.
4017 * Return: always zero.
4019 int spi_bus_lock(struct spi_controller *ctlr)
4021 unsigned long flags;
4023 mutex_lock(&ctlr->bus_lock_mutex);
4025 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4026 ctlr->bus_lock_flag = 1;
4027 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4029 /* mutex remains locked until spi_bus_unlock is called */
4033 EXPORT_SYMBOL_GPL(spi_bus_lock);
4036 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4037 * @ctlr: SPI bus master that was locked for exclusive bus access
4038 * Context: can sleep
4040 * This call may only be used from a context that may sleep. The sleep
4041 * is non-interruptible, and has no timeout.
4043 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4046 * Return: always zero.
4048 int spi_bus_unlock(struct spi_controller *ctlr)
4050 ctlr->bus_lock_flag = 0;
4052 mutex_unlock(&ctlr->bus_lock_mutex);
4056 EXPORT_SYMBOL_GPL(spi_bus_unlock);
4058 /* portable code must never pass more than 32 bytes */
4059 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4064 * spi_write_then_read - SPI synchronous write followed by read
4065 * @spi: device with which data will be exchanged
4066 * @txbuf: data to be written (need not be dma-safe)
4067 * @n_tx: size of txbuf, in bytes
4068 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4069 * @n_rx: size of rxbuf, in bytes
4070 * Context: can sleep
4072 * This performs a half duplex MicroWire style transaction with the
4073 * device, sending txbuf and then reading rxbuf. The return value
4074 * is zero for success, else a negative errno status code.
4075 * This call may only be used from a context that may sleep.
4077 * Parameters to this routine are always copied using a small buffer.
4078 * Performance-sensitive or bulk transfer code should instead use
4079 * spi_{async,sync}() calls with dma-safe buffers.
4081 * Return: zero on success, else a negative error code.
4083 int spi_write_then_read(struct spi_device *spi,
4084 const void *txbuf, unsigned n_tx,
4085 void *rxbuf, unsigned n_rx)
4087 static DEFINE_MUTEX(lock);
4090 struct spi_message message;
4091 struct spi_transfer x[2];
4095 * Use preallocated DMA-safe buffer if we can. We can't avoid
4096 * copying here, (as a pure convenience thing), but we can
4097 * keep heap costs out of the hot path unless someone else is
4098 * using the pre-allocated buffer or the transfer is too large.
4100 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4101 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4102 GFP_KERNEL | GFP_DMA);
4109 spi_message_init(&message);
4110 memset(x, 0, sizeof(x));
4113 spi_message_add_tail(&x[0], &message);
4117 spi_message_add_tail(&x[1], &message);
4120 memcpy(local_buf, txbuf, n_tx);
4121 x[0].tx_buf = local_buf;
4122 x[1].rx_buf = local_buf + n_tx;
4125 status = spi_sync(spi, &message);
4127 memcpy(rxbuf, x[1].rx_buf, n_rx);
4129 if (x[0].tx_buf == buf)
4130 mutex_unlock(&lock);
4136 EXPORT_SYMBOL_GPL(spi_write_then_read);
4138 /*-------------------------------------------------------------------------*/
4140 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4141 /* must call put_device() when done with returned spi_device device */
4142 static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4144 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4146 return dev ? to_spi_device(dev) : NULL;
4149 /* the spi controllers are not using spi_bus, so we find it with another way */
4150 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4154 dev = class_find_device_by_of_node(&spi_master_class, node);
4155 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4156 dev = class_find_device_by_of_node(&spi_slave_class, node);
4160 /* reference got in class_find_device */
4161 return container_of(dev, struct spi_controller, dev);
4164 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4167 struct of_reconfig_data *rd = arg;
4168 struct spi_controller *ctlr;
4169 struct spi_device *spi;
4171 switch (of_reconfig_get_state_change(action, arg)) {
4172 case OF_RECONFIG_CHANGE_ADD:
4173 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4175 return NOTIFY_OK; /* not for us */
4177 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4178 put_device(&ctlr->dev);
4182 spi = of_register_spi_device(ctlr, rd->dn);
4183 put_device(&ctlr->dev);
4186 pr_err("%s: failed to create for '%pOF'\n",
4188 of_node_clear_flag(rd->dn, OF_POPULATED);
4189 return notifier_from_errno(PTR_ERR(spi));
4193 case OF_RECONFIG_CHANGE_REMOVE:
4194 /* already depopulated? */
4195 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4198 /* find our device by node */
4199 spi = of_find_spi_device_by_node(rd->dn);
4201 return NOTIFY_OK; /* no? not meant for us */
4203 /* unregister takes one ref away */
4204 spi_unregister_device(spi);
4206 /* and put the reference of the find */
4207 put_device(&spi->dev);
4214 static struct notifier_block spi_of_notifier = {
4215 .notifier_call = of_spi_notify,
4217 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4218 extern struct notifier_block spi_of_notifier;
4219 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4221 #if IS_ENABLED(CONFIG_ACPI)
4222 static int spi_acpi_controller_match(struct device *dev, const void *data)
4224 return ACPI_COMPANION(dev->parent) == data;
4227 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4231 dev = class_find_device(&spi_master_class, NULL, adev,
4232 spi_acpi_controller_match);
4233 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4234 dev = class_find_device(&spi_slave_class, NULL, adev,
4235 spi_acpi_controller_match);
4239 return container_of(dev, struct spi_controller, dev);
4242 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4246 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4247 return to_spi_device(dev);
4250 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4253 struct acpi_device *adev = arg;
4254 struct spi_controller *ctlr;
4255 struct spi_device *spi;
4258 case ACPI_RECONFIG_DEVICE_ADD:
4259 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4263 acpi_register_spi_device(ctlr, adev);
4264 put_device(&ctlr->dev);
4266 case ACPI_RECONFIG_DEVICE_REMOVE:
4267 if (!acpi_device_enumerated(adev))
4270 spi = acpi_spi_find_device_by_adev(adev);
4274 spi_unregister_device(spi);
4275 put_device(&spi->dev);
4282 static struct notifier_block spi_acpi_notifier = {
4283 .notifier_call = acpi_spi_notify,
4286 extern struct notifier_block spi_acpi_notifier;
4289 static int __init spi_init(void)
4293 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4299 status = bus_register(&spi_bus_type);
4303 status = class_register(&spi_master_class);
4307 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4308 status = class_register(&spi_slave_class);
4313 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4314 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4315 if (IS_ENABLED(CONFIG_ACPI))
4316 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4321 class_unregister(&spi_master_class);
4323 bus_unregister(&spi_bus_type);
4332 * A board_info is normally registered in arch_initcall(),
4333 * but even essential drivers wait till later.
4335 * REVISIT only boardinfo really needs static linking. The rest (device and
4336 * driver registration) _could_ be dynamically linked (modular) ... Costs
4337 * include needing to have boardinfo data structures be much more public.
4339 postcore_initcall(spi_init);