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);
74 const char *end = memchr(buf, '\n', count);
75 const size_t len = end ? end - buf : count;
76 const char *driver_override, *old;
78 /* We need to keep extra room for a newline when displaying value */
79 if (len >= (PAGE_SIZE - 1))
82 driver_override = kstrndup(buf, len, GFP_KERNEL);
87 old = spi->driver_override;
89 spi->driver_override = driver_override;
91 /* Empty string, disable driver override */
92 spi->driver_override = NULL;
93 kfree(driver_override);
101 static ssize_t driver_override_show(struct device *dev,
102 struct device_attribute *a, char *buf)
104 const struct spi_device *spi = to_spi_device(dev);
108 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
112 static DEVICE_ATTR_RW(driver_override);
114 #define SPI_STATISTICS_ATTRS(field, file) \
115 static ssize_t spi_controller_##field##_show(struct device *dev, \
116 struct device_attribute *attr, \
119 struct spi_controller *ctlr = container_of(dev, \
120 struct spi_controller, dev); \
121 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
123 static struct device_attribute dev_attr_spi_controller_##field = { \
124 .attr = { .name = file, .mode = 0444 }, \
125 .show = spi_controller_##field##_show, \
127 static ssize_t spi_device_##field##_show(struct device *dev, \
128 struct device_attribute *attr, \
131 struct spi_device *spi = to_spi_device(dev); \
132 return spi_statistics_##field##_show(&spi->statistics, buf); \
134 static struct device_attribute dev_attr_spi_device_##field = { \
135 .attr = { .name = file, .mode = 0444 }, \
136 .show = spi_device_##field##_show, \
139 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
140 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
143 unsigned long flags; \
145 spin_lock_irqsave(&stat->lock, flags); \
146 len = sysfs_emit(buf, format_string "\n", stat->field); \
147 spin_unlock_irqrestore(&stat->lock, flags); \
150 SPI_STATISTICS_ATTRS(name, file)
152 #define SPI_STATISTICS_SHOW(field, format_string) \
153 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
154 field, format_string)
156 SPI_STATISTICS_SHOW(messages, "%lu");
157 SPI_STATISTICS_SHOW(transfers, "%lu");
158 SPI_STATISTICS_SHOW(errors, "%lu");
159 SPI_STATISTICS_SHOW(timedout, "%lu");
161 SPI_STATISTICS_SHOW(spi_sync, "%lu");
162 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
163 SPI_STATISTICS_SHOW(spi_async, "%lu");
165 SPI_STATISTICS_SHOW(bytes, "%llu");
166 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
167 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
169 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
170 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
171 "transfer_bytes_histo_" number, \
172 transfer_bytes_histo[index], "%lu")
173 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
174 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
175 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
176 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
191 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
193 static struct attribute *spi_dev_attrs[] = {
194 &dev_attr_modalias.attr,
195 &dev_attr_driver_override.attr,
199 static const struct attribute_group spi_dev_group = {
200 .attrs = spi_dev_attrs,
203 static struct attribute *spi_device_statistics_attrs[] = {
204 &dev_attr_spi_device_messages.attr,
205 &dev_attr_spi_device_transfers.attr,
206 &dev_attr_spi_device_errors.attr,
207 &dev_attr_spi_device_timedout.attr,
208 &dev_attr_spi_device_spi_sync.attr,
209 &dev_attr_spi_device_spi_sync_immediate.attr,
210 &dev_attr_spi_device_spi_async.attr,
211 &dev_attr_spi_device_bytes.attr,
212 &dev_attr_spi_device_bytes_rx.attr,
213 &dev_attr_spi_device_bytes_tx.attr,
214 &dev_attr_spi_device_transfer_bytes_histo0.attr,
215 &dev_attr_spi_device_transfer_bytes_histo1.attr,
216 &dev_attr_spi_device_transfer_bytes_histo2.attr,
217 &dev_attr_spi_device_transfer_bytes_histo3.attr,
218 &dev_attr_spi_device_transfer_bytes_histo4.attr,
219 &dev_attr_spi_device_transfer_bytes_histo5.attr,
220 &dev_attr_spi_device_transfer_bytes_histo6.attr,
221 &dev_attr_spi_device_transfer_bytes_histo7.attr,
222 &dev_attr_spi_device_transfer_bytes_histo8.attr,
223 &dev_attr_spi_device_transfer_bytes_histo9.attr,
224 &dev_attr_spi_device_transfer_bytes_histo10.attr,
225 &dev_attr_spi_device_transfer_bytes_histo11.attr,
226 &dev_attr_spi_device_transfer_bytes_histo12.attr,
227 &dev_attr_spi_device_transfer_bytes_histo13.attr,
228 &dev_attr_spi_device_transfer_bytes_histo14.attr,
229 &dev_attr_spi_device_transfer_bytes_histo15.attr,
230 &dev_attr_spi_device_transfer_bytes_histo16.attr,
231 &dev_attr_spi_device_transfers_split_maxsize.attr,
235 static const struct attribute_group spi_device_statistics_group = {
236 .name = "statistics",
237 .attrs = spi_device_statistics_attrs,
240 static const struct attribute_group *spi_dev_groups[] = {
242 &spi_device_statistics_group,
246 static struct attribute *spi_controller_statistics_attrs[] = {
247 &dev_attr_spi_controller_messages.attr,
248 &dev_attr_spi_controller_transfers.attr,
249 &dev_attr_spi_controller_errors.attr,
250 &dev_attr_spi_controller_timedout.attr,
251 &dev_attr_spi_controller_spi_sync.attr,
252 &dev_attr_spi_controller_spi_sync_immediate.attr,
253 &dev_attr_spi_controller_spi_async.attr,
254 &dev_attr_spi_controller_bytes.attr,
255 &dev_attr_spi_controller_bytes_rx.attr,
256 &dev_attr_spi_controller_bytes_tx.attr,
257 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
258 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
259 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
260 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
274 &dev_attr_spi_controller_transfers_split_maxsize.attr,
278 static const struct attribute_group spi_controller_statistics_group = {
279 .name = "statistics",
280 .attrs = spi_controller_statistics_attrs,
283 static const struct attribute_group *spi_master_groups[] = {
284 &spi_controller_statistics_group,
288 static void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
289 struct spi_transfer *xfer,
290 struct spi_controller *ctlr)
293 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
298 spin_lock_irqsave(&stats->lock, flags);
301 stats->transfer_bytes_histo[l2len]++;
303 stats->bytes += xfer->len;
304 if ((xfer->tx_buf) &&
305 (xfer->tx_buf != ctlr->dummy_tx))
306 stats->bytes_tx += xfer->len;
307 if ((xfer->rx_buf) &&
308 (xfer->rx_buf != ctlr->dummy_rx))
309 stats->bytes_rx += xfer->len;
311 spin_unlock_irqrestore(&stats->lock, flags);
315 * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
316 * and the sysfs version makes coldplug work too.
318 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
320 while (id->name[0]) {
321 if (!strcmp(name, id->name))
328 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
330 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
332 return spi_match_id(sdrv->id_table, sdev->modalias);
334 EXPORT_SYMBOL_GPL(spi_get_device_id);
336 static int spi_match_device(struct device *dev, struct device_driver *drv)
338 const struct spi_device *spi = to_spi_device(dev);
339 const struct spi_driver *sdrv = to_spi_driver(drv);
341 /* Check override first, and if set, only use the named driver */
342 if (spi->driver_override)
343 return strcmp(spi->driver_override, drv->name) == 0;
345 /* Attempt an OF style match */
346 if (of_driver_match_device(dev, drv))
350 if (acpi_driver_match_device(dev, drv))
354 return !!spi_match_id(sdrv->id_table, spi->modalias);
356 return strcmp(spi->modalias, drv->name) == 0;
359 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
361 const struct spi_device *spi = to_spi_device(dev);
364 rc = acpi_device_uevent_modalias(dev, env);
368 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
371 static int spi_probe(struct device *dev)
373 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
374 struct spi_device *spi = to_spi_device(dev);
377 ret = of_clk_set_defaults(dev->of_node, false);
382 spi->irq = of_irq_get(dev->of_node, 0);
383 if (spi->irq == -EPROBE_DEFER)
384 return -EPROBE_DEFER;
389 ret = dev_pm_domain_attach(dev, true);
394 ret = sdrv->probe(spi);
396 dev_pm_domain_detach(dev, true);
402 static void spi_remove(struct device *dev)
404 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
407 sdrv->remove(to_spi_device(dev));
409 dev_pm_domain_detach(dev, true);
412 static void spi_shutdown(struct device *dev)
415 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
418 sdrv->shutdown(to_spi_device(dev));
422 struct bus_type spi_bus_type = {
424 .dev_groups = spi_dev_groups,
425 .match = spi_match_device,
426 .uevent = spi_uevent,
428 .remove = spi_remove,
429 .shutdown = spi_shutdown,
431 EXPORT_SYMBOL_GPL(spi_bus_type);
434 * __spi_register_driver - register a SPI driver
435 * @owner: owner module of the driver to register
436 * @sdrv: the driver to register
439 * Return: zero on success, else a negative error code.
441 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
443 sdrv->driver.owner = owner;
444 sdrv->driver.bus = &spi_bus_type;
447 * For Really Good Reasons we use spi: modaliases not of:
448 * modaliases for DT so module autoloading won't work if we
449 * don't have a spi_device_id as well as a compatible string.
451 if (sdrv->driver.of_match_table) {
452 const struct of_device_id *of_id;
454 for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
458 /* Strip off any vendor prefix */
459 of_name = strnchr(of_id->compatible,
460 sizeof(of_id->compatible), ',');
464 of_name = of_id->compatible;
466 if (sdrv->id_table) {
467 const struct spi_device_id *spi_id;
469 spi_id = spi_match_id(sdrv->id_table, of_name);
473 if (strcmp(sdrv->driver.name, of_name) == 0)
477 pr_warn("SPI driver %s has no spi_device_id for %s\n",
478 sdrv->driver.name, of_id->compatible);
482 return driver_register(&sdrv->driver);
484 EXPORT_SYMBOL_GPL(__spi_register_driver);
486 /*-------------------------------------------------------------------------*/
489 * SPI devices should normally not be created by SPI device drivers; that
490 * would make them board-specific. Similarly with SPI controller drivers.
491 * Device registration normally goes into like arch/.../mach.../board-YYY.c
492 * with other readonly (flashable) information about mainboard devices.
496 struct list_head list;
497 struct spi_board_info board_info;
500 static LIST_HEAD(board_list);
501 static LIST_HEAD(spi_controller_list);
504 * Used to protect add/del operation for board_info list and
505 * spi_controller list, and their matching process also used
506 * to protect object of type struct idr.
508 static DEFINE_MUTEX(board_lock);
511 * spi_alloc_device - Allocate a new SPI device
512 * @ctlr: Controller to which device is connected
515 * Allows a driver to allocate and initialize a spi_device without
516 * registering it immediately. This allows a driver to directly
517 * fill the spi_device with device parameters before calling
518 * spi_add_device() on it.
520 * Caller is responsible to call spi_add_device() on the returned
521 * spi_device structure to add it to the SPI controller. If the caller
522 * needs to discard the spi_device without adding it, then it should
523 * call spi_dev_put() on it.
525 * Return: a pointer to the new device, or NULL.
527 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
529 struct spi_device *spi;
531 if (!spi_controller_get(ctlr))
534 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
536 spi_controller_put(ctlr);
540 spi->master = spi->controller = ctlr;
541 spi->dev.parent = &ctlr->dev;
542 spi->dev.bus = &spi_bus_type;
543 spi->dev.release = spidev_release;
544 spi->mode = ctlr->buswidth_override_bits;
546 spin_lock_init(&spi->statistics.lock);
548 device_initialize(&spi->dev);
551 EXPORT_SYMBOL_GPL(spi_alloc_device);
553 static void spi_dev_set_name(struct spi_device *spi)
555 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
558 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
562 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
566 static int spi_dev_check(struct device *dev, void *data)
568 struct spi_device *spi = to_spi_device(dev);
569 struct spi_device *new_spi = data;
571 if (spi->controller == new_spi->controller &&
572 spi->chip_select == new_spi->chip_select)
577 static void spi_cleanup(struct spi_device *spi)
579 if (spi->controller->cleanup)
580 spi->controller->cleanup(spi);
583 static int __spi_add_device(struct spi_device *spi)
585 struct spi_controller *ctlr = spi->controller;
586 struct device *dev = ctlr->dev.parent;
590 * We need to make sure there's no other device with this
591 * chipselect **BEFORE** we call setup(), else we'll trash
594 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
596 dev_err(dev, "chipselect %d already in use\n",
601 /* Controller may unregister concurrently */
602 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
603 !device_is_registered(&ctlr->dev)) {
608 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
611 * Drivers may modify this initial i/o setup, but will
612 * normally rely on the device being setup. Devices
613 * using SPI_CS_HIGH can't coexist well otherwise...
615 status = spi_setup(spi);
617 dev_err(dev, "can't setup %s, status %d\n",
618 dev_name(&spi->dev), status);
622 /* Device may be bound to an active driver when this returns */
623 status = device_add(&spi->dev);
625 dev_err(dev, "can't add %s, status %d\n",
626 dev_name(&spi->dev), status);
629 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
636 * spi_add_device - Add spi_device allocated with spi_alloc_device
637 * @spi: spi_device to register
639 * Companion function to spi_alloc_device. Devices allocated with
640 * spi_alloc_device can be added onto the spi bus with this function.
642 * Return: 0 on success; negative errno on failure
644 int spi_add_device(struct spi_device *spi)
646 struct spi_controller *ctlr = spi->controller;
647 struct device *dev = ctlr->dev.parent;
650 /* Chipselects are numbered 0..max; validate. */
651 if (spi->chip_select >= ctlr->num_chipselect) {
652 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
653 ctlr->num_chipselect);
657 /* Set the bus ID string */
658 spi_dev_set_name(spi);
660 mutex_lock(&ctlr->add_lock);
661 status = __spi_add_device(spi);
662 mutex_unlock(&ctlr->add_lock);
665 EXPORT_SYMBOL_GPL(spi_add_device);
667 static int spi_add_device_locked(struct spi_device *spi)
669 struct spi_controller *ctlr = spi->controller;
670 struct device *dev = ctlr->dev.parent;
672 /* Chipselects are numbered 0..max; validate. */
673 if (spi->chip_select >= ctlr->num_chipselect) {
674 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
675 ctlr->num_chipselect);
679 /* Set the bus ID string */
680 spi_dev_set_name(spi);
682 WARN_ON(!mutex_is_locked(&ctlr->add_lock));
683 return __spi_add_device(spi);
687 * spi_new_device - instantiate one new SPI device
688 * @ctlr: Controller to which device is connected
689 * @chip: Describes the SPI device
692 * On typical mainboards, this is purely internal; and it's not needed
693 * after board init creates the hard-wired devices. Some development
694 * platforms may not be able to use spi_register_board_info though, and
695 * this is exported so that for example a USB or parport based adapter
696 * driver could add devices (which it would learn about out-of-band).
698 * Return: the new device, or NULL.
700 struct spi_device *spi_new_device(struct spi_controller *ctlr,
701 struct spi_board_info *chip)
703 struct spi_device *proxy;
707 * NOTE: caller did any chip->bus_num checks necessary.
709 * Also, unless we change the return value convention to use
710 * error-or-pointer (not NULL-or-pointer), troubleshootability
711 * suggests syslogged diagnostics are best here (ugh).
714 proxy = spi_alloc_device(ctlr);
718 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
720 proxy->chip_select = chip->chip_select;
721 proxy->max_speed_hz = chip->max_speed_hz;
722 proxy->mode = chip->mode;
723 proxy->irq = chip->irq;
724 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
725 proxy->dev.platform_data = (void *) chip->platform_data;
726 proxy->controller_data = chip->controller_data;
727 proxy->controller_state = NULL;
730 status = device_add_software_node(&proxy->dev, chip->swnode);
732 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
733 chip->modalias, status);
738 status = spi_add_device(proxy);
745 device_remove_software_node(&proxy->dev);
749 EXPORT_SYMBOL_GPL(spi_new_device);
752 * spi_unregister_device - unregister a single SPI device
753 * @spi: spi_device to unregister
755 * Start making the passed SPI device vanish. Normally this would be handled
756 * by spi_unregister_controller().
758 void spi_unregister_device(struct spi_device *spi)
763 if (spi->dev.of_node) {
764 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
765 of_node_put(spi->dev.of_node);
767 if (ACPI_COMPANION(&spi->dev))
768 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
769 device_remove_software_node(&spi->dev);
770 device_del(&spi->dev);
772 put_device(&spi->dev);
774 EXPORT_SYMBOL_GPL(spi_unregister_device);
776 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
777 struct spi_board_info *bi)
779 struct spi_device *dev;
781 if (ctlr->bus_num != bi->bus_num)
784 dev = spi_new_device(ctlr, bi);
786 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
791 * spi_register_board_info - register SPI devices for a given board
792 * @info: array of chip descriptors
793 * @n: how many descriptors are provided
796 * Board-specific early init code calls this (probably during arch_initcall)
797 * with segments of the SPI device table. Any device nodes are created later,
798 * after the relevant parent SPI controller (bus_num) is defined. We keep
799 * this table of devices forever, so that reloading a controller driver will
800 * not make Linux forget about these hard-wired devices.
802 * Other code can also call this, e.g. a particular add-on board might provide
803 * SPI devices through its expansion connector, so code initializing that board
804 * would naturally declare its SPI devices.
806 * The board info passed can safely be __initdata ... but be careful of
807 * any embedded pointers (platform_data, etc), they're copied as-is.
809 * Return: zero on success, else a negative error code.
811 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
813 struct boardinfo *bi;
819 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
823 for (i = 0; i < n; i++, bi++, info++) {
824 struct spi_controller *ctlr;
826 memcpy(&bi->board_info, info, sizeof(*info));
828 mutex_lock(&board_lock);
829 list_add_tail(&bi->list, &board_list);
830 list_for_each_entry(ctlr, &spi_controller_list, list)
831 spi_match_controller_to_boardinfo(ctlr,
833 mutex_unlock(&board_lock);
839 /*-------------------------------------------------------------------------*/
841 /* Core methods for SPI resource management */
844 * spi_res_alloc - allocate a spi resource that is life-cycle managed
845 * during the processing of a spi_message while using
847 * @spi: the spi device for which we allocate memory
848 * @release: the release code to execute for this resource
849 * @size: size to alloc and return
850 * @gfp: GFP allocation flags
852 * Return: the pointer to the allocated data
854 * This may get enhanced in the future to allocate from a memory pool
855 * of the @spi_device or @spi_controller to avoid repeated allocations.
857 static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
858 size_t size, gfp_t gfp)
860 struct spi_res *sres;
862 sres = kzalloc(sizeof(*sres) + size, gfp);
866 INIT_LIST_HEAD(&sres->entry);
867 sres->release = release;
873 * spi_res_free - free an spi resource
874 * @res: pointer to the custom data of a resource
876 static void spi_res_free(void *res)
878 struct spi_res *sres = container_of(res, struct spi_res, data);
883 WARN_ON(!list_empty(&sres->entry));
888 * spi_res_add - add a spi_res to the spi_message
889 * @message: the spi message
890 * @res: the spi_resource
892 static void spi_res_add(struct spi_message *message, void *res)
894 struct spi_res *sres = container_of(res, struct spi_res, data);
896 WARN_ON(!list_empty(&sres->entry));
897 list_add_tail(&sres->entry, &message->resources);
901 * spi_res_release - release all spi resources for this message
902 * @ctlr: the @spi_controller
903 * @message: the @spi_message
905 static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
907 struct spi_res *res, *tmp;
909 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
911 res->release(ctlr, message, res->data);
913 list_del(&res->entry);
919 /*-------------------------------------------------------------------------*/
921 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
923 bool activate = enable;
926 * Avoid calling into the driver (or doing delays) if the chip select
927 * isn't actually changing from the last time this was called.
929 if (!force && ((enable && spi->controller->last_cs == spi->chip_select) ||
930 (!enable && spi->controller->last_cs != spi->chip_select)) &&
931 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
934 trace_spi_set_cs(spi, activate);
936 spi->controller->last_cs = enable ? spi->chip_select : -1;
937 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
939 if ((spi->cs_gpiod || !spi->controller->set_cs_timing) && !activate) {
940 spi_delay_exec(&spi->cs_hold, NULL);
943 if (spi->mode & SPI_CS_HIGH)
947 if (!(spi->mode & SPI_NO_CS)) {
949 * Historically ACPI has no means of the GPIO polarity and
950 * thus the SPISerialBus() resource defines it on the per-chip
951 * basis. In order to avoid a chain of negations, the GPIO
952 * polarity is considered being Active High. Even for the cases
953 * when _DSD() is involved (in the updated versions of ACPI)
954 * the GPIO CS polarity must be defined Active High to avoid
955 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
958 if (has_acpi_companion(&spi->dev))
959 gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
961 /* Polarity handled by GPIO library */
962 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
964 /* Some SPI masters need both GPIO CS & slave_select */
965 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
966 spi->controller->set_cs)
967 spi->controller->set_cs(spi, !enable);
968 } else if (spi->controller->set_cs) {
969 spi->controller->set_cs(spi, !enable);
972 if (spi->cs_gpiod || !spi->controller->set_cs_timing) {
974 spi_delay_exec(&spi->cs_setup, NULL);
976 spi_delay_exec(&spi->cs_inactive, NULL);
980 #ifdef CONFIG_HAS_DMA
981 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
982 struct sg_table *sgt, void *buf, size_t len,
983 enum dma_data_direction dir)
985 const bool vmalloced_buf = is_vmalloc_addr(buf);
986 unsigned int max_seg_size = dma_get_max_seg_size(dev);
987 #ifdef CONFIG_HIGHMEM
988 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
989 (unsigned long)buf < (PKMAP_BASE +
990 (LAST_PKMAP * PAGE_SIZE)));
992 const bool kmap_buf = false;
996 struct page *vm_page;
997 struct scatterlist *sg;
1002 if (vmalloced_buf || kmap_buf) {
1003 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
1004 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
1005 } else if (virt_addr_valid(buf)) {
1006 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
1007 sgs = DIV_ROUND_UP(len, desc_len);
1012 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
1017 for (i = 0; i < sgs; i++) {
1019 if (vmalloced_buf || kmap_buf) {
1021 * Next scatterlist entry size is the minimum between
1022 * the desc_len and the remaining buffer length that
1025 min = min_t(size_t, desc_len,
1027 PAGE_SIZE - offset_in_page(buf)));
1029 vm_page = vmalloc_to_page(buf);
1031 vm_page = kmap_to_page(buf);
1036 sg_set_page(sg, vm_page,
1037 min, offset_in_page(buf));
1039 min = min_t(size_t, len, desc_len);
1041 sg_set_buf(sg, sg_buf, min);
1049 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
1062 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
1063 struct sg_table *sgt, enum dma_data_direction dir)
1065 if (sgt->orig_nents) {
1066 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
1071 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1073 struct device *tx_dev, *rx_dev;
1074 struct spi_transfer *xfer;
1081 tx_dev = ctlr->dma_tx->device->dev;
1082 else if (ctlr->dma_map_dev)
1083 tx_dev = ctlr->dma_map_dev;
1085 tx_dev = ctlr->dev.parent;
1088 rx_dev = ctlr->dma_rx->device->dev;
1089 else if (ctlr->dma_map_dev)
1090 rx_dev = ctlr->dma_map_dev;
1092 rx_dev = ctlr->dev.parent;
1094 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1095 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1098 if (xfer->tx_buf != NULL) {
1099 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
1100 (void *)xfer->tx_buf, xfer->len,
1106 if (xfer->rx_buf != NULL) {
1107 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
1108 xfer->rx_buf, xfer->len,
1111 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
1118 ctlr->cur_msg_mapped = true;
1123 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1125 struct spi_transfer *xfer;
1126 struct device *tx_dev, *rx_dev;
1128 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1132 tx_dev = ctlr->dma_tx->device->dev;
1134 tx_dev = ctlr->dev.parent;
1137 rx_dev = ctlr->dma_rx->device->dev;
1139 rx_dev = ctlr->dev.parent;
1141 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1142 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1145 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1146 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1149 ctlr->cur_msg_mapped = false;
1153 #else /* !CONFIG_HAS_DMA */
1154 static inline int __spi_map_msg(struct spi_controller *ctlr,
1155 struct spi_message *msg)
1160 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1161 struct spi_message *msg)
1165 #endif /* !CONFIG_HAS_DMA */
1167 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1168 struct spi_message *msg)
1170 struct spi_transfer *xfer;
1172 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1174 * Restore the original value of tx_buf or rx_buf if they are
1177 if (xfer->tx_buf == ctlr->dummy_tx)
1178 xfer->tx_buf = NULL;
1179 if (xfer->rx_buf == ctlr->dummy_rx)
1180 xfer->rx_buf = NULL;
1183 return __spi_unmap_msg(ctlr, msg);
1186 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1188 struct spi_transfer *xfer;
1190 unsigned int max_tx, max_rx;
1192 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1193 && !(msg->spi->mode & SPI_3WIRE)) {
1197 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1198 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1200 max_tx = max(xfer->len, max_tx);
1201 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1203 max_rx = max(xfer->len, max_rx);
1207 tmp = krealloc(ctlr->dummy_tx, max_tx,
1208 GFP_KERNEL | GFP_DMA | __GFP_ZERO);
1211 ctlr->dummy_tx = tmp;
1215 tmp = krealloc(ctlr->dummy_rx, max_rx,
1216 GFP_KERNEL | GFP_DMA);
1219 ctlr->dummy_rx = tmp;
1222 if (max_tx || max_rx) {
1223 list_for_each_entry(xfer, &msg->transfers,
1228 xfer->tx_buf = ctlr->dummy_tx;
1230 xfer->rx_buf = ctlr->dummy_rx;
1235 return __spi_map_msg(ctlr, msg);
1238 static int spi_transfer_wait(struct spi_controller *ctlr,
1239 struct spi_message *msg,
1240 struct spi_transfer *xfer)
1242 struct spi_statistics *statm = &ctlr->statistics;
1243 struct spi_statistics *stats = &msg->spi->statistics;
1244 u32 speed_hz = xfer->speed_hz;
1245 unsigned long long ms;
1247 if (spi_controller_is_slave(ctlr)) {
1248 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1249 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1257 * For each byte we wait for 8 cycles of the SPI clock.
1258 * Since speed is defined in Hz and we want milliseconds,
1259 * use respective multiplier, but before the division,
1260 * otherwise we may get 0 for short transfers.
1262 ms = 8LL * MSEC_PER_SEC * xfer->len;
1263 do_div(ms, speed_hz);
1266 * Increase it twice and add 200 ms tolerance, use
1267 * predefined maximum in case of overflow.
1273 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1274 msecs_to_jiffies(ms));
1277 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1278 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1279 dev_err(&msg->spi->dev,
1280 "SPI transfer timed out\n");
1288 static void _spi_transfer_delay_ns(u32 ns)
1292 if (ns <= NSEC_PER_USEC) {
1295 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1300 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1304 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1306 u32 delay = _delay->value;
1307 u32 unit = _delay->unit;
1314 case SPI_DELAY_UNIT_USECS:
1315 delay *= NSEC_PER_USEC;
1317 case SPI_DELAY_UNIT_NSECS:
1318 /* Nothing to do here */
1320 case SPI_DELAY_UNIT_SCK:
1321 /* clock cycles need to be obtained from spi_transfer */
1325 * If there is unknown effective speed, approximate it
1326 * by underestimating with half of the requested hz.
1328 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1332 /* Convert delay to nanoseconds */
1333 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1341 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1343 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1352 delay = spi_delay_to_ns(_delay, xfer);
1356 _spi_transfer_delay_ns(delay);
1360 EXPORT_SYMBOL_GPL(spi_delay_exec);
1362 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1363 struct spi_transfer *xfer)
1365 u32 default_delay_ns = 10 * NSEC_PER_USEC;
1366 u32 delay = xfer->cs_change_delay.value;
1367 u32 unit = xfer->cs_change_delay.unit;
1370 /* return early on "fast" mode - for everything but USECS */
1372 if (unit == SPI_DELAY_UNIT_USECS)
1373 _spi_transfer_delay_ns(default_delay_ns);
1377 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1379 dev_err_once(&msg->spi->dev,
1380 "Use of unsupported delay unit %i, using default of %luus\n",
1381 unit, default_delay_ns / NSEC_PER_USEC);
1382 _spi_transfer_delay_ns(default_delay_ns);
1387 * spi_transfer_one_message - Default implementation of transfer_one_message()
1389 * This is a standard implementation of transfer_one_message() for
1390 * drivers which implement a transfer_one() operation. It provides
1391 * standard handling of delays and chip select management.
1393 static int spi_transfer_one_message(struct spi_controller *ctlr,
1394 struct spi_message *msg)
1396 struct spi_transfer *xfer;
1397 bool keep_cs = false;
1399 struct spi_statistics *statm = &ctlr->statistics;
1400 struct spi_statistics *stats = &msg->spi->statistics;
1402 spi_set_cs(msg->spi, true, false);
1404 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1405 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1407 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1408 trace_spi_transfer_start(msg, xfer);
1410 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1411 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1413 if (!ctlr->ptp_sts_supported) {
1414 xfer->ptp_sts_word_pre = 0;
1415 ptp_read_system_prets(xfer->ptp_sts);
1418 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1419 reinit_completion(&ctlr->xfer_completion);
1422 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1424 if (ctlr->cur_msg_mapped &&
1425 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1426 __spi_unmap_msg(ctlr, msg);
1427 ctlr->fallback = true;
1428 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1432 SPI_STATISTICS_INCREMENT_FIELD(statm,
1434 SPI_STATISTICS_INCREMENT_FIELD(stats,
1436 dev_err(&msg->spi->dev,
1437 "SPI transfer failed: %d\n", ret);
1442 ret = spi_transfer_wait(ctlr, msg, xfer);
1448 dev_err(&msg->spi->dev,
1449 "Bufferless transfer has length %u\n",
1453 if (!ctlr->ptp_sts_supported) {
1454 ptp_read_system_postts(xfer->ptp_sts);
1455 xfer->ptp_sts_word_post = xfer->len;
1458 trace_spi_transfer_stop(msg, xfer);
1460 if (msg->status != -EINPROGRESS)
1463 spi_transfer_delay_exec(xfer);
1465 if (xfer->cs_change) {
1466 if (list_is_last(&xfer->transfer_list,
1470 spi_set_cs(msg->spi, false, false);
1471 _spi_transfer_cs_change_delay(msg, xfer);
1472 spi_set_cs(msg->spi, true, false);
1476 msg->actual_length += xfer->len;
1480 if (ret != 0 || !keep_cs)
1481 spi_set_cs(msg->spi, false, false);
1483 if (msg->status == -EINPROGRESS)
1486 if (msg->status && ctlr->handle_err)
1487 ctlr->handle_err(ctlr, msg);
1489 spi_finalize_current_message(ctlr);
1495 * spi_finalize_current_transfer - report completion of a transfer
1496 * @ctlr: the controller reporting completion
1498 * Called by SPI drivers using the core transfer_one_message()
1499 * implementation to notify it that the current interrupt driven
1500 * transfer has finished and the next one may be scheduled.
1502 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1504 complete(&ctlr->xfer_completion);
1506 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1508 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1510 if (ctlr->auto_runtime_pm) {
1511 pm_runtime_mark_last_busy(ctlr->dev.parent);
1512 pm_runtime_put_autosuspend(ctlr->dev.parent);
1517 * __spi_pump_messages - function which processes spi message queue
1518 * @ctlr: controller to process queue for
1519 * @in_kthread: true if we are in the context of the message pump thread
1521 * This function checks if there is any spi message in the queue that
1522 * needs processing and if so call out to the driver to initialize hardware
1523 * and transfer each message.
1525 * Note that it is called both from the kthread itself and also from
1526 * inside spi_sync(); the queue extraction handling at the top of the
1527 * function should deal with this safely.
1529 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1531 struct spi_transfer *xfer;
1532 struct spi_message *msg;
1533 bool was_busy = false;
1534 unsigned long flags;
1538 spin_lock_irqsave(&ctlr->queue_lock, flags);
1540 /* Make sure we are not already running a message */
1541 if (ctlr->cur_msg) {
1542 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1546 /* If another context is idling the device then defer */
1548 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1549 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1553 /* Check if the queue is idle */
1554 if (list_empty(&ctlr->queue) || !ctlr->running) {
1556 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1560 /* Defer any non-atomic teardown to the thread */
1562 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1563 !ctlr->unprepare_transfer_hardware) {
1564 spi_idle_runtime_pm(ctlr);
1566 trace_spi_controller_idle(ctlr);
1568 kthread_queue_work(ctlr->kworker,
1569 &ctlr->pump_messages);
1571 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1576 ctlr->idling = true;
1577 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1579 kfree(ctlr->dummy_rx);
1580 ctlr->dummy_rx = NULL;
1581 kfree(ctlr->dummy_tx);
1582 ctlr->dummy_tx = NULL;
1583 if (ctlr->unprepare_transfer_hardware &&
1584 ctlr->unprepare_transfer_hardware(ctlr))
1586 "failed to unprepare transfer hardware\n");
1587 spi_idle_runtime_pm(ctlr);
1588 trace_spi_controller_idle(ctlr);
1590 spin_lock_irqsave(&ctlr->queue_lock, flags);
1591 ctlr->idling = false;
1592 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1596 /* Extract head of queue */
1597 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1598 ctlr->cur_msg = msg;
1600 list_del_init(&msg->queue);
1605 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1607 mutex_lock(&ctlr->io_mutex);
1609 if (!was_busy && ctlr->auto_runtime_pm) {
1610 ret = pm_runtime_get_sync(ctlr->dev.parent);
1612 pm_runtime_put_noidle(ctlr->dev.parent);
1613 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1615 mutex_unlock(&ctlr->io_mutex);
1621 trace_spi_controller_busy(ctlr);
1623 if (!was_busy && ctlr->prepare_transfer_hardware) {
1624 ret = ctlr->prepare_transfer_hardware(ctlr);
1627 "failed to prepare transfer hardware: %d\n",
1630 if (ctlr->auto_runtime_pm)
1631 pm_runtime_put(ctlr->dev.parent);
1634 spi_finalize_current_message(ctlr);
1636 mutex_unlock(&ctlr->io_mutex);
1641 trace_spi_message_start(msg);
1643 if (ctlr->prepare_message) {
1644 ret = ctlr->prepare_message(ctlr, msg);
1646 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1649 spi_finalize_current_message(ctlr);
1652 ctlr->cur_msg_prepared = true;
1655 ret = spi_map_msg(ctlr, msg);
1658 spi_finalize_current_message(ctlr);
1662 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1663 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1664 xfer->ptp_sts_word_pre = 0;
1665 ptp_read_system_prets(xfer->ptp_sts);
1669 ret = ctlr->transfer_one_message(ctlr, msg);
1672 "failed to transfer one message from queue\n");
1677 mutex_unlock(&ctlr->io_mutex);
1679 /* Prod the scheduler in case transfer_one() was busy waiting */
1685 * spi_pump_messages - kthread work function which processes spi message queue
1686 * @work: pointer to kthread work struct contained in the controller struct
1688 static void spi_pump_messages(struct kthread_work *work)
1690 struct spi_controller *ctlr =
1691 container_of(work, struct spi_controller, pump_messages);
1693 __spi_pump_messages(ctlr, true);
1697 * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1698 * @ctlr: Pointer to the spi_controller structure of the driver
1699 * @xfer: Pointer to the transfer being timestamped
1700 * @progress: How many words (not bytes) have been transferred so far
1701 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1702 * transfer, for less jitter in time measurement. Only compatible
1703 * with PIO drivers. If true, must follow up with
1704 * spi_take_timestamp_post or otherwise system will crash.
1705 * WARNING: for fully predictable results, the CPU frequency must
1706 * also be under control (governor).
1708 * This is a helper for drivers to collect the beginning of the TX timestamp
1709 * for the requested byte from the SPI transfer. The frequency with which this
1710 * function must be called (once per word, once for the whole transfer, once
1711 * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1712 * greater than or equal to the requested byte at the time of the call. The
1713 * timestamp is only taken once, at the first such call. It is assumed that
1714 * the driver advances its @tx buffer pointer monotonically.
1716 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1717 struct spi_transfer *xfer,
1718 size_t progress, bool irqs_off)
1723 if (xfer->timestamped)
1726 if (progress > xfer->ptp_sts_word_pre)
1729 /* Capture the resolution of the timestamp */
1730 xfer->ptp_sts_word_pre = progress;
1733 local_irq_save(ctlr->irq_flags);
1737 ptp_read_system_prets(xfer->ptp_sts);
1739 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1742 * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1743 * @ctlr: Pointer to the spi_controller structure of the driver
1744 * @xfer: Pointer to the transfer being timestamped
1745 * @progress: How many words (not bytes) have been transferred so far
1746 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1748 * This is a helper for drivers to collect the end of the TX timestamp for
1749 * the requested byte from the SPI transfer. Can be called with an arbitrary
1750 * frequency: only the first call where @tx exceeds or is equal to the
1751 * requested word will be timestamped.
1753 void spi_take_timestamp_post(struct spi_controller *ctlr,
1754 struct spi_transfer *xfer,
1755 size_t progress, bool irqs_off)
1760 if (xfer->timestamped)
1763 if (progress < xfer->ptp_sts_word_post)
1766 ptp_read_system_postts(xfer->ptp_sts);
1769 local_irq_restore(ctlr->irq_flags);
1773 /* Capture the resolution of the timestamp */
1774 xfer->ptp_sts_word_post = progress;
1776 xfer->timestamped = true;
1778 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1781 * spi_set_thread_rt - set the controller to pump at realtime priority
1782 * @ctlr: controller to boost priority of
1784 * This can be called because the controller requested realtime priority
1785 * (by setting the ->rt value before calling spi_register_controller()) or
1786 * because a device on the bus said that its transfers needed realtime
1789 * NOTE: at the moment if any device on a bus says it needs realtime then
1790 * the thread will be at realtime priority for all transfers on that
1791 * controller. If this eventually becomes a problem we may see if we can
1792 * find a way to boost the priority only temporarily during relevant
1795 static void spi_set_thread_rt(struct spi_controller *ctlr)
1797 dev_info(&ctlr->dev,
1798 "will run message pump with realtime priority\n");
1799 sched_set_fifo(ctlr->kworker->task);
1802 static int spi_init_queue(struct spi_controller *ctlr)
1804 ctlr->running = false;
1807 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1808 if (IS_ERR(ctlr->kworker)) {
1809 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1810 return PTR_ERR(ctlr->kworker);
1813 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1816 * Controller config will indicate if this controller should run the
1817 * message pump with high (realtime) priority to reduce the transfer
1818 * latency on the bus by minimising the delay between a transfer
1819 * request and the scheduling of the message pump thread. Without this
1820 * setting the message pump thread will remain at default priority.
1823 spi_set_thread_rt(ctlr);
1829 * spi_get_next_queued_message() - called by driver to check for queued
1831 * @ctlr: the controller to check for queued messages
1833 * If there are more messages in the queue, the next message is returned from
1836 * Return: the next message in the queue, else NULL if the queue is empty.
1838 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1840 struct spi_message *next;
1841 unsigned long flags;
1843 /* get a pointer to the next message, if any */
1844 spin_lock_irqsave(&ctlr->queue_lock, flags);
1845 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1847 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1851 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1854 * spi_finalize_current_message() - the current message is complete
1855 * @ctlr: the controller to return the message to
1857 * Called by the driver to notify the core that the message in the front of the
1858 * queue is complete and can be removed from the queue.
1860 void spi_finalize_current_message(struct spi_controller *ctlr)
1862 struct spi_transfer *xfer;
1863 struct spi_message *mesg;
1864 unsigned long flags;
1867 spin_lock_irqsave(&ctlr->queue_lock, flags);
1868 mesg = ctlr->cur_msg;
1869 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1871 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1872 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1873 ptp_read_system_postts(xfer->ptp_sts);
1874 xfer->ptp_sts_word_post = xfer->len;
1878 if (unlikely(ctlr->ptp_sts_supported))
1879 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1880 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1882 spi_unmap_msg(ctlr, mesg);
1885 * In the prepare_messages callback the SPI bus has the opportunity
1886 * to split a transfer to smaller chunks.
1888 * Release the split transfers here since spi_map_msg() is done on
1889 * the split transfers.
1891 spi_res_release(ctlr, mesg);
1893 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1894 ret = ctlr->unprepare_message(ctlr, mesg);
1896 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1901 spin_lock_irqsave(&ctlr->queue_lock, flags);
1902 ctlr->cur_msg = NULL;
1903 ctlr->cur_msg_prepared = false;
1904 ctlr->fallback = false;
1905 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1906 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1908 trace_spi_message_done(mesg);
1912 mesg->complete(mesg->context);
1914 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1916 static int spi_start_queue(struct spi_controller *ctlr)
1918 unsigned long flags;
1920 spin_lock_irqsave(&ctlr->queue_lock, flags);
1922 if (ctlr->running || ctlr->busy) {
1923 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1927 ctlr->running = true;
1928 ctlr->cur_msg = NULL;
1929 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1931 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1936 static int spi_stop_queue(struct spi_controller *ctlr)
1938 unsigned long flags;
1939 unsigned limit = 500;
1942 spin_lock_irqsave(&ctlr->queue_lock, flags);
1945 * This is a bit lame, but is optimized for the common execution path.
1946 * A wait_queue on the ctlr->busy could be used, but then the common
1947 * execution path (pump_messages) would be required to call wake_up or
1948 * friends on every SPI message. Do this instead.
1950 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1951 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1952 usleep_range(10000, 11000);
1953 spin_lock_irqsave(&ctlr->queue_lock, flags);
1956 if (!list_empty(&ctlr->queue) || ctlr->busy)
1959 ctlr->running = false;
1961 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1964 dev_warn(&ctlr->dev, "could not stop message queue\n");
1970 static int spi_destroy_queue(struct spi_controller *ctlr)
1974 ret = spi_stop_queue(ctlr);
1977 * kthread_flush_worker will block until all work is done.
1978 * If the reason that stop_queue timed out is that the work will never
1979 * finish, then it does no good to call flush/stop thread, so
1983 dev_err(&ctlr->dev, "problem destroying queue\n");
1987 kthread_destroy_worker(ctlr->kworker);
1992 static int __spi_queued_transfer(struct spi_device *spi,
1993 struct spi_message *msg,
1996 struct spi_controller *ctlr = spi->controller;
1997 unsigned long flags;
1999 spin_lock_irqsave(&ctlr->queue_lock, flags);
2001 if (!ctlr->running) {
2002 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2005 msg->actual_length = 0;
2006 msg->status = -EINPROGRESS;
2008 list_add_tail(&msg->queue, &ctlr->queue);
2009 if (!ctlr->busy && need_pump)
2010 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2012 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2017 * spi_queued_transfer - transfer function for queued transfers
2018 * @spi: spi device which is requesting transfer
2019 * @msg: spi message which is to handled is queued to driver queue
2021 * Return: zero on success, else a negative error code.
2023 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
2025 return __spi_queued_transfer(spi, msg, true);
2028 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2032 ctlr->transfer = spi_queued_transfer;
2033 if (!ctlr->transfer_one_message)
2034 ctlr->transfer_one_message = spi_transfer_one_message;
2036 /* Initialize and start queue */
2037 ret = spi_init_queue(ctlr);
2039 dev_err(&ctlr->dev, "problem initializing queue\n");
2040 goto err_init_queue;
2042 ctlr->queued = true;
2043 ret = spi_start_queue(ctlr);
2045 dev_err(&ctlr->dev, "problem starting queue\n");
2046 goto err_start_queue;
2052 spi_destroy_queue(ctlr);
2058 * spi_flush_queue - Send all pending messages in the queue from the callers'
2060 * @ctlr: controller to process queue for
2062 * This should be used when one wants to ensure all pending messages have been
2063 * sent before doing something. Is used by the spi-mem code to make sure SPI
2064 * memory operations do not preempt regular SPI transfers that have been queued
2065 * before the spi-mem operation.
2067 void spi_flush_queue(struct spi_controller *ctlr)
2069 if (ctlr->transfer == spi_queued_transfer)
2070 __spi_pump_messages(ctlr, false);
2073 /*-------------------------------------------------------------------------*/
2075 #if defined(CONFIG_OF)
2076 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2077 struct device_node *nc)
2082 /* Mode (clock phase/polarity/etc.) */
2083 if (of_property_read_bool(nc, "spi-cpha"))
2084 spi->mode |= SPI_CPHA;
2085 if (of_property_read_bool(nc, "spi-cpol"))
2086 spi->mode |= SPI_CPOL;
2087 if (of_property_read_bool(nc, "spi-3wire"))
2088 spi->mode |= SPI_3WIRE;
2089 if (of_property_read_bool(nc, "spi-lsb-first"))
2090 spi->mode |= SPI_LSB_FIRST;
2091 if (of_property_read_bool(nc, "spi-cs-high"))
2092 spi->mode |= SPI_CS_HIGH;
2094 /* Device DUAL/QUAD mode */
2095 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2098 spi->mode |= SPI_NO_TX;
2103 spi->mode |= SPI_TX_DUAL;
2106 spi->mode |= SPI_TX_QUAD;
2109 spi->mode |= SPI_TX_OCTAL;
2112 dev_warn(&ctlr->dev,
2113 "spi-tx-bus-width %d not supported\n",
2119 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2122 spi->mode |= SPI_NO_RX;
2127 spi->mode |= SPI_RX_DUAL;
2130 spi->mode |= SPI_RX_QUAD;
2133 spi->mode |= SPI_RX_OCTAL;
2136 dev_warn(&ctlr->dev,
2137 "spi-rx-bus-width %d not supported\n",
2143 if (spi_controller_is_slave(ctlr)) {
2144 if (!of_node_name_eq(nc, "slave")) {
2145 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2152 /* Device address */
2153 rc = of_property_read_u32(nc, "reg", &value);
2155 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2159 spi->chip_select = value;
2162 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2163 spi->max_speed_hz = value;
2168 static struct spi_device *
2169 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2171 struct spi_device *spi;
2174 /* Alloc an spi_device */
2175 spi = spi_alloc_device(ctlr);
2177 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2182 /* Select device driver */
2183 rc = of_modalias_node(nc, spi->modalias,
2184 sizeof(spi->modalias));
2186 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2190 rc = of_spi_parse_dt(ctlr, spi, nc);
2194 /* Store a pointer to the node in the device structure */
2196 spi->dev.of_node = nc;
2197 spi->dev.fwnode = of_fwnode_handle(nc);
2199 /* Register the new device */
2200 rc = spi_add_device(spi);
2202 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2203 goto err_of_node_put;
2216 * of_register_spi_devices() - Register child devices onto the SPI bus
2217 * @ctlr: Pointer to spi_controller device
2219 * Registers an spi_device for each child node of controller node which
2220 * represents a valid SPI slave.
2222 static void of_register_spi_devices(struct spi_controller *ctlr)
2224 struct spi_device *spi;
2225 struct device_node *nc;
2227 if (!ctlr->dev.of_node)
2230 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2231 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2233 spi = of_register_spi_device(ctlr, nc);
2235 dev_warn(&ctlr->dev,
2236 "Failed to create SPI device for %pOF\n", nc);
2237 of_node_clear_flag(nc, OF_POPULATED);
2242 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2246 * spi_new_ancillary_device() - Register ancillary SPI device
2247 * @spi: Pointer to the main SPI device registering the ancillary device
2248 * @chip_select: Chip Select of the ancillary device
2250 * Register an ancillary SPI device; for example some chips have a chip-select
2251 * for normal device usage and another one for setup/firmware upload.
2253 * This may only be called from main SPI device's probe routine.
2255 * Return: 0 on success; negative errno on failure
2257 struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2260 struct spi_device *ancillary;
2263 /* Alloc an spi_device */
2264 ancillary = spi_alloc_device(spi->controller);
2270 strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2272 /* Use provided chip-select for ancillary device */
2273 ancillary->chip_select = chip_select;
2275 /* Take over SPI mode/speed from SPI main device */
2276 ancillary->max_speed_hz = spi->max_speed_hz;
2277 ancillary->mode = spi->mode;
2279 /* Register the new device */
2280 rc = spi_add_device_locked(ancillary);
2282 dev_err(&spi->dev, "failed to register ancillary device\n");
2289 spi_dev_put(ancillary);
2292 EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2295 struct acpi_spi_lookup {
2296 struct spi_controller *ctlr;
2306 static int acpi_spi_count(struct acpi_resource *ares, void *data)
2308 struct acpi_resource_spi_serialbus *sb;
2311 if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2314 sb = &ares->data.spi_serial_bus;
2315 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2318 *count = *count + 1;
2324 * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2325 * @adev: ACPI device
2327 * Returns the number of SpiSerialBus resources in the ACPI-device's
2328 * resource-list; or a negative error code.
2330 int acpi_spi_count_resources(struct acpi_device *adev)
2336 ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2340 acpi_dev_free_resource_list(&r);
2344 EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2346 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2347 struct acpi_spi_lookup *lookup)
2349 const union acpi_object *obj;
2351 if (!x86_apple_machine)
2354 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2355 && obj->buffer.length >= 4)
2356 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2358 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2359 && obj->buffer.length == 8)
2360 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2362 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2363 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2364 lookup->mode |= SPI_LSB_FIRST;
2366 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2367 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2368 lookup->mode |= SPI_CPOL;
2370 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2371 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2372 lookup->mode |= SPI_CPHA;
2375 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
2377 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2379 struct acpi_spi_lookup *lookup = data;
2380 struct spi_controller *ctlr = lookup->ctlr;
2382 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2383 struct acpi_resource_spi_serialbus *sb;
2384 acpi_handle parent_handle;
2387 sb = &ares->data.spi_serial_bus;
2388 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2390 if (lookup->index != -1 && lookup->n++ != lookup->index)
2393 if (lookup->index == -1 && !ctlr)
2396 status = acpi_get_handle(NULL,
2397 sb->resource_source.string_ptr,
2400 if (ACPI_FAILURE(status))
2404 if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2407 struct acpi_device *adev;
2409 if (acpi_bus_get_device(parent_handle, &adev))
2412 ctlr = acpi_spi_find_controller_by_adev(adev);
2416 lookup->ctlr = ctlr;
2420 * ACPI DeviceSelection numbering is handled by the
2421 * host controller driver in Windows and can vary
2422 * from driver to driver. In Linux we always expect
2423 * 0 .. max - 1 so we need to ask the driver to
2424 * translate between the two schemes.
2426 if (ctlr->fw_translate_cs) {
2427 int cs = ctlr->fw_translate_cs(ctlr,
2428 sb->device_selection);
2431 lookup->chip_select = cs;
2433 lookup->chip_select = sb->device_selection;
2436 lookup->max_speed_hz = sb->connection_speed;
2437 lookup->bits_per_word = sb->data_bit_length;
2439 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2440 lookup->mode |= SPI_CPHA;
2441 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2442 lookup->mode |= SPI_CPOL;
2443 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2444 lookup->mode |= SPI_CS_HIGH;
2446 } else if (lookup->irq < 0) {
2449 if (acpi_dev_resource_interrupt(ares, 0, &r))
2450 lookup->irq = r.start;
2453 /* Always tell the ACPI core to skip this resource */
2458 * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2459 * @ctlr: controller to which the spi device belongs
2460 * @adev: ACPI Device for the spi device
2461 * @index: Index of the spi resource inside the ACPI Node
2463 * This should be used to allocate a new spi device from and ACPI Node.
2464 * The caller is responsible for calling spi_add_device to register the spi device.
2466 * If ctlr is set to NULL, the Controller for the spi device will be looked up
2467 * using the resource.
2468 * If index is set to -1, index is not used.
2469 * Note: If index is -1, ctlr must be set.
2471 * Return: a pointer to the new device, or ERR_PTR on error.
2473 struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
2474 struct acpi_device *adev,
2477 acpi_handle parent_handle = NULL;
2478 struct list_head resource_list;
2479 struct acpi_spi_lookup lookup = {};
2480 struct spi_device *spi;
2483 if (!ctlr && index == -1)
2484 return ERR_PTR(-EINVAL);
2488 lookup.index = index;
2491 INIT_LIST_HEAD(&resource_list);
2492 ret = acpi_dev_get_resources(adev, &resource_list,
2493 acpi_spi_add_resource, &lookup);
2494 acpi_dev_free_resource_list(&resource_list);
2497 /* found SPI in _CRS but it points to another controller */
2498 return ERR_PTR(-ENODEV);
2500 if (!lookup.max_speed_hz &&
2501 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2502 ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
2503 /* Apple does not use _CRS but nested devices for SPI slaves */
2504 acpi_spi_parse_apple_properties(adev, &lookup);
2507 if (!lookup.max_speed_hz)
2508 return ERR_PTR(-ENODEV);
2510 spi = spi_alloc_device(lookup.ctlr);
2512 dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
2513 dev_name(&adev->dev));
2514 return ERR_PTR(-ENOMEM);
2517 ACPI_COMPANION_SET(&spi->dev, adev);
2518 spi->max_speed_hz = lookup.max_speed_hz;
2519 spi->mode |= lookup.mode;
2520 spi->irq = lookup.irq;
2521 spi->bits_per_word = lookup.bits_per_word;
2522 spi->chip_select = lookup.chip_select;
2526 EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2528 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2529 struct acpi_device *adev)
2531 struct spi_device *spi;
2533 if (acpi_bus_get_status(adev) || !adev->status.present ||
2534 acpi_device_enumerated(adev))
2537 spi = acpi_spi_device_alloc(ctlr, adev, -1);
2539 if (PTR_ERR(spi) == -ENOMEM)
2540 return AE_NO_MEMORY;
2545 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2546 sizeof(spi->modalias));
2549 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2551 acpi_device_set_enumerated(adev);
2553 adev->power.flags.ignore_parent = true;
2554 if (spi_add_device(spi)) {
2555 adev->power.flags.ignore_parent = false;
2556 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2557 dev_name(&adev->dev));
2564 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2565 void *data, void **return_value)
2567 struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
2568 struct spi_controller *ctlr = data;
2573 return acpi_register_spi_device(ctlr, adev);
2576 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2578 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2583 handle = ACPI_HANDLE(ctlr->dev.parent);
2587 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2588 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2589 acpi_spi_add_device, NULL, ctlr, NULL);
2590 if (ACPI_FAILURE(status))
2591 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2594 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2595 #endif /* CONFIG_ACPI */
2597 static void spi_controller_release(struct device *dev)
2599 struct spi_controller *ctlr;
2601 ctlr = container_of(dev, struct spi_controller, dev);
2605 static struct class spi_master_class = {
2606 .name = "spi_master",
2607 .owner = THIS_MODULE,
2608 .dev_release = spi_controller_release,
2609 .dev_groups = spi_master_groups,
2612 #ifdef CONFIG_SPI_SLAVE
2614 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2616 * @spi: device used for the current transfer
2618 int spi_slave_abort(struct spi_device *spi)
2620 struct spi_controller *ctlr = spi->controller;
2622 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2623 return ctlr->slave_abort(ctlr);
2627 EXPORT_SYMBOL_GPL(spi_slave_abort);
2629 static int match_true(struct device *dev, void *data)
2634 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2637 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2639 struct device *child;
2641 child = device_find_child(&ctlr->dev, NULL, match_true);
2642 return sprintf(buf, "%s\n",
2643 child ? to_spi_device(child)->modalias : NULL);
2646 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2647 const char *buf, size_t count)
2649 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2651 struct spi_device *spi;
2652 struct device *child;
2656 rc = sscanf(buf, "%31s", name);
2657 if (rc != 1 || !name[0])
2660 child = device_find_child(&ctlr->dev, NULL, match_true);
2662 /* Remove registered slave */
2663 device_unregister(child);
2667 if (strcmp(name, "(null)")) {
2668 /* Register new slave */
2669 spi = spi_alloc_device(ctlr);
2673 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2675 rc = spi_add_device(spi);
2685 static DEVICE_ATTR_RW(slave);
2687 static struct attribute *spi_slave_attrs[] = {
2688 &dev_attr_slave.attr,
2692 static const struct attribute_group spi_slave_group = {
2693 .attrs = spi_slave_attrs,
2696 static const struct attribute_group *spi_slave_groups[] = {
2697 &spi_controller_statistics_group,
2702 static struct class spi_slave_class = {
2703 .name = "spi_slave",
2704 .owner = THIS_MODULE,
2705 .dev_release = spi_controller_release,
2706 .dev_groups = spi_slave_groups,
2709 extern struct class spi_slave_class; /* dummy */
2713 * __spi_alloc_controller - allocate an SPI master or slave controller
2714 * @dev: the controller, possibly using the platform_bus
2715 * @size: how much zeroed driver-private data to allocate; the pointer to this
2716 * memory is in the driver_data field of the returned device, accessible
2717 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2718 * drivers granting DMA access to portions of their private data need to
2719 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2720 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2721 * slave (true) controller
2722 * Context: can sleep
2724 * This call is used only by SPI controller drivers, which are the
2725 * only ones directly touching chip registers. It's how they allocate
2726 * an spi_controller structure, prior to calling spi_register_controller().
2728 * This must be called from context that can sleep.
2730 * The caller is responsible for assigning the bus number and initializing the
2731 * controller's methods before calling spi_register_controller(); and (after
2732 * errors adding the device) calling spi_controller_put() to prevent a memory
2735 * Return: the SPI controller structure on success, else NULL.
2737 struct spi_controller *__spi_alloc_controller(struct device *dev,
2738 unsigned int size, bool slave)
2740 struct spi_controller *ctlr;
2741 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2746 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2750 device_initialize(&ctlr->dev);
2751 INIT_LIST_HEAD(&ctlr->queue);
2752 spin_lock_init(&ctlr->queue_lock);
2753 spin_lock_init(&ctlr->bus_lock_spinlock);
2754 mutex_init(&ctlr->bus_lock_mutex);
2755 mutex_init(&ctlr->io_mutex);
2756 mutex_init(&ctlr->add_lock);
2758 ctlr->num_chipselect = 1;
2759 ctlr->slave = slave;
2760 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2761 ctlr->dev.class = &spi_slave_class;
2763 ctlr->dev.class = &spi_master_class;
2764 ctlr->dev.parent = dev;
2765 pm_suspend_ignore_children(&ctlr->dev, true);
2766 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2770 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2772 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2774 spi_controller_put(*(struct spi_controller **)ctlr);
2778 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2779 * @dev: physical device of SPI controller
2780 * @size: how much zeroed driver-private data to allocate
2781 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2782 * Context: can sleep
2784 * Allocate an SPI controller and automatically release a reference on it
2785 * when @dev is unbound from its driver. Drivers are thus relieved from
2786 * having to call spi_controller_put().
2788 * The arguments to this function are identical to __spi_alloc_controller().
2790 * Return: the SPI controller structure on success, else NULL.
2792 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2796 struct spi_controller **ptr, *ctlr;
2798 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2803 ctlr = __spi_alloc_controller(dev, size, slave);
2805 ctlr->devm_allocated = true;
2807 devres_add(dev, ptr);
2814 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2817 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2818 * @ctlr: The SPI master to grab GPIO descriptors for
2820 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2823 struct gpio_desc **cs;
2824 struct device *dev = &ctlr->dev;
2825 unsigned long native_cs_mask = 0;
2826 unsigned int num_cs_gpios = 0;
2828 nb = gpiod_count(dev, "cs");
2830 /* No GPIOs at all is fine, else return the error */
2836 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2838 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2842 ctlr->cs_gpiods = cs;
2844 for (i = 0; i < nb; i++) {
2846 * Most chipselects are active low, the inverted
2847 * semantics are handled by special quirks in gpiolib,
2848 * so initializing them GPIOD_OUT_LOW here means
2849 * "unasserted", in most cases this will drive the physical
2852 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2855 return PTR_ERR(cs[i]);
2859 * If we find a CS GPIO, name it after the device and
2864 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2868 gpiod_set_consumer_name(cs[i], gpioname);
2873 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2874 dev_err(dev, "Invalid native chip select %d\n", i);
2877 native_cs_mask |= BIT(i);
2880 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2882 if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2883 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2884 dev_err(dev, "No unused native chip select available\n");
2891 static int spi_controller_check_ops(struct spi_controller *ctlr)
2894 * The controller may implement only the high-level SPI-memory like
2895 * operations if it does not support regular SPI transfers, and this is
2897 * If ->mem_ops is NULL, we request that at least one of the
2898 * ->transfer_xxx() method be implemented.
2900 if (ctlr->mem_ops) {
2901 if (!ctlr->mem_ops->exec_op)
2903 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2904 !ctlr->transfer_one_message) {
2912 * spi_register_controller - register SPI master or slave controller
2913 * @ctlr: initialized master, originally from spi_alloc_master() or
2915 * Context: can sleep
2917 * SPI controllers connect to their drivers using some non-SPI bus,
2918 * such as the platform bus. The final stage of probe() in that code
2919 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2921 * SPI controllers use board specific (often SOC specific) bus numbers,
2922 * and board-specific addressing for SPI devices combines those numbers
2923 * with chip select numbers. Since SPI does not directly support dynamic
2924 * device identification, boards need configuration tables telling which
2925 * chip is at which address.
2927 * This must be called from context that can sleep. It returns zero on
2928 * success, else a negative error code (dropping the controller's refcount).
2929 * After a successful return, the caller is responsible for calling
2930 * spi_unregister_controller().
2932 * Return: zero on success, else a negative error code.
2934 int spi_register_controller(struct spi_controller *ctlr)
2936 struct device *dev = ctlr->dev.parent;
2937 struct boardinfo *bi;
2939 int id, first_dynamic;
2945 * Make sure all necessary hooks are implemented before registering
2946 * the SPI controller.
2948 status = spi_controller_check_ops(ctlr);
2952 if (ctlr->bus_num >= 0) {
2953 /* devices with a fixed bus num must check-in with the num */
2954 mutex_lock(&board_lock);
2955 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2956 ctlr->bus_num + 1, GFP_KERNEL);
2957 mutex_unlock(&board_lock);
2958 if (WARN(id < 0, "couldn't get idr"))
2959 return id == -ENOSPC ? -EBUSY : id;
2961 } else if (ctlr->dev.of_node) {
2962 /* allocate dynamic bus number using Linux idr */
2963 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2966 mutex_lock(&board_lock);
2967 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2968 ctlr->bus_num + 1, GFP_KERNEL);
2969 mutex_unlock(&board_lock);
2970 if (WARN(id < 0, "couldn't get idr"))
2971 return id == -ENOSPC ? -EBUSY : id;
2974 if (ctlr->bus_num < 0) {
2975 first_dynamic = of_alias_get_highest_id("spi");
2976 if (first_dynamic < 0)
2981 mutex_lock(&board_lock);
2982 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2984 mutex_unlock(&board_lock);
2985 if (WARN(id < 0, "couldn't get idr"))
2989 ctlr->bus_lock_flag = 0;
2990 init_completion(&ctlr->xfer_completion);
2991 if (!ctlr->max_dma_len)
2992 ctlr->max_dma_len = INT_MAX;
2995 * Register the device, then userspace will see it.
2996 * Registration fails if the bus ID is in use.
2998 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
3000 if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
3001 status = spi_get_gpio_descs(ctlr);
3005 * A controller using GPIO descriptors always
3006 * supports SPI_CS_HIGH if need be.
3008 ctlr->mode_bits |= SPI_CS_HIGH;
3012 * Even if it's just one always-selected device, there must
3013 * be at least one chipselect.
3015 if (!ctlr->num_chipselect) {
3020 /* setting last_cs to -1 means no chip selected */
3023 status = device_add(&ctlr->dev);
3026 dev_dbg(dev, "registered %s %s\n",
3027 spi_controller_is_slave(ctlr) ? "slave" : "master",
3028 dev_name(&ctlr->dev));
3031 * If we're using a queued driver, start the queue. Note that we don't
3032 * need the queueing logic if the driver is only supporting high-level
3033 * memory operations.
3035 if (ctlr->transfer) {
3036 dev_info(dev, "controller is unqueued, this is deprecated\n");
3037 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
3038 status = spi_controller_initialize_queue(ctlr);
3040 device_del(&ctlr->dev);
3044 /* add statistics */
3045 spin_lock_init(&ctlr->statistics.lock);
3047 mutex_lock(&board_lock);
3048 list_add_tail(&ctlr->list, &spi_controller_list);
3049 list_for_each_entry(bi, &board_list, list)
3050 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
3051 mutex_unlock(&board_lock);
3053 /* Register devices from the device tree and ACPI */
3054 of_register_spi_devices(ctlr);
3055 acpi_register_spi_devices(ctlr);
3059 mutex_lock(&board_lock);
3060 idr_remove(&spi_master_idr, ctlr->bus_num);
3061 mutex_unlock(&board_lock);
3064 EXPORT_SYMBOL_GPL(spi_register_controller);
3066 static void devm_spi_unregister(void *ctlr)
3068 spi_unregister_controller(ctlr);
3072 * devm_spi_register_controller - register managed SPI master or slave
3074 * @dev: device managing SPI controller
3075 * @ctlr: initialized controller, originally from spi_alloc_master() or
3077 * Context: can sleep
3079 * Register a SPI device as with spi_register_controller() which will
3080 * automatically be unregistered and freed.
3082 * Return: zero on success, else a negative error code.
3084 int devm_spi_register_controller(struct device *dev,
3085 struct spi_controller *ctlr)
3089 ret = spi_register_controller(ctlr);
3093 return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
3095 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3097 static int __unregister(struct device *dev, void *null)
3099 spi_unregister_device(to_spi_device(dev));
3104 * spi_unregister_controller - unregister SPI master or slave controller
3105 * @ctlr: the controller being unregistered
3106 * Context: can sleep
3108 * This call is used only by SPI controller drivers, which are the
3109 * only ones directly touching chip registers.
3111 * This must be called from context that can sleep.
3113 * Note that this function also drops a reference to the controller.
3115 void spi_unregister_controller(struct spi_controller *ctlr)
3117 struct spi_controller *found;
3118 int id = ctlr->bus_num;
3120 /* Prevent addition of new devices, unregister existing ones */
3121 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3122 mutex_lock(&ctlr->add_lock);
3124 device_for_each_child(&ctlr->dev, NULL, __unregister);
3126 /* First make sure that this controller was ever added */
3127 mutex_lock(&board_lock);
3128 found = idr_find(&spi_master_idr, id);
3129 mutex_unlock(&board_lock);
3131 if (spi_destroy_queue(ctlr))
3132 dev_err(&ctlr->dev, "queue remove failed\n");
3134 mutex_lock(&board_lock);
3135 list_del(&ctlr->list);
3136 mutex_unlock(&board_lock);
3138 device_del(&ctlr->dev);
3141 mutex_lock(&board_lock);
3143 idr_remove(&spi_master_idr, id);
3144 mutex_unlock(&board_lock);
3146 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3147 mutex_unlock(&ctlr->add_lock);
3149 /* Release the last reference on the controller if its driver
3150 * has not yet been converted to devm_spi_alloc_master/slave().
3152 if (!ctlr->devm_allocated)
3153 put_device(&ctlr->dev);
3155 EXPORT_SYMBOL_GPL(spi_unregister_controller);
3157 int spi_controller_suspend(struct spi_controller *ctlr)
3161 /* Basically no-ops for non-queued controllers */
3165 ret = spi_stop_queue(ctlr);
3167 dev_err(&ctlr->dev, "queue stop failed\n");
3171 EXPORT_SYMBOL_GPL(spi_controller_suspend);
3173 int spi_controller_resume(struct spi_controller *ctlr)
3180 ret = spi_start_queue(ctlr);
3182 dev_err(&ctlr->dev, "queue restart failed\n");
3186 EXPORT_SYMBOL_GPL(spi_controller_resume);
3188 /*-------------------------------------------------------------------------*/
3190 /* Core methods for spi_message alterations */
3192 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3193 struct spi_message *msg,
3196 struct spi_replaced_transfers *rxfer = res;
3199 /* call extra callback if requested */
3201 rxfer->release(ctlr, msg, res);
3203 /* insert replaced transfers back into the message */
3204 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3206 /* remove the formerly inserted entries */
3207 for (i = 0; i < rxfer->inserted; i++)
3208 list_del(&rxfer->inserted_transfers[i].transfer_list);
3212 * spi_replace_transfers - replace transfers with several transfers
3213 * and register change with spi_message.resources
3214 * @msg: the spi_message we work upon
3215 * @xfer_first: the first spi_transfer we want to replace
3216 * @remove: number of transfers to remove
3217 * @insert: the number of transfers we want to insert instead
3218 * @release: extra release code necessary in some circumstances
3219 * @extradatasize: extra data to allocate (with alignment guarantees
3220 * of struct @spi_transfer)
3223 * Returns: pointer to @spi_replaced_transfers,
3224 * PTR_ERR(...) in case of errors.
3226 static struct spi_replaced_transfers *spi_replace_transfers(
3227 struct spi_message *msg,
3228 struct spi_transfer *xfer_first,
3231 spi_replaced_release_t release,
3232 size_t extradatasize,
3235 struct spi_replaced_transfers *rxfer;
3236 struct spi_transfer *xfer;
3239 /* allocate the structure using spi_res */
3240 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3241 struct_size(rxfer, inserted_transfers, insert)
3245 return ERR_PTR(-ENOMEM);
3247 /* the release code to invoke before running the generic release */
3248 rxfer->release = release;
3250 /* assign extradata */
3253 &rxfer->inserted_transfers[insert];
3255 /* init the replaced_transfers list */
3256 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3259 * Assign the list_entry after which we should reinsert
3260 * the @replaced_transfers - it may be spi_message.messages!
3262 rxfer->replaced_after = xfer_first->transfer_list.prev;
3264 /* remove the requested number of transfers */
3265 for (i = 0; i < remove; i++) {
3267 * If the entry after replaced_after it is msg->transfers
3268 * then we have been requested to remove more transfers
3269 * than are in the list.
3271 if (rxfer->replaced_after->next == &msg->transfers) {
3272 dev_err(&msg->spi->dev,
3273 "requested to remove more spi_transfers than are available\n");
3274 /* insert replaced transfers back into the message */
3275 list_splice(&rxfer->replaced_transfers,
3276 rxfer->replaced_after);
3278 /* free the spi_replace_transfer structure */
3279 spi_res_free(rxfer);
3281 /* and return with an error */
3282 return ERR_PTR(-EINVAL);
3286 * Remove the entry after replaced_after from list of
3287 * transfers and add it to list of replaced_transfers.
3289 list_move_tail(rxfer->replaced_after->next,
3290 &rxfer->replaced_transfers);
3294 * Create copy of the given xfer with identical settings
3295 * based on the first transfer to get removed.
3297 for (i = 0; i < insert; i++) {
3298 /* we need to run in reverse order */
3299 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3301 /* copy all spi_transfer data */
3302 memcpy(xfer, xfer_first, sizeof(*xfer));
3305 list_add(&xfer->transfer_list, rxfer->replaced_after);
3307 /* clear cs_change and delay for all but the last */
3309 xfer->cs_change = false;
3310 xfer->delay.value = 0;
3314 /* set up inserted */
3315 rxfer->inserted = insert;
3317 /* and register it with spi_res/spi_message */
3318 spi_res_add(msg, rxfer);
3323 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3324 struct spi_message *msg,
3325 struct spi_transfer **xferp,
3329 struct spi_transfer *xfer = *xferp, *xfers;
3330 struct spi_replaced_transfers *srt;
3334 /* calculate how many we have to replace */
3335 count = DIV_ROUND_UP(xfer->len, maxsize);
3337 /* create replacement */
3338 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3340 return PTR_ERR(srt);
3341 xfers = srt->inserted_transfers;
3344 * Now handle each of those newly inserted spi_transfers.
3345 * Note that the replacements spi_transfers all are preset
3346 * to the same values as *xferp, so tx_buf, rx_buf and len
3347 * are all identical (as well as most others)
3348 * so we just have to fix up len and the pointers.
3350 * This also includes support for the depreciated
3351 * spi_message.is_dma_mapped interface.
3355 * The first transfer just needs the length modified, so we
3356 * run it outside the loop.
3358 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3360 /* all the others need rx_buf/tx_buf also set */
3361 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3362 /* update rx_buf, tx_buf and dma */
3363 if (xfers[i].rx_buf)
3364 xfers[i].rx_buf += offset;
3365 if (xfers[i].rx_dma)
3366 xfers[i].rx_dma += offset;
3367 if (xfers[i].tx_buf)
3368 xfers[i].tx_buf += offset;
3369 if (xfers[i].tx_dma)
3370 xfers[i].tx_dma += offset;
3373 xfers[i].len = min(maxsize, xfers[i].len - offset);
3377 * We set up xferp to the last entry we have inserted,
3378 * so that we skip those already split transfers.
3380 *xferp = &xfers[count - 1];
3382 /* increment statistics counters */
3383 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3384 transfers_split_maxsize);
3385 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3386 transfers_split_maxsize);
3392 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3393 * when an individual transfer exceeds a
3395 * @ctlr: the @spi_controller for this transfer
3396 * @msg: the @spi_message to transform
3397 * @maxsize: the maximum when to apply this
3398 * @gfp: GFP allocation flags
3400 * Return: status of transformation
3402 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3403 struct spi_message *msg,
3407 struct spi_transfer *xfer;
3411 * Iterate over the transfer_list,
3412 * but note that xfer is advanced to the last transfer inserted
3413 * to avoid checking sizes again unnecessarily (also xfer does
3414 * potentially belong to a different list by the time the
3415 * replacement has happened).
3417 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3418 if (xfer->len > maxsize) {
3419 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3428 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3430 /*-------------------------------------------------------------------------*/
3432 /* Core methods for SPI controller protocol drivers. Some of the
3433 * other core methods are currently defined as inline functions.
3436 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3439 if (ctlr->bits_per_word_mask) {
3440 /* Only 32 bits fit in the mask */
3441 if (bits_per_word > 32)
3443 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3451 * spi_setup - setup SPI mode and clock rate
3452 * @spi: the device whose settings are being modified
3453 * Context: can sleep, and no requests are queued to the device
3455 * SPI protocol drivers may need to update the transfer mode if the
3456 * device doesn't work with its default. They may likewise need
3457 * to update clock rates or word sizes from initial values. This function
3458 * changes those settings, and must be called from a context that can sleep.
3459 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3460 * effect the next time the device is selected and data is transferred to
3461 * or from it. When this function returns, the spi device is deselected.
3463 * Note that this call will fail if the protocol driver specifies an option
3464 * that the underlying controller or its driver does not support. For
3465 * example, not all hardware supports wire transfers using nine bit words,
3466 * LSB-first wire encoding, or active-high chipselects.
3468 * Return: zero on success, else a negative error code.
3470 int spi_setup(struct spi_device *spi)
3472 unsigned bad_bits, ugly_bits;
3476 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3477 * are set at the same time.
3479 if ((hweight_long(spi->mode &
3480 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3481 (hweight_long(spi->mode &
3482 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3484 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3487 /* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3488 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3489 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3490 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3493 * Help drivers fail *cleanly* when they need options
3494 * that aren't supported with their current controller.
3495 * SPI_CS_WORD has a fallback software implementation,
3496 * so it is ignored here.
3498 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3499 SPI_NO_TX | SPI_NO_RX);
3500 ugly_bits = bad_bits &
3501 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3502 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3505 "setup: ignoring unsupported mode bits %x\n",
3507 spi->mode &= ~ugly_bits;
3508 bad_bits &= ~ugly_bits;
3511 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3516 if (!spi->bits_per_word)
3517 spi->bits_per_word = 8;
3519 status = __spi_validate_bits_per_word(spi->controller,
3520 spi->bits_per_word);
3524 if (spi->controller->max_speed_hz &&
3525 (!spi->max_speed_hz ||
3526 spi->max_speed_hz > spi->controller->max_speed_hz))
3527 spi->max_speed_hz = spi->controller->max_speed_hz;
3529 mutex_lock(&spi->controller->io_mutex);
3531 if (spi->controller->setup) {
3532 status = spi->controller->setup(spi);
3534 mutex_unlock(&spi->controller->io_mutex);
3535 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3541 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3542 status = pm_runtime_get_sync(spi->controller->dev.parent);
3544 mutex_unlock(&spi->controller->io_mutex);
3545 pm_runtime_put_noidle(spi->controller->dev.parent);
3546 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3552 * We do not want to return positive value from pm_runtime_get,
3553 * there are many instances of devices calling spi_setup() and
3554 * checking for a non-zero return value instead of a negative
3559 spi_set_cs(spi, false, true);
3560 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3561 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3563 spi_set_cs(spi, false, true);
3566 mutex_unlock(&spi->controller->io_mutex);
3568 if (spi->rt && !spi->controller->rt) {
3569 spi->controller->rt = true;
3570 spi_set_thread_rt(spi->controller);
3573 trace_spi_setup(spi, status);
3575 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3576 spi->mode & SPI_MODE_X_MASK,
3577 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3578 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3579 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3580 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3581 spi->bits_per_word, spi->max_speed_hz,
3586 EXPORT_SYMBOL_GPL(spi_setup);
3588 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3589 struct spi_device *spi)
3593 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3597 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3601 if (delay1 < delay2)
3602 memcpy(&xfer->word_delay, &spi->word_delay,
3603 sizeof(xfer->word_delay));
3608 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3610 struct spi_controller *ctlr = spi->controller;
3611 struct spi_transfer *xfer;
3614 if (list_empty(&message->transfers))
3618 * If an SPI controller does not support toggling the CS line on each
3619 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3620 * for the CS line, we can emulate the CS-per-word hardware function by
3621 * splitting transfers into one-word transfers and ensuring that
3622 * cs_change is set for each transfer.
3624 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3629 maxsize = (spi->bits_per_word + 7) / 8;
3631 /* spi_split_transfers_maxsize() requires message->spi */
3634 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3639 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3640 /* don't change cs_change on the last entry in the list */
3641 if (list_is_last(&xfer->transfer_list, &message->transfers))
3643 xfer->cs_change = 1;
3648 * Half-duplex links include original MicroWire, and ones with
3649 * only one data pin like SPI_3WIRE (switches direction) or where
3650 * either MOSI or MISO is missing. They can also be caused by
3651 * software limitations.
3653 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3654 (spi->mode & SPI_3WIRE)) {
3655 unsigned flags = ctlr->flags;
3657 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3658 if (xfer->rx_buf && xfer->tx_buf)
3660 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3662 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3668 * Set transfer bits_per_word and max speed as spi device default if
3669 * it is not set for this transfer.
3670 * Set transfer tx_nbits and rx_nbits as single transfer default
3671 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3672 * Ensure transfer word_delay is at least as long as that required by
3675 message->frame_length = 0;
3676 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3677 xfer->effective_speed_hz = 0;
3678 message->frame_length += xfer->len;
3679 if (!xfer->bits_per_word)
3680 xfer->bits_per_word = spi->bits_per_word;
3682 if (!xfer->speed_hz)
3683 xfer->speed_hz = spi->max_speed_hz;
3685 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3686 xfer->speed_hz = ctlr->max_speed_hz;
3688 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3692 * SPI transfer length should be multiple of SPI word size
3693 * where SPI word size should be power-of-two multiple.
3695 if (xfer->bits_per_word <= 8)
3697 else if (xfer->bits_per_word <= 16)
3702 /* No partial transfers accepted */
3703 if (xfer->len % w_size)
3706 if (xfer->speed_hz && ctlr->min_speed_hz &&
3707 xfer->speed_hz < ctlr->min_speed_hz)
3710 if (xfer->tx_buf && !xfer->tx_nbits)
3711 xfer->tx_nbits = SPI_NBITS_SINGLE;
3712 if (xfer->rx_buf && !xfer->rx_nbits)
3713 xfer->rx_nbits = SPI_NBITS_SINGLE;
3715 * Check transfer tx/rx_nbits:
3716 * 1. check the value matches one of single, dual and quad
3717 * 2. check tx/rx_nbits match the mode in spi_device
3720 if (spi->mode & SPI_NO_TX)
3722 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3723 xfer->tx_nbits != SPI_NBITS_DUAL &&
3724 xfer->tx_nbits != SPI_NBITS_QUAD)
3726 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3727 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3729 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3730 !(spi->mode & SPI_TX_QUAD))
3733 /* check transfer rx_nbits */
3735 if (spi->mode & SPI_NO_RX)
3737 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3738 xfer->rx_nbits != SPI_NBITS_DUAL &&
3739 xfer->rx_nbits != SPI_NBITS_QUAD)
3741 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3742 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3744 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3745 !(spi->mode & SPI_RX_QUAD))
3749 if (_spi_xfer_word_delay_update(xfer, spi))
3753 message->status = -EINPROGRESS;
3758 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3760 struct spi_controller *ctlr = spi->controller;
3761 struct spi_transfer *xfer;
3764 * Some controllers do not support doing regular SPI transfers. Return
3765 * ENOTSUPP when this is the case.
3767 if (!ctlr->transfer)
3772 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3773 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3775 trace_spi_message_submit(message);
3777 if (!ctlr->ptp_sts_supported) {
3778 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3779 xfer->ptp_sts_word_pre = 0;
3780 ptp_read_system_prets(xfer->ptp_sts);
3784 return ctlr->transfer(spi, message);
3788 * spi_async - asynchronous SPI transfer
3789 * @spi: device with which data will be exchanged
3790 * @message: describes the data transfers, including completion callback
3791 * Context: any (irqs may be blocked, etc)
3793 * This call may be used in_irq and other contexts which can't sleep,
3794 * as well as from task contexts which can sleep.
3796 * The completion callback is invoked in a context which can't sleep.
3797 * Before that invocation, the value of message->status is undefined.
3798 * When the callback is issued, message->status holds either zero (to
3799 * indicate complete success) or a negative error code. After that
3800 * callback returns, the driver which issued the transfer request may
3801 * deallocate the associated memory; it's no longer in use by any SPI
3802 * core or controller driver code.
3804 * Note that although all messages to a spi_device are handled in
3805 * FIFO order, messages may go to different devices in other orders.
3806 * Some device might be higher priority, or have various "hard" access
3807 * time requirements, for example.
3809 * On detection of any fault during the transfer, processing of
3810 * the entire message is aborted, and the device is deselected.
3811 * Until returning from the associated message completion callback,
3812 * no other spi_message queued to that device will be processed.
3813 * (This rule applies equally to all the synchronous transfer calls,
3814 * which are wrappers around this core asynchronous primitive.)
3816 * Return: zero on success, else a negative error code.
3818 int spi_async(struct spi_device *spi, struct spi_message *message)
3820 struct spi_controller *ctlr = spi->controller;
3822 unsigned long flags;
3824 ret = __spi_validate(spi, message);
3828 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3830 if (ctlr->bus_lock_flag)
3833 ret = __spi_async(spi, message);
3835 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3839 EXPORT_SYMBOL_GPL(spi_async);
3842 * spi_async_locked - version of spi_async with exclusive bus usage
3843 * @spi: device with which data will be exchanged
3844 * @message: describes the data transfers, including completion callback
3845 * Context: any (irqs may be blocked, etc)
3847 * This call may be used in_irq and other contexts which can't sleep,
3848 * as well as from task contexts which can sleep.
3850 * The completion callback is invoked in a context which can't sleep.
3851 * Before that invocation, the value of message->status is undefined.
3852 * When the callback is issued, message->status holds either zero (to
3853 * indicate complete success) or a negative error code. After that
3854 * callback returns, the driver which issued the transfer request may
3855 * deallocate the associated memory; it's no longer in use by any SPI
3856 * core or controller driver code.
3858 * Note that although all messages to a spi_device are handled in
3859 * FIFO order, messages may go to different devices in other orders.
3860 * Some device might be higher priority, or have various "hard" access
3861 * time requirements, for example.
3863 * On detection of any fault during the transfer, processing of
3864 * the entire message is aborted, and the device is deselected.
3865 * Until returning from the associated message completion callback,
3866 * no other spi_message queued to that device will be processed.
3867 * (This rule applies equally to all the synchronous transfer calls,
3868 * which are wrappers around this core asynchronous primitive.)
3870 * Return: zero on success, else a negative error code.
3872 static int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3874 struct spi_controller *ctlr = spi->controller;
3876 unsigned long flags;
3878 ret = __spi_validate(spi, message);
3882 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3884 ret = __spi_async(spi, message);
3886 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3892 /*-------------------------------------------------------------------------*/
3895 * Utility methods for SPI protocol drivers, layered on
3896 * top of the core. Some other utility methods are defined as
3900 static void spi_complete(void *arg)
3905 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3907 DECLARE_COMPLETION_ONSTACK(done);
3909 struct spi_controller *ctlr = spi->controller;
3910 unsigned long flags;
3912 status = __spi_validate(spi, message);
3916 message->complete = spi_complete;
3917 message->context = &done;
3920 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3921 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3924 * If we're not using the legacy transfer method then we will
3925 * try to transfer in the calling context so special case.
3926 * This code would be less tricky if we could remove the
3927 * support for driver implemented message queues.
3929 if (ctlr->transfer == spi_queued_transfer) {
3930 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3932 trace_spi_message_submit(message);
3934 status = __spi_queued_transfer(spi, message, false);
3936 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3938 status = spi_async_locked(spi, message);
3942 /* Push out the messages in the calling context if we can */
3943 if (ctlr->transfer == spi_queued_transfer) {
3944 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3945 spi_sync_immediate);
3946 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3947 spi_sync_immediate);
3948 __spi_pump_messages(ctlr, false);
3951 wait_for_completion(&done);
3952 status = message->status;
3954 message->context = NULL;
3959 * spi_sync - blocking/synchronous SPI data transfers
3960 * @spi: device with which data will be exchanged
3961 * @message: describes the data transfers
3962 * Context: can sleep
3964 * This call may only be used from a context that may sleep. The sleep
3965 * is non-interruptible, and has no timeout. Low-overhead controller
3966 * drivers may DMA directly into and out of the message buffers.
3968 * Note that the SPI device's chip select is active during the message,
3969 * and then is normally disabled between messages. Drivers for some
3970 * frequently-used devices may want to minimize costs of selecting a chip,
3971 * by leaving it selected in anticipation that the next message will go
3972 * to the same chip. (That may increase power usage.)
3974 * Also, the caller is guaranteeing that the memory associated with the
3975 * message will not be freed before this call returns.
3977 * Return: zero on success, else a negative error code.
3979 int spi_sync(struct spi_device *spi, struct spi_message *message)
3983 mutex_lock(&spi->controller->bus_lock_mutex);
3984 ret = __spi_sync(spi, message);
3985 mutex_unlock(&spi->controller->bus_lock_mutex);
3989 EXPORT_SYMBOL_GPL(spi_sync);
3992 * spi_sync_locked - version of spi_sync with exclusive bus usage
3993 * @spi: device with which data will be exchanged
3994 * @message: describes the data transfers
3995 * Context: can sleep
3997 * This call may only be used from a context that may sleep. The sleep
3998 * is non-interruptible, and has no timeout. Low-overhead controller
3999 * drivers may DMA directly into and out of the message buffers.
4001 * This call should be used by drivers that require exclusive access to the
4002 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4003 * be released by a spi_bus_unlock call when the exclusive access is over.
4005 * Return: zero on success, else a negative error code.
4007 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4009 return __spi_sync(spi, message);
4011 EXPORT_SYMBOL_GPL(spi_sync_locked);
4014 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
4015 * @ctlr: SPI bus master that should be locked for exclusive bus access
4016 * Context: can sleep
4018 * This call may only be used from a context that may sleep. The sleep
4019 * is non-interruptible, and has no timeout.
4021 * This call should be used by drivers that require exclusive access to the
4022 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4023 * exclusive access is over. Data transfer must be done by spi_sync_locked
4024 * and spi_async_locked calls when the SPI bus lock is held.
4026 * Return: always zero.
4028 int spi_bus_lock(struct spi_controller *ctlr)
4030 unsigned long flags;
4032 mutex_lock(&ctlr->bus_lock_mutex);
4034 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4035 ctlr->bus_lock_flag = 1;
4036 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4038 /* mutex remains locked until spi_bus_unlock is called */
4042 EXPORT_SYMBOL_GPL(spi_bus_lock);
4045 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4046 * @ctlr: SPI bus master that was locked for exclusive bus access
4047 * Context: can sleep
4049 * This call may only be used from a context that may sleep. The sleep
4050 * is non-interruptible, and has no timeout.
4052 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4055 * Return: always zero.
4057 int spi_bus_unlock(struct spi_controller *ctlr)
4059 ctlr->bus_lock_flag = 0;
4061 mutex_unlock(&ctlr->bus_lock_mutex);
4065 EXPORT_SYMBOL_GPL(spi_bus_unlock);
4067 /* portable code must never pass more than 32 bytes */
4068 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4073 * spi_write_then_read - SPI synchronous write followed by read
4074 * @spi: device with which data will be exchanged
4075 * @txbuf: data to be written (need not be dma-safe)
4076 * @n_tx: size of txbuf, in bytes
4077 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4078 * @n_rx: size of rxbuf, in bytes
4079 * Context: can sleep
4081 * This performs a half duplex MicroWire style transaction with the
4082 * device, sending txbuf and then reading rxbuf. The return value
4083 * is zero for success, else a negative errno status code.
4084 * This call may only be used from a context that may sleep.
4086 * Parameters to this routine are always copied using a small buffer.
4087 * Performance-sensitive or bulk transfer code should instead use
4088 * spi_{async,sync}() calls with dma-safe buffers.
4090 * Return: zero on success, else a negative error code.
4092 int spi_write_then_read(struct spi_device *spi,
4093 const void *txbuf, unsigned n_tx,
4094 void *rxbuf, unsigned n_rx)
4096 static DEFINE_MUTEX(lock);
4099 struct spi_message message;
4100 struct spi_transfer x[2];
4104 * Use preallocated DMA-safe buffer if we can. We can't avoid
4105 * copying here, (as a pure convenience thing), but we can
4106 * keep heap costs out of the hot path unless someone else is
4107 * using the pre-allocated buffer or the transfer is too large.
4109 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4110 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4111 GFP_KERNEL | GFP_DMA);
4118 spi_message_init(&message);
4119 memset(x, 0, sizeof(x));
4122 spi_message_add_tail(&x[0], &message);
4126 spi_message_add_tail(&x[1], &message);
4129 memcpy(local_buf, txbuf, n_tx);
4130 x[0].tx_buf = local_buf;
4131 x[1].rx_buf = local_buf + n_tx;
4134 status = spi_sync(spi, &message);
4136 memcpy(rxbuf, x[1].rx_buf, n_rx);
4138 if (x[0].tx_buf == buf)
4139 mutex_unlock(&lock);
4145 EXPORT_SYMBOL_GPL(spi_write_then_read);
4147 /*-------------------------------------------------------------------------*/
4149 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4150 /* must call put_device() when done with returned spi_device device */
4151 static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4153 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4155 return dev ? to_spi_device(dev) : NULL;
4158 /* the spi controllers are not using spi_bus, so we find it with another way */
4159 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4163 dev = class_find_device_by_of_node(&spi_master_class, node);
4164 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4165 dev = class_find_device_by_of_node(&spi_slave_class, node);
4169 /* reference got in class_find_device */
4170 return container_of(dev, struct spi_controller, dev);
4173 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4176 struct of_reconfig_data *rd = arg;
4177 struct spi_controller *ctlr;
4178 struct spi_device *spi;
4180 switch (of_reconfig_get_state_change(action, arg)) {
4181 case OF_RECONFIG_CHANGE_ADD:
4182 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4184 return NOTIFY_OK; /* not for us */
4186 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4187 put_device(&ctlr->dev);
4191 spi = of_register_spi_device(ctlr, rd->dn);
4192 put_device(&ctlr->dev);
4195 pr_err("%s: failed to create for '%pOF'\n",
4197 of_node_clear_flag(rd->dn, OF_POPULATED);
4198 return notifier_from_errno(PTR_ERR(spi));
4202 case OF_RECONFIG_CHANGE_REMOVE:
4203 /* already depopulated? */
4204 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4207 /* find our device by node */
4208 spi = of_find_spi_device_by_node(rd->dn);
4210 return NOTIFY_OK; /* no? not meant for us */
4212 /* unregister takes one ref away */
4213 spi_unregister_device(spi);
4215 /* and put the reference of the find */
4216 put_device(&spi->dev);
4223 static struct notifier_block spi_of_notifier = {
4224 .notifier_call = of_spi_notify,
4226 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4227 extern struct notifier_block spi_of_notifier;
4228 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4230 #if IS_ENABLED(CONFIG_ACPI)
4231 static int spi_acpi_controller_match(struct device *dev, const void *data)
4233 return ACPI_COMPANION(dev->parent) == data;
4236 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4240 dev = class_find_device(&spi_master_class, NULL, adev,
4241 spi_acpi_controller_match);
4242 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4243 dev = class_find_device(&spi_slave_class, NULL, adev,
4244 spi_acpi_controller_match);
4248 return container_of(dev, struct spi_controller, dev);
4251 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4255 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4256 return to_spi_device(dev);
4259 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4262 struct acpi_device *adev = arg;
4263 struct spi_controller *ctlr;
4264 struct spi_device *spi;
4267 case ACPI_RECONFIG_DEVICE_ADD:
4268 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4272 acpi_register_spi_device(ctlr, adev);
4273 put_device(&ctlr->dev);
4275 case ACPI_RECONFIG_DEVICE_REMOVE:
4276 if (!acpi_device_enumerated(adev))
4279 spi = acpi_spi_find_device_by_adev(adev);
4283 spi_unregister_device(spi);
4284 put_device(&spi->dev);
4291 static struct notifier_block spi_acpi_notifier = {
4292 .notifier_call = acpi_spi_notify,
4295 extern struct notifier_block spi_acpi_notifier;
4298 static int __init spi_init(void)
4302 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4308 status = bus_register(&spi_bus_type);
4312 status = class_register(&spi_master_class);
4316 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4317 status = class_register(&spi_slave_class);
4322 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4323 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4324 if (IS_ENABLED(CONFIG_ACPI))
4325 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4330 class_unregister(&spi_master_class);
4332 bus_unregister(&spi_bus_type);
4341 * A board_info is normally registered in arch_initcall(),
4342 * but even essential drivers wait till later.
4344 * REVISIT only boardinfo really needs static linking. The rest (device and
4345 * driver registration) _could_ be dynamically linked (modular) ... Costs
4346 * include needing to have boardinfo data structures be much more public.
4348 postcore_initcall(spi_init);