1 // SPDX-License-Identifier: GPL-2.0-or-later
4 // Copyright (C) 2005 David Brownell
5 // Copyright (C) 2008 Secret Lab Technologies Ltd.
7 #include <linux/kernel.h>
8 #include <linux/device.h>
9 #include <linux/init.h>
10 #include <linux/cache.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/dmaengine.h>
13 #include <linux/mutex.h>
14 #include <linux/of_device.h>
15 #include <linux/of_irq.h>
16 #include <linux/clk/clk-conf.h>
17 #include <linux/slab.h>
18 #include <linux/mod_devicetable.h>
19 #include <linux/spi/spi.h>
20 #include <linux/spi/spi-mem.h>
21 #include <linux/of_gpio.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/pm_domain.h>
25 #include <linux/property.h>
26 #include <linux/export.h>
27 #include <linux/sched/rt.h>
28 #include <uapi/linux/sched/types.h>
29 #include <linux/delay.h>
30 #include <linux/kthread.h>
31 #include <linux/ioport.h>
32 #include <linux/acpi.h>
33 #include <linux/highmem.h>
34 #include <linux/idr.h>
35 #include <linux/platform_data/x86/apple.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/spi.h>
39 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
42 #include "internals.h"
44 static DEFINE_IDR(spi_master_idr);
46 static void spidev_release(struct device *dev)
48 struct spi_device *spi = to_spi_device(dev);
50 spi_controller_put(spi->controller);
51 kfree(spi->driver_override);
56 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
58 const struct spi_device *spi = to_spi_device(dev);
61 len = of_device_modalias(dev, buf, PAGE_SIZE);
65 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
69 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
71 static DEVICE_ATTR_RO(modalias);
73 static ssize_t driver_override_store(struct device *dev,
74 struct device_attribute *a,
75 const char *buf, size_t count)
77 struct spi_device *spi = to_spi_device(dev);
78 const char *end = memchr(buf, '\n', count);
79 const size_t len = end ? end - buf : count;
80 const char *driver_override, *old;
82 /* We need to keep extra room for a newline when displaying value */
83 if (len >= (PAGE_SIZE - 1))
86 driver_override = kstrndup(buf, len, GFP_KERNEL);
91 old = spi->driver_override;
93 spi->driver_override = driver_override;
95 /* Empty string, disable driver override */
96 spi->driver_override = NULL;
97 kfree(driver_override);
105 static ssize_t driver_override_show(struct device *dev,
106 struct device_attribute *a, char *buf)
108 const struct spi_device *spi = to_spi_device(dev);
112 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
116 static DEVICE_ATTR_RW(driver_override);
118 #define SPI_STATISTICS_ATTRS(field, file) \
119 static ssize_t spi_controller_##field##_show(struct device *dev, \
120 struct device_attribute *attr, \
123 struct spi_controller *ctlr = container_of(dev, \
124 struct spi_controller, dev); \
125 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
127 static struct device_attribute dev_attr_spi_controller_##field = { \
128 .attr = { .name = file, .mode = 0444 }, \
129 .show = spi_controller_##field##_show, \
131 static ssize_t spi_device_##field##_show(struct device *dev, \
132 struct device_attribute *attr, \
135 struct spi_device *spi = to_spi_device(dev); \
136 return spi_statistics_##field##_show(&spi->statistics, buf); \
138 static struct device_attribute dev_attr_spi_device_##field = { \
139 .attr = { .name = file, .mode = 0444 }, \
140 .show = spi_device_##field##_show, \
143 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
144 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
147 unsigned long flags; \
149 spin_lock_irqsave(&stat->lock, flags); \
150 len = sprintf(buf, format_string, stat->field); \
151 spin_unlock_irqrestore(&stat->lock, flags); \
154 SPI_STATISTICS_ATTRS(name, file)
156 #define SPI_STATISTICS_SHOW(field, format_string) \
157 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
158 field, format_string)
160 SPI_STATISTICS_SHOW(messages, "%lu");
161 SPI_STATISTICS_SHOW(transfers, "%lu");
162 SPI_STATISTICS_SHOW(errors, "%lu");
163 SPI_STATISTICS_SHOW(timedout, "%lu");
165 SPI_STATISTICS_SHOW(spi_sync, "%lu");
166 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
167 SPI_STATISTICS_SHOW(spi_async, "%lu");
169 SPI_STATISTICS_SHOW(bytes, "%llu");
170 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
171 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
173 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
174 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
175 "transfer_bytes_histo_" number, \
176 transfer_bytes_histo[index], "%lu")
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
190 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
191 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
192 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
193 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
195 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
197 static struct attribute *spi_dev_attrs[] = {
198 &dev_attr_modalias.attr,
199 &dev_attr_driver_override.attr,
203 static const struct attribute_group spi_dev_group = {
204 .attrs = spi_dev_attrs,
207 static struct attribute *spi_device_statistics_attrs[] = {
208 &dev_attr_spi_device_messages.attr,
209 &dev_attr_spi_device_transfers.attr,
210 &dev_attr_spi_device_errors.attr,
211 &dev_attr_spi_device_timedout.attr,
212 &dev_attr_spi_device_spi_sync.attr,
213 &dev_attr_spi_device_spi_sync_immediate.attr,
214 &dev_attr_spi_device_spi_async.attr,
215 &dev_attr_spi_device_bytes.attr,
216 &dev_attr_spi_device_bytes_rx.attr,
217 &dev_attr_spi_device_bytes_tx.attr,
218 &dev_attr_spi_device_transfer_bytes_histo0.attr,
219 &dev_attr_spi_device_transfer_bytes_histo1.attr,
220 &dev_attr_spi_device_transfer_bytes_histo2.attr,
221 &dev_attr_spi_device_transfer_bytes_histo3.attr,
222 &dev_attr_spi_device_transfer_bytes_histo4.attr,
223 &dev_attr_spi_device_transfer_bytes_histo5.attr,
224 &dev_attr_spi_device_transfer_bytes_histo6.attr,
225 &dev_attr_spi_device_transfer_bytes_histo7.attr,
226 &dev_attr_spi_device_transfer_bytes_histo8.attr,
227 &dev_attr_spi_device_transfer_bytes_histo9.attr,
228 &dev_attr_spi_device_transfer_bytes_histo10.attr,
229 &dev_attr_spi_device_transfer_bytes_histo11.attr,
230 &dev_attr_spi_device_transfer_bytes_histo12.attr,
231 &dev_attr_spi_device_transfer_bytes_histo13.attr,
232 &dev_attr_spi_device_transfer_bytes_histo14.attr,
233 &dev_attr_spi_device_transfer_bytes_histo15.attr,
234 &dev_attr_spi_device_transfer_bytes_histo16.attr,
235 &dev_attr_spi_device_transfers_split_maxsize.attr,
239 static const struct attribute_group spi_device_statistics_group = {
240 .name = "statistics",
241 .attrs = spi_device_statistics_attrs,
244 static const struct attribute_group *spi_dev_groups[] = {
246 &spi_device_statistics_group,
250 static struct attribute *spi_controller_statistics_attrs[] = {
251 &dev_attr_spi_controller_messages.attr,
252 &dev_attr_spi_controller_transfers.attr,
253 &dev_attr_spi_controller_errors.attr,
254 &dev_attr_spi_controller_timedout.attr,
255 &dev_attr_spi_controller_spi_sync.attr,
256 &dev_attr_spi_controller_spi_sync_immediate.attr,
257 &dev_attr_spi_controller_spi_async.attr,
258 &dev_attr_spi_controller_bytes.attr,
259 &dev_attr_spi_controller_bytes_rx.attr,
260 &dev_attr_spi_controller_bytes_tx.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
274 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
275 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
276 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
277 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
278 &dev_attr_spi_controller_transfers_split_maxsize.attr,
282 static const struct attribute_group spi_controller_statistics_group = {
283 .name = "statistics",
284 .attrs = spi_controller_statistics_attrs,
287 static const struct attribute_group *spi_master_groups[] = {
288 &spi_controller_statistics_group,
292 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
293 struct spi_transfer *xfer,
294 struct spi_controller *ctlr)
297 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
302 spin_lock_irqsave(&stats->lock, flags);
305 stats->transfer_bytes_histo[l2len]++;
307 stats->bytes += xfer->len;
308 if ((xfer->tx_buf) &&
309 (xfer->tx_buf != ctlr->dummy_tx))
310 stats->bytes_tx += xfer->len;
311 if ((xfer->rx_buf) &&
312 (xfer->rx_buf != ctlr->dummy_rx))
313 stats->bytes_rx += xfer->len;
315 spin_unlock_irqrestore(&stats->lock, flags);
317 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
319 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
320 * and the sysfs version makes coldplug work too.
323 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
324 const struct spi_device *sdev)
326 while (id->name[0]) {
327 if (!strcmp(sdev->modalias, id->name))
334 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
336 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
338 return spi_match_id(sdrv->id_table, sdev);
340 EXPORT_SYMBOL_GPL(spi_get_device_id);
342 static int spi_match_device(struct device *dev, struct device_driver *drv)
344 const struct spi_device *spi = to_spi_device(dev);
345 const struct spi_driver *sdrv = to_spi_driver(drv);
347 /* Check override first, and if set, only use the named driver */
348 if (spi->driver_override)
349 return strcmp(spi->driver_override, drv->name) == 0;
351 /* Attempt an OF style match */
352 if (of_driver_match_device(dev, drv))
356 if (acpi_driver_match_device(dev, drv))
360 return !!spi_match_id(sdrv->id_table, spi);
362 return strcmp(spi->modalias, drv->name) == 0;
365 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
367 const struct spi_device *spi = to_spi_device(dev);
370 rc = of_device_uevent_modalias(dev, env);
374 rc = acpi_device_uevent_modalias(dev, env);
378 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
381 static int spi_probe(struct device *dev)
383 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
384 struct spi_device *spi = to_spi_device(dev);
387 ret = of_clk_set_defaults(dev->of_node, false);
392 spi->irq = of_irq_get(dev->of_node, 0);
393 if (spi->irq == -EPROBE_DEFER)
394 return -EPROBE_DEFER;
399 ret = dev_pm_domain_attach(dev, true);
404 ret = sdrv->probe(spi);
406 dev_pm_domain_detach(dev, true);
412 static void spi_remove(struct device *dev)
414 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
419 ret = sdrv->remove(to_spi_device(dev));
422 "Failed to unbind driver (%pe), ignoring\n",
426 dev_pm_domain_detach(dev, true);
429 static void spi_shutdown(struct device *dev)
432 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
435 sdrv->shutdown(to_spi_device(dev));
439 struct bus_type spi_bus_type = {
441 .dev_groups = spi_dev_groups,
442 .match = spi_match_device,
443 .uevent = spi_uevent,
445 .remove = spi_remove,
446 .shutdown = spi_shutdown,
448 EXPORT_SYMBOL_GPL(spi_bus_type);
451 * __spi_register_driver - register a SPI driver
452 * @owner: owner module of the driver to register
453 * @sdrv: the driver to register
456 * Return: zero on success, else a negative error code.
458 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
460 sdrv->driver.owner = owner;
461 sdrv->driver.bus = &spi_bus_type;
462 return driver_register(&sdrv->driver);
464 EXPORT_SYMBOL_GPL(__spi_register_driver);
466 /*-------------------------------------------------------------------------*/
468 /* SPI devices should normally not be created by SPI device drivers; that
469 * would make them board-specific. Similarly with SPI controller drivers.
470 * Device registration normally goes into like arch/.../mach.../board-YYY.c
471 * with other readonly (flashable) information about mainboard devices.
475 struct list_head list;
476 struct spi_board_info board_info;
479 static LIST_HEAD(board_list);
480 static LIST_HEAD(spi_controller_list);
483 * Used to protect add/del operation for board_info list and
484 * spi_controller list, and their matching process
485 * also used to protect object of type struct idr
487 static DEFINE_MUTEX(board_lock);
490 * Prevents addition of devices with same chip select and
491 * addition of devices below an unregistering controller.
493 static DEFINE_MUTEX(spi_add_lock);
496 * spi_alloc_device - Allocate a new SPI device
497 * @ctlr: Controller to which device is connected
500 * Allows a driver to allocate and initialize a spi_device without
501 * registering it immediately. This allows a driver to directly
502 * fill the spi_device with device parameters before calling
503 * spi_add_device() on it.
505 * Caller is responsible to call spi_add_device() on the returned
506 * spi_device structure to add it to the SPI controller. If the caller
507 * needs to discard the spi_device without adding it, then it should
508 * call spi_dev_put() on it.
510 * Return: a pointer to the new device, or NULL.
512 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
514 struct spi_device *spi;
516 if (!spi_controller_get(ctlr))
519 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
521 spi_controller_put(ctlr);
525 spi->master = spi->controller = ctlr;
526 spi->dev.parent = &ctlr->dev;
527 spi->dev.bus = &spi_bus_type;
528 spi->dev.release = spidev_release;
529 spi->cs_gpio = -ENOENT;
530 spi->mode = ctlr->buswidth_override_bits;
532 spin_lock_init(&spi->statistics.lock);
534 device_initialize(&spi->dev);
537 EXPORT_SYMBOL_GPL(spi_alloc_device);
539 static void spi_dev_set_name(struct spi_device *spi)
541 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
544 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
548 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
552 static int spi_dev_check(struct device *dev, void *data)
554 struct spi_device *spi = to_spi_device(dev);
555 struct spi_device *new_spi = data;
557 if (spi->controller == new_spi->controller &&
558 spi->chip_select == new_spi->chip_select)
563 static void spi_cleanup(struct spi_device *spi)
565 if (spi->controller->cleanup)
566 spi->controller->cleanup(spi);
569 static int __spi_add_device(struct spi_device *spi)
571 struct spi_controller *ctlr = spi->controller;
572 struct device *dev = ctlr->dev.parent;
575 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
577 dev_err(dev, "chipselect %d already in use\n",
582 /* Controller may unregister concurrently */
583 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
584 !device_is_registered(&ctlr->dev)) {
588 /* Descriptors take precedence */
590 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
591 else if (ctlr->cs_gpios)
592 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
594 /* Drivers may modify this initial i/o setup, but will
595 * normally rely on the device being setup. Devices
596 * using SPI_CS_HIGH can't coexist well otherwise...
598 status = spi_setup(spi);
600 dev_err(dev, "can't setup %s, status %d\n",
601 dev_name(&spi->dev), status);
605 /* Device may be bound to an active driver when this returns */
606 status = device_add(&spi->dev);
608 dev_err(dev, "can't add %s, status %d\n",
609 dev_name(&spi->dev), status);
612 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
619 * spi_add_device - Add spi_device allocated with spi_alloc_device
620 * @spi: spi_device to register
622 * Companion function to spi_alloc_device. Devices allocated with
623 * spi_alloc_device can be added onto the spi bus with this function.
625 * Return: 0 on success; negative errno on failure
627 int spi_add_device(struct spi_device *spi)
629 struct spi_controller *ctlr = spi->controller;
630 struct device *dev = ctlr->dev.parent;
633 /* Chipselects are numbered 0..max; validate. */
634 if (spi->chip_select >= ctlr->num_chipselect) {
635 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
636 ctlr->num_chipselect);
640 /* Set the bus ID string */
641 spi_dev_set_name(spi);
643 /* We need to make sure there's no other device with this
644 * chipselect **BEFORE** we call setup(), else we'll trash
645 * its configuration. Lock against concurrent add() calls.
647 mutex_lock(&spi_add_lock);
648 status = __spi_add_device(spi);
649 mutex_unlock(&spi_add_lock);
652 EXPORT_SYMBOL_GPL(spi_add_device);
654 static int spi_add_device_locked(struct spi_device *spi)
656 struct spi_controller *ctlr = spi->controller;
657 struct device *dev = ctlr->dev.parent;
659 /* Chipselects are numbered 0..max; validate. */
660 if (spi->chip_select >= ctlr->num_chipselect) {
661 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
662 ctlr->num_chipselect);
666 /* Set the bus ID string */
667 spi_dev_set_name(spi);
669 WARN_ON(!mutex_is_locked(&spi_add_lock));
670 return __spi_add_device(spi);
674 * spi_new_device - instantiate one new SPI device
675 * @ctlr: Controller to which device is connected
676 * @chip: Describes the SPI device
679 * On typical mainboards, this is purely internal; and it's not needed
680 * after board init creates the hard-wired devices. Some development
681 * platforms may not be able to use spi_register_board_info though, and
682 * this is exported so that for example a USB or parport based adapter
683 * driver could add devices (which it would learn about out-of-band).
685 * Return: the new device, or NULL.
687 struct spi_device *spi_new_device(struct spi_controller *ctlr,
688 struct spi_board_info *chip)
690 struct spi_device *proxy;
693 /* NOTE: caller did any chip->bus_num checks necessary.
695 * Also, unless we change the return value convention to use
696 * error-or-pointer (not NULL-or-pointer), troubleshootability
697 * suggests syslogged diagnostics are best here (ugh).
700 proxy = spi_alloc_device(ctlr);
704 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
706 proxy->chip_select = chip->chip_select;
707 proxy->max_speed_hz = chip->max_speed_hz;
708 proxy->mode = chip->mode;
709 proxy->irq = chip->irq;
710 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
711 proxy->dev.platform_data = (void *) chip->platform_data;
712 proxy->controller_data = chip->controller_data;
713 proxy->controller_state = NULL;
716 status = device_add_software_node(&proxy->dev, chip->swnode);
718 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
719 chip->modalias, status);
724 status = spi_add_device(proxy);
731 device_remove_software_node(&proxy->dev);
735 EXPORT_SYMBOL_GPL(spi_new_device);
738 * spi_unregister_device - unregister a single SPI device
739 * @spi: spi_device to unregister
741 * Start making the passed SPI device vanish. Normally this would be handled
742 * by spi_unregister_controller().
744 void spi_unregister_device(struct spi_device *spi)
749 if (spi->dev.of_node) {
750 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
751 of_node_put(spi->dev.of_node);
753 if (ACPI_COMPANION(&spi->dev))
754 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
755 device_remove_software_node(&spi->dev);
756 device_del(&spi->dev);
758 put_device(&spi->dev);
760 EXPORT_SYMBOL_GPL(spi_unregister_device);
762 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
763 struct spi_board_info *bi)
765 struct spi_device *dev;
767 if (ctlr->bus_num != bi->bus_num)
770 dev = spi_new_device(ctlr, bi);
772 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
777 * spi_register_board_info - register SPI devices for a given board
778 * @info: array of chip descriptors
779 * @n: how many descriptors are provided
782 * Board-specific early init code calls this (probably during arch_initcall)
783 * with segments of the SPI device table. Any device nodes are created later,
784 * after the relevant parent SPI controller (bus_num) is defined. We keep
785 * this table of devices forever, so that reloading a controller driver will
786 * not make Linux forget about these hard-wired devices.
788 * Other code can also call this, e.g. a particular add-on board might provide
789 * SPI devices through its expansion connector, so code initializing that board
790 * would naturally declare its SPI devices.
792 * The board info passed can safely be __initdata ... but be careful of
793 * any embedded pointers (platform_data, etc), they're copied as-is.
795 * Return: zero on success, else a negative error code.
797 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
799 struct boardinfo *bi;
805 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
809 for (i = 0; i < n; i++, bi++, info++) {
810 struct spi_controller *ctlr;
812 memcpy(&bi->board_info, info, sizeof(*info));
814 mutex_lock(&board_lock);
815 list_add_tail(&bi->list, &board_list);
816 list_for_each_entry(ctlr, &spi_controller_list, list)
817 spi_match_controller_to_boardinfo(ctlr,
819 mutex_unlock(&board_lock);
825 /*-------------------------------------------------------------------------*/
827 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
829 bool activate = enable;
832 * Avoid calling into the driver (or doing delays) if the chip select
833 * isn't actually changing from the last time this was called.
835 if (!force && (spi->controller->last_cs_enable == enable) &&
836 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
839 trace_spi_set_cs(spi, activate);
841 spi->controller->last_cs_enable = enable;
842 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
844 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
845 !spi->controller->set_cs_timing) {
847 spi_delay_exec(&spi->cs_setup, NULL);
849 spi_delay_exec(&spi->cs_hold, NULL);
852 if (spi->mode & SPI_CS_HIGH)
855 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
856 if (!(spi->mode & SPI_NO_CS)) {
859 * Historically ACPI has no means of the GPIO polarity and
860 * thus the SPISerialBus() resource defines it on the per-chip
861 * basis. In order to avoid a chain of negations, the GPIO
862 * polarity is considered being Active High. Even for the cases
863 * when _DSD() is involved (in the updated versions of ACPI)
864 * the GPIO CS polarity must be defined Active High to avoid
865 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
868 if (has_acpi_companion(&spi->dev))
869 gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
871 /* Polarity handled by GPIO library */
872 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
875 * invert the enable line, as active low is
878 gpio_set_value_cansleep(spi->cs_gpio, !enable);
881 /* Some SPI masters need both GPIO CS & slave_select */
882 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
883 spi->controller->set_cs)
884 spi->controller->set_cs(spi, !enable);
885 } else if (spi->controller->set_cs) {
886 spi->controller->set_cs(spi, !enable);
889 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
890 !spi->controller->set_cs_timing) {
892 spi_delay_exec(&spi->cs_inactive, NULL);
896 #ifdef CONFIG_HAS_DMA
897 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
898 struct sg_table *sgt, void *buf, size_t len,
899 enum dma_data_direction dir)
901 const bool vmalloced_buf = is_vmalloc_addr(buf);
902 unsigned int max_seg_size = dma_get_max_seg_size(dev);
903 #ifdef CONFIG_HIGHMEM
904 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
905 (unsigned long)buf < (PKMAP_BASE +
906 (LAST_PKMAP * PAGE_SIZE)));
908 const bool kmap_buf = false;
912 struct page *vm_page;
913 struct scatterlist *sg;
918 if (vmalloced_buf || kmap_buf) {
919 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
920 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
921 } else if (virt_addr_valid(buf)) {
922 desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
923 sgs = DIV_ROUND_UP(len, desc_len);
928 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
933 for (i = 0; i < sgs; i++) {
935 if (vmalloced_buf || kmap_buf) {
937 * Next scatterlist entry size is the minimum between
938 * the desc_len and the remaining buffer length that
941 min = min_t(size_t, desc_len,
943 PAGE_SIZE - offset_in_page(buf)));
945 vm_page = vmalloc_to_page(buf);
947 vm_page = kmap_to_page(buf);
952 sg_set_page(sg, vm_page,
953 min, offset_in_page(buf));
955 min = min_t(size_t, len, desc_len);
957 sg_set_buf(sg, sg_buf, min);
965 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
978 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
979 struct sg_table *sgt, enum dma_data_direction dir)
981 if (sgt->orig_nents) {
982 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
987 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
989 struct device *tx_dev, *rx_dev;
990 struct spi_transfer *xfer;
997 tx_dev = ctlr->dma_tx->device->dev;
998 else if (ctlr->dma_map_dev)
999 tx_dev = ctlr->dma_map_dev;
1001 tx_dev = ctlr->dev.parent;
1004 rx_dev = ctlr->dma_rx->device->dev;
1005 else if (ctlr->dma_map_dev)
1006 rx_dev = ctlr->dma_map_dev;
1008 rx_dev = ctlr->dev.parent;
1010 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1011 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1014 if (xfer->tx_buf != NULL) {
1015 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
1016 (void *)xfer->tx_buf, xfer->len,
1022 if (xfer->rx_buf != NULL) {
1023 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
1024 xfer->rx_buf, xfer->len,
1027 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
1034 ctlr->cur_msg_mapped = true;
1039 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1041 struct spi_transfer *xfer;
1042 struct device *tx_dev, *rx_dev;
1044 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1048 tx_dev = ctlr->dma_tx->device->dev;
1050 tx_dev = ctlr->dev.parent;
1053 rx_dev = ctlr->dma_rx->device->dev;
1055 rx_dev = ctlr->dev.parent;
1057 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1058 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1061 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1062 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1065 ctlr->cur_msg_mapped = false;
1069 #else /* !CONFIG_HAS_DMA */
1070 static inline int __spi_map_msg(struct spi_controller *ctlr,
1071 struct spi_message *msg)
1076 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1077 struct spi_message *msg)
1081 #endif /* !CONFIG_HAS_DMA */
1083 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1084 struct spi_message *msg)
1086 struct spi_transfer *xfer;
1088 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1090 * Restore the original value of tx_buf or rx_buf if they are
1093 if (xfer->tx_buf == ctlr->dummy_tx)
1094 xfer->tx_buf = NULL;
1095 if (xfer->rx_buf == ctlr->dummy_rx)
1096 xfer->rx_buf = NULL;
1099 return __spi_unmap_msg(ctlr, msg);
1102 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1104 struct spi_transfer *xfer;
1106 unsigned int max_tx, max_rx;
1108 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1109 && !(msg->spi->mode & SPI_3WIRE)) {
1113 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1114 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1116 max_tx = max(xfer->len, max_tx);
1117 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1119 max_rx = max(xfer->len, max_rx);
1123 tmp = krealloc(ctlr->dummy_tx, max_tx,
1124 GFP_KERNEL | GFP_DMA);
1127 ctlr->dummy_tx = tmp;
1128 memset(tmp, 0, max_tx);
1132 tmp = krealloc(ctlr->dummy_rx, max_rx,
1133 GFP_KERNEL | GFP_DMA);
1136 ctlr->dummy_rx = tmp;
1139 if (max_tx || max_rx) {
1140 list_for_each_entry(xfer, &msg->transfers,
1145 xfer->tx_buf = ctlr->dummy_tx;
1147 xfer->rx_buf = ctlr->dummy_rx;
1152 return __spi_map_msg(ctlr, msg);
1155 static int spi_transfer_wait(struct spi_controller *ctlr,
1156 struct spi_message *msg,
1157 struct spi_transfer *xfer)
1159 struct spi_statistics *statm = &ctlr->statistics;
1160 struct spi_statistics *stats = &msg->spi->statistics;
1161 u32 speed_hz = xfer->speed_hz;
1162 unsigned long long ms;
1164 if (spi_controller_is_slave(ctlr)) {
1165 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1166 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1174 * For each byte we wait for 8 cycles of the SPI clock.
1175 * Since speed is defined in Hz and we want milliseconds,
1176 * use respective multiplier, but before the division,
1177 * otherwise we may get 0 for short transfers.
1179 ms = 8LL * MSEC_PER_SEC * xfer->len;
1180 do_div(ms, speed_hz);
1183 * Increase it twice and add 200 ms tolerance, use
1184 * predefined maximum in case of overflow.
1190 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1191 msecs_to_jiffies(ms));
1194 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1195 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1196 dev_err(&msg->spi->dev,
1197 "SPI transfer timed out\n");
1205 static void _spi_transfer_delay_ns(u32 ns)
1209 if (ns <= NSEC_PER_USEC) {
1212 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1217 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1221 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1223 u32 delay = _delay->value;
1224 u32 unit = _delay->unit;
1231 case SPI_DELAY_UNIT_USECS:
1232 delay *= NSEC_PER_USEC;
1234 case SPI_DELAY_UNIT_NSECS:
1235 /* Nothing to do here */
1237 case SPI_DELAY_UNIT_SCK:
1238 /* clock cycles need to be obtained from spi_transfer */
1242 * If there is unknown effective speed, approximate it
1243 * by underestimating with half of the requested hz.
1245 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1249 /* Convert delay to nanoseconds */
1250 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1258 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1260 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1269 delay = spi_delay_to_ns(_delay, xfer);
1273 _spi_transfer_delay_ns(delay);
1277 EXPORT_SYMBOL_GPL(spi_delay_exec);
1279 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1280 struct spi_transfer *xfer)
1282 u32 default_delay_ns = 10 * NSEC_PER_USEC;
1283 u32 delay = xfer->cs_change_delay.value;
1284 u32 unit = xfer->cs_change_delay.unit;
1287 /* return early on "fast" mode - for everything but USECS */
1289 if (unit == SPI_DELAY_UNIT_USECS)
1290 _spi_transfer_delay_ns(default_delay_ns);
1294 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1296 dev_err_once(&msg->spi->dev,
1297 "Use of unsupported delay unit %i, using default of %luus\n",
1298 unit, default_delay_ns / NSEC_PER_USEC);
1299 _spi_transfer_delay_ns(default_delay_ns);
1304 * spi_transfer_one_message - Default implementation of transfer_one_message()
1306 * This is a standard implementation of transfer_one_message() for
1307 * drivers which implement a transfer_one() operation. It provides
1308 * standard handling of delays and chip select management.
1310 static int spi_transfer_one_message(struct spi_controller *ctlr,
1311 struct spi_message *msg)
1313 struct spi_transfer *xfer;
1314 bool keep_cs = false;
1316 struct spi_statistics *statm = &ctlr->statistics;
1317 struct spi_statistics *stats = &msg->spi->statistics;
1319 spi_set_cs(msg->spi, true, false);
1321 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1322 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1324 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1325 trace_spi_transfer_start(msg, xfer);
1327 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1328 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1330 if (!ctlr->ptp_sts_supported) {
1331 xfer->ptp_sts_word_pre = 0;
1332 ptp_read_system_prets(xfer->ptp_sts);
1335 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1336 reinit_completion(&ctlr->xfer_completion);
1339 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1341 if (ctlr->cur_msg_mapped &&
1342 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1343 __spi_unmap_msg(ctlr, msg);
1344 ctlr->fallback = true;
1345 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1349 SPI_STATISTICS_INCREMENT_FIELD(statm,
1351 SPI_STATISTICS_INCREMENT_FIELD(stats,
1353 dev_err(&msg->spi->dev,
1354 "SPI transfer failed: %d\n", ret);
1359 ret = spi_transfer_wait(ctlr, msg, xfer);
1365 dev_err(&msg->spi->dev,
1366 "Bufferless transfer has length %u\n",
1370 if (!ctlr->ptp_sts_supported) {
1371 ptp_read_system_postts(xfer->ptp_sts);
1372 xfer->ptp_sts_word_post = xfer->len;
1375 trace_spi_transfer_stop(msg, xfer);
1377 if (msg->status != -EINPROGRESS)
1380 spi_transfer_delay_exec(xfer);
1382 if (xfer->cs_change) {
1383 if (list_is_last(&xfer->transfer_list,
1387 spi_set_cs(msg->spi, false, false);
1388 _spi_transfer_cs_change_delay(msg, xfer);
1389 spi_set_cs(msg->spi, true, false);
1393 msg->actual_length += xfer->len;
1397 if (ret != 0 || !keep_cs)
1398 spi_set_cs(msg->spi, false, false);
1400 if (msg->status == -EINPROGRESS)
1403 if (msg->status && ctlr->handle_err)
1404 ctlr->handle_err(ctlr, msg);
1406 spi_finalize_current_message(ctlr);
1412 * spi_finalize_current_transfer - report completion of a transfer
1413 * @ctlr: the controller reporting completion
1415 * Called by SPI drivers using the core transfer_one_message()
1416 * implementation to notify it that the current interrupt driven
1417 * transfer has finished and the next one may be scheduled.
1419 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1421 complete(&ctlr->xfer_completion);
1423 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1425 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1427 if (ctlr->auto_runtime_pm) {
1428 pm_runtime_mark_last_busy(ctlr->dev.parent);
1429 pm_runtime_put_autosuspend(ctlr->dev.parent);
1434 * __spi_pump_messages - function which processes spi message queue
1435 * @ctlr: controller to process queue for
1436 * @in_kthread: true if we are in the context of the message pump thread
1438 * This function checks if there is any spi message in the queue that
1439 * needs processing and if so call out to the driver to initialize hardware
1440 * and transfer each message.
1442 * Note that it is called both from the kthread itself and also from
1443 * inside spi_sync(); the queue extraction handling at the top of the
1444 * function should deal with this safely.
1446 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1448 struct spi_transfer *xfer;
1449 struct spi_message *msg;
1450 bool was_busy = false;
1451 unsigned long flags;
1455 spin_lock_irqsave(&ctlr->queue_lock, flags);
1457 /* Make sure we are not already running a message */
1458 if (ctlr->cur_msg) {
1459 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1463 /* If another context is idling the device then defer */
1465 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1466 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1470 /* Check if the queue is idle */
1471 if (list_empty(&ctlr->queue) || !ctlr->running) {
1473 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1477 /* Defer any non-atomic teardown to the thread */
1479 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1480 !ctlr->unprepare_transfer_hardware) {
1481 spi_idle_runtime_pm(ctlr);
1483 trace_spi_controller_idle(ctlr);
1485 kthread_queue_work(ctlr->kworker,
1486 &ctlr->pump_messages);
1488 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1493 ctlr->idling = true;
1494 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1496 kfree(ctlr->dummy_rx);
1497 ctlr->dummy_rx = NULL;
1498 kfree(ctlr->dummy_tx);
1499 ctlr->dummy_tx = NULL;
1500 if (ctlr->unprepare_transfer_hardware &&
1501 ctlr->unprepare_transfer_hardware(ctlr))
1503 "failed to unprepare transfer hardware\n");
1504 spi_idle_runtime_pm(ctlr);
1505 trace_spi_controller_idle(ctlr);
1507 spin_lock_irqsave(&ctlr->queue_lock, flags);
1508 ctlr->idling = false;
1509 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1513 /* Extract head of queue */
1514 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1515 ctlr->cur_msg = msg;
1517 list_del_init(&msg->queue);
1522 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1524 mutex_lock(&ctlr->io_mutex);
1526 if (!was_busy && ctlr->auto_runtime_pm) {
1527 ret = pm_runtime_get_sync(ctlr->dev.parent);
1529 pm_runtime_put_noidle(ctlr->dev.parent);
1530 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1532 mutex_unlock(&ctlr->io_mutex);
1538 trace_spi_controller_busy(ctlr);
1540 if (!was_busy && ctlr->prepare_transfer_hardware) {
1541 ret = ctlr->prepare_transfer_hardware(ctlr);
1544 "failed to prepare transfer hardware: %d\n",
1547 if (ctlr->auto_runtime_pm)
1548 pm_runtime_put(ctlr->dev.parent);
1551 spi_finalize_current_message(ctlr);
1553 mutex_unlock(&ctlr->io_mutex);
1558 trace_spi_message_start(msg);
1560 if (ctlr->prepare_message) {
1561 ret = ctlr->prepare_message(ctlr, msg);
1563 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1566 spi_finalize_current_message(ctlr);
1569 ctlr->cur_msg_prepared = true;
1572 ret = spi_map_msg(ctlr, msg);
1575 spi_finalize_current_message(ctlr);
1579 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1580 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1581 xfer->ptp_sts_word_pre = 0;
1582 ptp_read_system_prets(xfer->ptp_sts);
1586 ret = ctlr->transfer_one_message(ctlr, msg);
1589 "failed to transfer one message from queue\n");
1594 mutex_unlock(&ctlr->io_mutex);
1596 /* Prod the scheduler in case transfer_one() was busy waiting */
1602 * spi_pump_messages - kthread work function which processes spi message queue
1603 * @work: pointer to kthread work struct contained in the controller struct
1605 static void spi_pump_messages(struct kthread_work *work)
1607 struct spi_controller *ctlr =
1608 container_of(work, struct spi_controller, pump_messages);
1610 __spi_pump_messages(ctlr, true);
1614 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1615 * TX timestamp for the requested byte from the SPI
1616 * transfer. The frequency with which this function
1617 * must be called (once per word, once for the whole
1618 * transfer, once per batch of words etc) is arbitrary
1619 * as long as the @tx buffer offset is greater than or
1620 * equal to the requested byte at the time of the
1621 * call. The timestamp is only taken once, at the
1622 * first such call. It is assumed that the driver
1623 * advances its @tx buffer pointer monotonically.
1624 * @ctlr: Pointer to the spi_controller structure of the driver
1625 * @xfer: Pointer to the transfer being timestamped
1626 * @progress: How many words (not bytes) have been transferred so far
1627 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1628 * transfer, for less jitter in time measurement. Only compatible
1629 * with PIO drivers. If true, must follow up with
1630 * spi_take_timestamp_post or otherwise system will crash.
1631 * WARNING: for fully predictable results, the CPU frequency must
1632 * also be under control (governor).
1634 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1635 struct spi_transfer *xfer,
1636 size_t progress, bool irqs_off)
1641 if (xfer->timestamped)
1644 if (progress > xfer->ptp_sts_word_pre)
1647 /* Capture the resolution of the timestamp */
1648 xfer->ptp_sts_word_pre = progress;
1651 local_irq_save(ctlr->irq_flags);
1655 ptp_read_system_prets(xfer->ptp_sts);
1657 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1660 * spi_take_timestamp_post - helper for drivers to collect the end of the
1661 * TX timestamp for the requested byte from the SPI
1662 * transfer. Can be called with an arbitrary
1663 * frequency: only the first call where @tx exceeds
1664 * or is equal to the requested word will be
1666 * @ctlr: Pointer to the spi_controller structure of the driver
1667 * @xfer: Pointer to the transfer being timestamped
1668 * @progress: How many words (not bytes) have been transferred so far
1669 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1671 void spi_take_timestamp_post(struct spi_controller *ctlr,
1672 struct spi_transfer *xfer,
1673 size_t progress, bool irqs_off)
1678 if (xfer->timestamped)
1681 if (progress < xfer->ptp_sts_word_post)
1684 ptp_read_system_postts(xfer->ptp_sts);
1687 local_irq_restore(ctlr->irq_flags);
1691 /* Capture the resolution of the timestamp */
1692 xfer->ptp_sts_word_post = progress;
1694 xfer->timestamped = true;
1696 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1699 * spi_set_thread_rt - set the controller to pump at realtime priority
1700 * @ctlr: controller to boost priority of
1702 * This can be called because the controller requested realtime priority
1703 * (by setting the ->rt value before calling spi_register_controller()) or
1704 * because a device on the bus said that its transfers needed realtime
1707 * NOTE: at the moment if any device on a bus says it needs realtime then
1708 * the thread will be at realtime priority for all transfers on that
1709 * controller. If this eventually becomes a problem we may see if we can
1710 * find a way to boost the priority only temporarily during relevant
1713 static void spi_set_thread_rt(struct spi_controller *ctlr)
1715 dev_info(&ctlr->dev,
1716 "will run message pump with realtime priority\n");
1717 sched_set_fifo(ctlr->kworker->task);
1720 static int spi_init_queue(struct spi_controller *ctlr)
1722 ctlr->running = false;
1725 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1726 if (IS_ERR(ctlr->kworker)) {
1727 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1728 return PTR_ERR(ctlr->kworker);
1731 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1734 * Controller config will indicate if this controller should run the
1735 * message pump with high (realtime) priority to reduce the transfer
1736 * latency on the bus by minimising the delay between a transfer
1737 * request and the scheduling of the message pump thread. Without this
1738 * setting the message pump thread will remain at default priority.
1741 spi_set_thread_rt(ctlr);
1747 * spi_get_next_queued_message() - called by driver to check for queued
1749 * @ctlr: the controller to check for queued messages
1751 * If there are more messages in the queue, the next message is returned from
1754 * Return: the next message in the queue, else NULL if the queue is empty.
1756 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1758 struct spi_message *next;
1759 unsigned long flags;
1761 /* get a pointer to the next message, if any */
1762 spin_lock_irqsave(&ctlr->queue_lock, flags);
1763 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1765 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1769 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1772 * spi_finalize_current_message() - the current message is complete
1773 * @ctlr: the controller to return the message to
1775 * Called by the driver to notify the core that the message in the front of the
1776 * queue is complete and can be removed from the queue.
1778 void spi_finalize_current_message(struct spi_controller *ctlr)
1780 struct spi_transfer *xfer;
1781 struct spi_message *mesg;
1782 unsigned long flags;
1785 spin_lock_irqsave(&ctlr->queue_lock, flags);
1786 mesg = ctlr->cur_msg;
1787 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1789 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1790 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1791 ptp_read_system_postts(xfer->ptp_sts);
1792 xfer->ptp_sts_word_post = xfer->len;
1796 if (unlikely(ctlr->ptp_sts_supported))
1797 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1798 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1800 spi_unmap_msg(ctlr, mesg);
1802 /* In the prepare_messages callback the spi bus has the opportunity to
1803 * split a transfer to smaller chunks.
1804 * Release splited transfers here since spi_map_msg is done on the
1805 * splited transfers.
1807 spi_res_release(ctlr, mesg);
1809 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1810 ret = ctlr->unprepare_message(ctlr, mesg);
1812 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1817 spin_lock_irqsave(&ctlr->queue_lock, flags);
1818 ctlr->cur_msg = NULL;
1819 ctlr->cur_msg_prepared = false;
1820 ctlr->fallback = false;
1821 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1822 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1824 trace_spi_message_done(mesg);
1828 mesg->complete(mesg->context);
1830 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1832 static int spi_start_queue(struct spi_controller *ctlr)
1834 unsigned long flags;
1836 spin_lock_irqsave(&ctlr->queue_lock, flags);
1838 if (ctlr->running || ctlr->busy) {
1839 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1843 ctlr->running = true;
1844 ctlr->cur_msg = NULL;
1845 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1847 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1852 static int spi_stop_queue(struct spi_controller *ctlr)
1854 unsigned long flags;
1855 unsigned limit = 500;
1858 spin_lock_irqsave(&ctlr->queue_lock, flags);
1861 * This is a bit lame, but is optimized for the common execution path.
1862 * A wait_queue on the ctlr->busy could be used, but then the common
1863 * execution path (pump_messages) would be required to call wake_up or
1864 * friends on every SPI message. Do this instead.
1866 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1867 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1868 usleep_range(10000, 11000);
1869 spin_lock_irqsave(&ctlr->queue_lock, flags);
1872 if (!list_empty(&ctlr->queue) || ctlr->busy)
1875 ctlr->running = false;
1877 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1880 dev_warn(&ctlr->dev, "could not stop message queue\n");
1886 static int spi_destroy_queue(struct spi_controller *ctlr)
1890 ret = spi_stop_queue(ctlr);
1893 * kthread_flush_worker will block until all work is done.
1894 * If the reason that stop_queue timed out is that the work will never
1895 * finish, then it does no good to call flush/stop thread, so
1899 dev_err(&ctlr->dev, "problem destroying queue\n");
1903 kthread_destroy_worker(ctlr->kworker);
1908 static int __spi_queued_transfer(struct spi_device *spi,
1909 struct spi_message *msg,
1912 struct spi_controller *ctlr = spi->controller;
1913 unsigned long flags;
1915 spin_lock_irqsave(&ctlr->queue_lock, flags);
1917 if (!ctlr->running) {
1918 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1921 msg->actual_length = 0;
1922 msg->status = -EINPROGRESS;
1924 list_add_tail(&msg->queue, &ctlr->queue);
1925 if (!ctlr->busy && need_pump)
1926 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1928 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1933 * spi_queued_transfer - transfer function for queued transfers
1934 * @spi: spi device which is requesting transfer
1935 * @msg: spi message which is to handled is queued to driver queue
1937 * Return: zero on success, else a negative error code.
1939 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1941 return __spi_queued_transfer(spi, msg, true);
1944 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1948 ctlr->transfer = spi_queued_transfer;
1949 if (!ctlr->transfer_one_message)
1950 ctlr->transfer_one_message = spi_transfer_one_message;
1952 /* Initialize and start queue */
1953 ret = spi_init_queue(ctlr);
1955 dev_err(&ctlr->dev, "problem initializing queue\n");
1956 goto err_init_queue;
1958 ctlr->queued = true;
1959 ret = spi_start_queue(ctlr);
1961 dev_err(&ctlr->dev, "problem starting queue\n");
1962 goto err_start_queue;
1968 spi_destroy_queue(ctlr);
1974 * spi_flush_queue - Send all pending messages in the queue from the callers'
1976 * @ctlr: controller to process queue for
1978 * This should be used when one wants to ensure all pending messages have been
1979 * sent before doing something. Is used by the spi-mem code to make sure SPI
1980 * memory operations do not preempt regular SPI transfers that have been queued
1981 * before the spi-mem operation.
1983 void spi_flush_queue(struct spi_controller *ctlr)
1985 if (ctlr->transfer == spi_queued_transfer)
1986 __spi_pump_messages(ctlr, false);
1989 /*-------------------------------------------------------------------------*/
1991 #if defined(CONFIG_OF)
1992 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1993 struct device_node *nc)
1998 /* Mode (clock phase/polarity/etc.) */
1999 if (of_property_read_bool(nc, "spi-cpha"))
2000 spi->mode |= SPI_CPHA;
2001 if (of_property_read_bool(nc, "spi-cpol"))
2002 spi->mode |= SPI_CPOL;
2003 if (of_property_read_bool(nc, "spi-3wire"))
2004 spi->mode |= SPI_3WIRE;
2005 if (of_property_read_bool(nc, "spi-lsb-first"))
2006 spi->mode |= SPI_LSB_FIRST;
2007 if (of_property_read_bool(nc, "spi-cs-high"))
2008 spi->mode |= SPI_CS_HIGH;
2010 /* Device DUAL/QUAD mode */
2011 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2014 spi->mode |= SPI_NO_TX;
2019 spi->mode |= SPI_TX_DUAL;
2022 spi->mode |= SPI_TX_QUAD;
2025 spi->mode |= SPI_TX_OCTAL;
2028 dev_warn(&ctlr->dev,
2029 "spi-tx-bus-width %d not supported\n",
2035 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2038 spi->mode |= SPI_NO_RX;
2043 spi->mode |= SPI_RX_DUAL;
2046 spi->mode |= SPI_RX_QUAD;
2049 spi->mode |= SPI_RX_OCTAL;
2052 dev_warn(&ctlr->dev,
2053 "spi-rx-bus-width %d not supported\n",
2059 if (spi_controller_is_slave(ctlr)) {
2060 if (!of_node_name_eq(nc, "slave")) {
2061 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2068 /* Device address */
2069 rc = of_property_read_u32(nc, "reg", &value);
2071 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2075 spi->chip_select = value;
2078 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2079 spi->max_speed_hz = value;
2084 static struct spi_device *
2085 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2087 struct spi_device *spi;
2090 /* Alloc an spi_device */
2091 spi = spi_alloc_device(ctlr);
2093 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2098 /* Select device driver */
2099 rc = of_modalias_node(nc, spi->modalias,
2100 sizeof(spi->modalias));
2102 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2106 rc = of_spi_parse_dt(ctlr, spi, nc);
2110 /* Store a pointer to the node in the device structure */
2112 spi->dev.of_node = nc;
2113 spi->dev.fwnode = of_fwnode_handle(nc);
2115 /* Register the new device */
2116 rc = spi_add_device(spi);
2118 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2119 goto err_of_node_put;
2132 * of_register_spi_devices() - Register child devices onto the SPI bus
2133 * @ctlr: Pointer to spi_controller device
2135 * Registers an spi_device for each child node of controller node which
2136 * represents a valid SPI slave.
2138 static void of_register_spi_devices(struct spi_controller *ctlr)
2140 struct spi_device *spi;
2141 struct device_node *nc;
2143 if (!ctlr->dev.of_node)
2146 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2147 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2149 spi = of_register_spi_device(ctlr, nc);
2151 dev_warn(&ctlr->dev,
2152 "Failed to create SPI device for %pOF\n", nc);
2153 of_node_clear_flag(nc, OF_POPULATED);
2158 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2162 * spi_new_ancillary_device() - Register ancillary SPI device
2163 * @spi: Pointer to the main SPI device registering the ancillary device
2164 * @chip_select: Chip Select of the ancillary device
2166 * Register an ancillary SPI device; for example some chips have a chip-select
2167 * for normal device usage and another one for setup/firmware upload.
2169 * This may only be called from main SPI device's probe routine.
2171 * Return: 0 on success; negative errno on failure
2173 struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2176 struct spi_device *ancillary;
2179 /* Alloc an spi_device */
2180 ancillary = spi_alloc_device(spi->controller);
2186 strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2188 /* Use provided chip-select for ancillary device */
2189 ancillary->chip_select = chip_select;
2191 /* Take over SPI mode/speed from SPI main device */
2192 ancillary->max_speed_hz = spi->max_speed_hz;
2193 ancillary->mode = spi->mode;
2195 /* Register the new device */
2196 rc = spi_add_device_locked(ancillary);
2198 dev_err(&spi->dev, "failed to register ancillary device\n");
2205 spi_dev_put(ancillary);
2208 EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2211 struct acpi_spi_lookup {
2212 struct spi_controller *ctlr;
2220 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2221 struct acpi_spi_lookup *lookup)
2223 const union acpi_object *obj;
2225 if (!x86_apple_machine)
2228 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2229 && obj->buffer.length >= 4)
2230 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2232 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2233 && obj->buffer.length == 8)
2234 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2236 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2237 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2238 lookup->mode |= SPI_LSB_FIRST;
2240 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2241 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2242 lookup->mode |= SPI_CPOL;
2244 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2245 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2246 lookup->mode |= SPI_CPHA;
2249 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2251 struct acpi_spi_lookup *lookup = data;
2252 struct spi_controller *ctlr = lookup->ctlr;
2254 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2255 struct acpi_resource_spi_serialbus *sb;
2256 acpi_handle parent_handle;
2259 sb = &ares->data.spi_serial_bus;
2260 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2262 status = acpi_get_handle(NULL,
2263 sb->resource_source.string_ptr,
2266 if (ACPI_FAILURE(status) ||
2267 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2271 * ACPI DeviceSelection numbering is handled by the
2272 * host controller driver in Windows and can vary
2273 * from driver to driver. In Linux we always expect
2274 * 0 .. max - 1 so we need to ask the driver to
2275 * translate between the two schemes.
2277 if (ctlr->fw_translate_cs) {
2278 int cs = ctlr->fw_translate_cs(ctlr,
2279 sb->device_selection);
2282 lookup->chip_select = cs;
2284 lookup->chip_select = sb->device_selection;
2287 lookup->max_speed_hz = sb->connection_speed;
2288 lookup->bits_per_word = sb->data_bit_length;
2290 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2291 lookup->mode |= SPI_CPHA;
2292 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2293 lookup->mode |= SPI_CPOL;
2294 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2295 lookup->mode |= SPI_CS_HIGH;
2297 } else if (lookup->irq < 0) {
2300 if (acpi_dev_resource_interrupt(ares, 0, &r))
2301 lookup->irq = r.start;
2304 /* Always tell the ACPI core to skip this resource */
2308 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2309 struct acpi_device *adev)
2311 acpi_handle parent_handle = NULL;
2312 struct list_head resource_list;
2313 struct acpi_spi_lookup lookup = {};
2314 struct spi_device *spi;
2317 if (acpi_bus_get_status(adev) || !adev->status.present ||
2318 acpi_device_enumerated(adev))
2324 INIT_LIST_HEAD(&resource_list);
2325 ret = acpi_dev_get_resources(adev, &resource_list,
2326 acpi_spi_add_resource, &lookup);
2327 acpi_dev_free_resource_list(&resource_list);
2330 /* found SPI in _CRS but it points to another controller */
2333 if (!lookup.max_speed_hz &&
2334 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2335 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2336 /* Apple does not use _CRS but nested devices for SPI slaves */
2337 acpi_spi_parse_apple_properties(adev, &lookup);
2340 if (!lookup.max_speed_hz)
2343 spi = spi_alloc_device(ctlr);
2345 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2346 dev_name(&adev->dev));
2347 return AE_NO_MEMORY;
2351 ACPI_COMPANION_SET(&spi->dev, adev);
2352 spi->max_speed_hz = lookup.max_speed_hz;
2353 spi->mode |= lookup.mode;
2354 spi->irq = lookup.irq;
2355 spi->bits_per_word = lookup.bits_per_word;
2356 spi->chip_select = lookup.chip_select;
2358 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2359 sizeof(spi->modalias));
2362 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2364 acpi_device_set_enumerated(adev);
2366 adev->power.flags.ignore_parent = true;
2367 if (spi_add_device(spi)) {
2368 adev->power.flags.ignore_parent = false;
2369 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2370 dev_name(&adev->dev));
2377 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2378 void *data, void **return_value)
2380 struct spi_controller *ctlr = data;
2381 struct acpi_device *adev;
2383 if (acpi_bus_get_device(handle, &adev))
2386 return acpi_register_spi_device(ctlr, adev);
2389 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2391 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2396 handle = ACPI_HANDLE(ctlr->dev.parent);
2400 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2401 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2402 acpi_spi_add_device, NULL, ctlr, NULL);
2403 if (ACPI_FAILURE(status))
2404 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2407 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2408 #endif /* CONFIG_ACPI */
2410 static void spi_controller_release(struct device *dev)
2412 struct spi_controller *ctlr;
2414 ctlr = container_of(dev, struct spi_controller, dev);
2418 static struct class spi_master_class = {
2419 .name = "spi_master",
2420 .owner = THIS_MODULE,
2421 .dev_release = spi_controller_release,
2422 .dev_groups = spi_master_groups,
2425 #ifdef CONFIG_SPI_SLAVE
2427 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2429 * @spi: device used for the current transfer
2431 int spi_slave_abort(struct spi_device *spi)
2433 struct spi_controller *ctlr = spi->controller;
2435 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2436 return ctlr->slave_abort(ctlr);
2440 EXPORT_SYMBOL_GPL(spi_slave_abort);
2442 static int match_true(struct device *dev, void *data)
2447 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2450 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2452 struct device *child;
2454 child = device_find_child(&ctlr->dev, NULL, match_true);
2455 return sprintf(buf, "%s\n",
2456 child ? to_spi_device(child)->modalias : NULL);
2459 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2460 const char *buf, size_t count)
2462 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2464 struct spi_device *spi;
2465 struct device *child;
2469 rc = sscanf(buf, "%31s", name);
2470 if (rc != 1 || !name[0])
2473 child = device_find_child(&ctlr->dev, NULL, match_true);
2475 /* Remove registered slave */
2476 device_unregister(child);
2480 if (strcmp(name, "(null)")) {
2481 /* Register new slave */
2482 spi = spi_alloc_device(ctlr);
2486 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2488 rc = spi_add_device(spi);
2498 static DEVICE_ATTR_RW(slave);
2500 static struct attribute *spi_slave_attrs[] = {
2501 &dev_attr_slave.attr,
2505 static const struct attribute_group spi_slave_group = {
2506 .attrs = spi_slave_attrs,
2509 static const struct attribute_group *spi_slave_groups[] = {
2510 &spi_controller_statistics_group,
2515 static struct class spi_slave_class = {
2516 .name = "spi_slave",
2517 .owner = THIS_MODULE,
2518 .dev_release = spi_controller_release,
2519 .dev_groups = spi_slave_groups,
2522 extern struct class spi_slave_class; /* dummy */
2526 * __spi_alloc_controller - allocate an SPI master or slave controller
2527 * @dev: the controller, possibly using the platform_bus
2528 * @size: how much zeroed driver-private data to allocate; the pointer to this
2529 * memory is in the driver_data field of the returned device, accessible
2530 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2531 * drivers granting DMA access to portions of their private data need to
2532 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2533 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2534 * slave (true) controller
2535 * Context: can sleep
2537 * This call is used only by SPI controller drivers, which are the
2538 * only ones directly touching chip registers. It's how they allocate
2539 * an spi_controller structure, prior to calling spi_register_controller().
2541 * This must be called from context that can sleep.
2543 * The caller is responsible for assigning the bus number and initializing the
2544 * controller's methods before calling spi_register_controller(); and (after
2545 * errors adding the device) calling spi_controller_put() to prevent a memory
2548 * Return: the SPI controller structure on success, else NULL.
2550 struct spi_controller *__spi_alloc_controller(struct device *dev,
2551 unsigned int size, bool slave)
2553 struct spi_controller *ctlr;
2554 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2559 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2563 device_initialize(&ctlr->dev);
2565 ctlr->num_chipselect = 1;
2566 ctlr->slave = slave;
2567 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2568 ctlr->dev.class = &spi_slave_class;
2570 ctlr->dev.class = &spi_master_class;
2571 ctlr->dev.parent = dev;
2572 pm_suspend_ignore_children(&ctlr->dev, true);
2573 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2577 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2579 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2581 spi_controller_put(*(struct spi_controller **)ctlr);
2585 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2586 * @dev: physical device of SPI controller
2587 * @size: how much zeroed driver-private data to allocate
2588 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2589 * Context: can sleep
2591 * Allocate an SPI controller and automatically release a reference on it
2592 * when @dev is unbound from its driver. Drivers are thus relieved from
2593 * having to call spi_controller_put().
2595 * The arguments to this function are identical to __spi_alloc_controller().
2597 * Return: the SPI controller structure on success, else NULL.
2599 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2603 struct spi_controller **ptr, *ctlr;
2605 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2610 ctlr = __spi_alloc_controller(dev, size, slave);
2612 ctlr->devm_allocated = true;
2614 devres_add(dev, ptr);
2621 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2624 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2627 struct device_node *np = ctlr->dev.of_node;
2632 nb = of_gpio_named_count(np, "cs-gpios");
2633 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2635 /* Return error only for an incorrectly formed cs-gpios property */
2636 if (nb == 0 || nb == -ENOENT)
2641 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2643 ctlr->cs_gpios = cs;
2645 if (!ctlr->cs_gpios)
2648 for (i = 0; i < ctlr->num_chipselect; i++)
2651 for (i = 0; i < nb; i++)
2652 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2657 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2664 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2665 * @ctlr: The SPI master to grab GPIO descriptors for
2667 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2670 struct gpio_desc **cs;
2671 struct device *dev = &ctlr->dev;
2672 unsigned long native_cs_mask = 0;
2673 unsigned int num_cs_gpios = 0;
2675 nb = gpiod_count(dev, "cs");
2677 /* No GPIOs at all is fine, else return the error */
2683 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2685 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2689 ctlr->cs_gpiods = cs;
2691 for (i = 0; i < nb; i++) {
2693 * Most chipselects are active low, the inverted
2694 * semantics are handled by special quirks in gpiolib,
2695 * so initializing them GPIOD_OUT_LOW here means
2696 * "unasserted", in most cases this will drive the physical
2699 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2702 return PTR_ERR(cs[i]);
2706 * If we find a CS GPIO, name it after the device and
2711 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2715 gpiod_set_consumer_name(cs[i], gpioname);
2720 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2721 dev_err(dev, "Invalid native chip select %d\n", i);
2724 native_cs_mask |= BIT(i);
2727 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2729 if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2730 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2731 dev_err(dev, "No unused native chip select available\n");
2738 static int spi_controller_check_ops(struct spi_controller *ctlr)
2741 * The controller may implement only the high-level SPI-memory like
2742 * operations if it does not support regular SPI transfers, and this is
2744 * If ->mem_ops is NULL, we request that at least one of the
2745 * ->transfer_xxx() method be implemented.
2747 if (ctlr->mem_ops) {
2748 if (!ctlr->mem_ops->exec_op)
2750 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2751 !ctlr->transfer_one_message) {
2759 * spi_register_controller - register SPI master or slave controller
2760 * @ctlr: initialized master, originally from spi_alloc_master() or
2762 * Context: can sleep
2764 * SPI controllers connect to their drivers using some non-SPI bus,
2765 * such as the platform bus. The final stage of probe() in that code
2766 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2768 * SPI controllers use board specific (often SOC specific) bus numbers,
2769 * and board-specific addressing for SPI devices combines those numbers
2770 * with chip select numbers. Since SPI does not directly support dynamic
2771 * device identification, boards need configuration tables telling which
2772 * chip is at which address.
2774 * This must be called from context that can sleep. It returns zero on
2775 * success, else a negative error code (dropping the controller's refcount).
2776 * After a successful return, the caller is responsible for calling
2777 * spi_unregister_controller().
2779 * Return: zero on success, else a negative error code.
2781 int spi_register_controller(struct spi_controller *ctlr)
2783 struct device *dev = ctlr->dev.parent;
2784 struct boardinfo *bi;
2786 int id, first_dynamic;
2792 * Make sure all necessary hooks are implemented before registering
2793 * the SPI controller.
2795 status = spi_controller_check_ops(ctlr);
2799 if (ctlr->bus_num >= 0) {
2800 /* devices with a fixed bus num must check-in with the num */
2801 mutex_lock(&board_lock);
2802 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2803 ctlr->bus_num + 1, GFP_KERNEL);
2804 mutex_unlock(&board_lock);
2805 if (WARN(id < 0, "couldn't get idr"))
2806 return id == -ENOSPC ? -EBUSY : id;
2808 } else if (ctlr->dev.of_node) {
2809 /* allocate dynamic bus number using Linux idr */
2810 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2813 mutex_lock(&board_lock);
2814 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2815 ctlr->bus_num + 1, GFP_KERNEL);
2816 mutex_unlock(&board_lock);
2817 if (WARN(id < 0, "couldn't get idr"))
2818 return id == -ENOSPC ? -EBUSY : id;
2821 if (ctlr->bus_num < 0) {
2822 first_dynamic = of_alias_get_highest_id("spi");
2823 if (first_dynamic < 0)
2828 mutex_lock(&board_lock);
2829 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2831 mutex_unlock(&board_lock);
2832 if (WARN(id < 0, "couldn't get idr"))
2836 INIT_LIST_HEAD(&ctlr->queue);
2837 spin_lock_init(&ctlr->queue_lock);
2838 spin_lock_init(&ctlr->bus_lock_spinlock);
2839 mutex_init(&ctlr->bus_lock_mutex);
2840 mutex_init(&ctlr->io_mutex);
2841 ctlr->bus_lock_flag = 0;
2842 init_completion(&ctlr->xfer_completion);
2843 if (!ctlr->max_dma_len)
2844 ctlr->max_dma_len = INT_MAX;
2846 /* register the device, then userspace will see it.
2847 * registration fails if the bus ID is in use.
2849 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2851 if (!spi_controller_is_slave(ctlr)) {
2852 if (ctlr->use_gpio_descriptors) {
2853 status = spi_get_gpio_descs(ctlr);
2857 * A controller using GPIO descriptors always
2858 * supports SPI_CS_HIGH if need be.
2860 ctlr->mode_bits |= SPI_CS_HIGH;
2862 /* Legacy code path for GPIOs from DT */
2863 status = of_spi_get_gpio_numbers(ctlr);
2870 * Even if it's just one always-selected device, there must
2871 * be at least one chipselect.
2873 if (!ctlr->num_chipselect) {
2878 status = device_add(&ctlr->dev);
2881 dev_dbg(dev, "registered %s %s\n",
2882 spi_controller_is_slave(ctlr) ? "slave" : "master",
2883 dev_name(&ctlr->dev));
2886 * If we're using a queued driver, start the queue. Note that we don't
2887 * need the queueing logic if the driver is only supporting high-level
2888 * memory operations.
2890 if (ctlr->transfer) {
2891 dev_info(dev, "controller is unqueued, this is deprecated\n");
2892 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2893 status = spi_controller_initialize_queue(ctlr);
2895 device_del(&ctlr->dev);
2899 /* add statistics */
2900 spin_lock_init(&ctlr->statistics.lock);
2902 mutex_lock(&board_lock);
2903 list_add_tail(&ctlr->list, &spi_controller_list);
2904 list_for_each_entry(bi, &board_list, list)
2905 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2906 mutex_unlock(&board_lock);
2908 /* Register devices from the device tree and ACPI */
2909 of_register_spi_devices(ctlr);
2910 acpi_register_spi_devices(ctlr);
2914 mutex_lock(&board_lock);
2915 idr_remove(&spi_master_idr, ctlr->bus_num);
2916 mutex_unlock(&board_lock);
2919 EXPORT_SYMBOL_GPL(spi_register_controller);
2921 static void devm_spi_unregister(void *ctlr)
2923 spi_unregister_controller(ctlr);
2927 * devm_spi_register_controller - register managed SPI master or slave
2929 * @dev: device managing SPI controller
2930 * @ctlr: initialized controller, originally from spi_alloc_master() or
2932 * Context: can sleep
2934 * Register a SPI device as with spi_register_controller() which will
2935 * automatically be unregistered and freed.
2937 * Return: zero on success, else a negative error code.
2939 int devm_spi_register_controller(struct device *dev,
2940 struct spi_controller *ctlr)
2944 ret = spi_register_controller(ctlr);
2948 return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
2950 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2952 static int __unregister(struct device *dev, void *null)
2954 spi_unregister_device(to_spi_device(dev));
2959 * spi_unregister_controller - unregister SPI master or slave controller
2960 * @ctlr: the controller being unregistered
2961 * Context: can sleep
2963 * This call is used only by SPI controller drivers, which are the
2964 * only ones directly touching chip registers.
2966 * This must be called from context that can sleep.
2968 * Note that this function also drops a reference to the controller.
2970 void spi_unregister_controller(struct spi_controller *ctlr)
2972 struct spi_controller *found;
2973 int id = ctlr->bus_num;
2975 /* Prevent addition of new devices, unregister existing ones */
2976 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2977 mutex_lock(&spi_add_lock);
2979 device_for_each_child(&ctlr->dev, NULL, __unregister);
2981 /* First make sure that this controller was ever added */
2982 mutex_lock(&board_lock);
2983 found = idr_find(&spi_master_idr, id);
2984 mutex_unlock(&board_lock);
2986 if (spi_destroy_queue(ctlr))
2987 dev_err(&ctlr->dev, "queue remove failed\n");
2989 mutex_lock(&board_lock);
2990 list_del(&ctlr->list);
2991 mutex_unlock(&board_lock);
2993 device_del(&ctlr->dev);
2995 /* Release the last reference on the controller if its driver
2996 * has not yet been converted to devm_spi_alloc_master/slave().
2998 if (!ctlr->devm_allocated)
2999 put_device(&ctlr->dev);
3002 mutex_lock(&board_lock);
3004 idr_remove(&spi_master_idr, id);
3005 mutex_unlock(&board_lock);
3007 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3008 mutex_unlock(&spi_add_lock);
3010 EXPORT_SYMBOL_GPL(spi_unregister_controller);
3012 int spi_controller_suspend(struct spi_controller *ctlr)
3016 /* Basically no-ops for non-queued controllers */
3020 ret = spi_stop_queue(ctlr);
3022 dev_err(&ctlr->dev, "queue stop failed\n");
3026 EXPORT_SYMBOL_GPL(spi_controller_suspend);
3028 int spi_controller_resume(struct spi_controller *ctlr)
3035 ret = spi_start_queue(ctlr);
3037 dev_err(&ctlr->dev, "queue restart failed\n");
3041 EXPORT_SYMBOL_GPL(spi_controller_resume);
3043 static int __spi_controller_match(struct device *dev, const void *data)
3045 struct spi_controller *ctlr;
3046 const u16 *bus_num = data;
3048 ctlr = container_of(dev, struct spi_controller, dev);
3049 return ctlr->bus_num == *bus_num;
3053 * spi_busnum_to_master - look up master associated with bus_num
3054 * @bus_num: the master's bus number
3055 * Context: can sleep
3057 * This call may be used with devices that are registered after
3058 * arch init time. It returns a refcounted pointer to the relevant
3059 * spi_controller (which the caller must release), or NULL if there is
3060 * no such master registered.
3062 * Return: the SPI master structure on success, else NULL.
3064 struct spi_controller *spi_busnum_to_master(u16 bus_num)
3067 struct spi_controller *ctlr = NULL;
3069 dev = class_find_device(&spi_master_class, NULL, &bus_num,
3070 __spi_controller_match);
3072 ctlr = container_of(dev, struct spi_controller, dev);
3073 /* reference got in class_find_device */
3076 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
3078 /*-------------------------------------------------------------------------*/
3080 /* Core methods for SPI resource management */
3083 * spi_res_alloc - allocate a spi resource that is life-cycle managed
3084 * during the processing of a spi_message while using
3086 * @spi: the spi device for which we allocate memory
3087 * @release: the release code to execute for this resource
3088 * @size: size to alloc and return
3089 * @gfp: GFP allocation flags
3091 * Return: the pointer to the allocated data
3093 * This may get enhanced in the future to allocate from a memory pool
3094 * of the @spi_device or @spi_controller to avoid repeated allocations.
3096 void *spi_res_alloc(struct spi_device *spi,
3097 spi_res_release_t release,
3098 size_t size, gfp_t gfp)
3100 struct spi_res *sres;
3102 sres = kzalloc(sizeof(*sres) + size, gfp);
3106 INIT_LIST_HEAD(&sres->entry);
3107 sres->release = release;
3111 EXPORT_SYMBOL_GPL(spi_res_alloc);
3114 * spi_res_free - free an spi resource
3115 * @res: pointer to the custom data of a resource
3118 void spi_res_free(void *res)
3120 struct spi_res *sres = container_of(res, struct spi_res, data);
3125 WARN_ON(!list_empty(&sres->entry));
3128 EXPORT_SYMBOL_GPL(spi_res_free);
3131 * spi_res_add - add a spi_res to the spi_message
3132 * @message: the spi message
3133 * @res: the spi_resource
3135 void spi_res_add(struct spi_message *message, void *res)
3137 struct spi_res *sres = container_of(res, struct spi_res, data);
3139 WARN_ON(!list_empty(&sres->entry));
3140 list_add_tail(&sres->entry, &message->resources);
3142 EXPORT_SYMBOL_GPL(spi_res_add);
3145 * spi_res_release - release all spi resources for this message
3146 * @ctlr: the @spi_controller
3147 * @message: the @spi_message
3149 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3151 struct spi_res *res, *tmp;
3153 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3155 res->release(ctlr, message, res->data);
3157 list_del(&res->entry);
3162 EXPORT_SYMBOL_GPL(spi_res_release);
3164 /*-------------------------------------------------------------------------*/
3166 /* Core methods for spi_message alterations */
3168 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3169 struct spi_message *msg,
3172 struct spi_replaced_transfers *rxfer = res;
3175 /* call extra callback if requested */
3177 rxfer->release(ctlr, msg, res);
3179 /* insert replaced transfers back into the message */
3180 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3182 /* remove the formerly inserted entries */
3183 for (i = 0; i < rxfer->inserted; i++)
3184 list_del(&rxfer->inserted_transfers[i].transfer_list);
3188 * spi_replace_transfers - replace transfers with several transfers
3189 * and register change with spi_message.resources
3190 * @msg: the spi_message we work upon
3191 * @xfer_first: the first spi_transfer we want to replace
3192 * @remove: number of transfers to remove
3193 * @insert: the number of transfers we want to insert instead
3194 * @release: extra release code necessary in some circumstances
3195 * @extradatasize: extra data to allocate (with alignment guarantees
3196 * of struct @spi_transfer)
3199 * Returns: pointer to @spi_replaced_transfers,
3200 * PTR_ERR(...) in case of errors.
3202 struct spi_replaced_transfers *spi_replace_transfers(
3203 struct spi_message *msg,
3204 struct spi_transfer *xfer_first,
3207 spi_replaced_release_t release,
3208 size_t extradatasize,
3211 struct spi_replaced_transfers *rxfer;
3212 struct spi_transfer *xfer;
3215 /* allocate the structure using spi_res */
3216 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3217 struct_size(rxfer, inserted_transfers, insert)
3221 return ERR_PTR(-ENOMEM);
3223 /* the release code to invoke before running the generic release */
3224 rxfer->release = release;
3226 /* assign extradata */
3229 &rxfer->inserted_transfers[insert];
3231 /* init the replaced_transfers list */
3232 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3234 /* assign the list_entry after which we should reinsert
3235 * the @replaced_transfers - it may be spi_message.messages!
3237 rxfer->replaced_after = xfer_first->transfer_list.prev;
3239 /* remove the requested number of transfers */
3240 for (i = 0; i < remove; i++) {
3241 /* if the entry after replaced_after it is msg->transfers
3242 * then we have been requested to remove more transfers
3243 * than are in the list
3245 if (rxfer->replaced_after->next == &msg->transfers) {
3246 dev_err(&msg->spi->dev,
3247 "requested to remove more spi_transfers than are available\n");
3248 /* insert replaced transfers back into the message */
3249 list_splice(&rxfer->replaced_transfers,
3250 rxfer->replaced_after);
3252 /* free the spi_replace_transfer structure */
3253 spi_res_free(rxfer);
3255 /* and return with an error */
3256 return ERR_PTR(-EINVAL);
3259 /* remove the entry after replaced_after from list of
3260 * transfers and add it to list of replaced_transfers
3262 list_move_tail(rxfer->replaced_after->next,
3263 &rxfer->replaced_transfers);
3266 /* create copy of the given xfer with identical settings
3267 * based on the first transfer to get removed
3269 for (i = 0; i < insert; i++) {
3270 /* we need to run in reverse order */
3271 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3273 /* copy all spi_transfer data */
3274 memcpy(xfer, xfer_first, sizeof(*xfer));
3277 list_add(&xfer->transfer_list, rxfer->replaced_after);
3279 /* clear cs_change and delay for all but the last */
3281 xfer->cs_change = false;
3282 xfer->delay.value = 0;
3286 /* set up inserted */
3287 rxfer->inserted = insert;
3289 /* and register it with spi_res/spi_message */
3290 spi_res_add(msg, rxfer);
3294 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3296 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3297 struct spi_message *msg,
3298 struct spi_transfer **xferp,
3302 struct spi_transfer *xfer = *xferp, *xfers;
3303 struct spi_replaced_transfers *srt;
3307 /* calculate how many we have to replace */
3308 count = DIV_ROUND_UP(xfer->len, maxsize);
3310 /* create replacement */
3311 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3313 return PTR_ERR(srt);
3314 xfers = srt->inserted_transfers;
3316 /* now handle each of those newly inserted spi_transfers
3317 * note that the replacements spi_transfers all are preset
3318 * to the same values as *xferp, so tx_buf, rx_buf and len
3319 * are all identical (as well as most others)
3320 * so we just have to fix up len and the pointers.
3322 * this also includes support for the depreciated
3323 * spi_message.is_dma_mapped interface
3326 /* the first transfer just needs the length modified, so we
3327 * run it outside the loop
3329 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3331 /* all the others need rx_buf/tx_buf also set */
3332 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3333 /* update rx_buf, tx_buf and dma */
3334 if (xfers[i].rx_buf)
3335 xfers[i].rx_buf += offset;
3336 if (xfers[i].rx_dma)
3337 xfers[i].rx_dma += offset;
3338 if (xfers[i].tx_buf)
3339 xfers[i].tx_buf += offset;
3340 if (xfers[i].tx_dma)
3341 xfers[i].tx_dma += offset;
3344 xfers[i].len = min(maxsize, xfers[i].len - offset);
3347 /* we set up xferp to the last entry we have inserted,
3348 * so that we skip those already split transfers
3350 *xferp = &xfers[count - 1];
3352 /* increment statistics counters */
3353 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3354 transfers_split_maxsize);
3355 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3356 transfers_split_maxsize);
3362 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3363 * when an individual transfer exceeds a
3365 * @ctlr: the @spi_controller for this transfer
3366 * @msg: the @spi_message to transform
3367 * @maxsize: the maximum when to apply this
3368 * @gfp: GFP allocation flags
3370 * Return: status of transformation
3372 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3373 struct spi_message *msg,
3377 struct spi_transfer *xfer;
3380 /* iterate over the transfer_list,
3381 * but note that xfer is advanced to the last transfer inserted
3382 * to avoid checking sizes again unnecessarily (also xfer does
3383 * potentiall belong to a different list by the time the
3384 * replacement has happened
3386 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3387 if (xfer->len > maxsize) {
3388 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3397 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3399 /*-------------------------------------------------------------------------*/
3401 /* Core methods for SPI controller protocol drivers. Some of the
3402 * other core methods are currently defined as inline functions.
3405 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3408 if (ctlr->bits_per_word_mask) {
3409 /* Only 32 bits fit in the mask */
3410 if (bits_per_word > 32)
3412 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3420 * spi_setup - setup SPI mode and clock rate
3421 * @spi: the device whose settings are being modified
3422 * Context: can sleep, and no requests are queued to the device
3424 * SPI protocol drivers may need to update the transfer mode if the
3425 * device doesn't work with its default. They may likewise need
3426 * to update clock rates or word sizes from initial values. This function
3427 * changes those settings, and must be called from a context that can sleep.
3428 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3429 * effect the next time the device is selected and data is transferred to
3430 * or from it. When this function returns, the spi device is deselected.
3432 * Note that this call will fail if the protocol driver specifies an option
3433 * that the underlying controller or its driver does not support. For
3434 * example, not all hardware supports wire transfers using nine bit words,
3435 * LSB-first wire encoding, or active-high chipselects.
3437 * Return: zero on success, else a negative error code.
3439 int spi_setup(struct spi_device *spi)
3441 unsigned bad_bits, ugly_bits;
3445 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3446 * are set at the same time
3448 if ((hweight_long(spi->mode &
3449 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3450 (hweight_long(spi->mode &
3451 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3453 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3456 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3458 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3459 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3460 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3462 /* help drivers fail *cleanly* when they need options
3463 * that aren't supported with their current controller
3464 * SPI_CS_WORD has a fallback software implementation,
3465 * so it is ignored here.
3467 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3468 SPI_NO_TX | SPI_NO_RX);
3469 /* nothing prevents from working with active-high CS in case if it
3470 * is driven by GPIO.
3472 if (gpio_is_valid(spi->cs_gpio))
3473 bad_bits &= ~SPI_CS_HIGH;
3474 ugly_bits = bad_bits &
3475 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3476 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3479 "setup: ignoring unsupported mode bits %x\n",
3481 spi->mode &= ~ugly_bits;
3482 bad_bits &= ~ugly_bits;
3485 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3490 if (!spi->bits_per_word)
3491 spi->bits_per_word = 8;
3493 status = __spi_validate_bits_per_word(spi->controller,
3494 spi->bits_per_word);
3498 if (spi->controller->max_speed_hz &&
3499 (!spi->max_speed_hz ||
3500 spi->max_speed_hz > spi->controller->max_speed_hz))
3501 spi->max_speed_hz = spi->controller->max_speed_hz;
3503 mutex_lock(&spi->controller->io_mutex);
3505 if (spi->controller->setup) {
3506 status = spi->controller->setup(spi);
3508 mutex_unlock(&spi->controller->io_mutex);
3509 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3515 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3516 status = pm_runtime_get_sync(spi->controller->dev.parent);
3518 mutex_unlock(&spi->controller->io_mutex);
3519 pm_runtime_put_noidle(spi->controller->dev.parent);
3520 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3526 * We do not want to return positive value from pm_runtime_get,
3527 * there are many instances of devices calling spi_setup() and
3528 * checking for a non-zero return value instead of a negative
3533 spi_set_cs(spi, false, true);
3534 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3535 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3537 spi_set_cs(spi, false, true);
3540 mutex_unlock(&spi->controller->io_mutex);
3542 if (spi->rt && !spi->controller->rt) {
3543 spi->controller->rt = true;
3544 spi_set_thread_rt(spi->controller);
3547 trace_spi_setup(spi, status);
3549 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3550 spi->mode & SPI_MODE_X_MASK,
3551 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3552 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3553 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3554 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3555 spi->bits_per_word, spi->max_speed_hz,
3560 EXPORT_SYMBOL_GPL(spi_setup);
3562 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3563 struct spi_device *spi)
3567 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3571 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3575 if (delay1 < delay2)
3576 memcpy(&xfer->word_delay, &spi->word_delay,
3577 sizeof(xfer->word_delay));
3582 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3584 struct spi_controller *ctlr = spi->controller;
3585 struct spi_transfer *xfer;
3588 if (list_empty(&message->transfers))
3591 /* If an SPI controller does not support toggling the CS line on each
3592 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3593 * for the CS line, we can emulate the CS-per-word hardware function by
3594 * splitting transfers into one-word transfers and ensuring that
3595 * cs_change is set for each transfer.
3597 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3599 gpio_is_valid(spi->cs_gpio))) {
3603 maxsize = (spi->bits_per_word + 7) / 8;
3605 /* spi_split_transfers_maxsize() requires message->spi */
3608 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3613 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3614 /* don't change cs_change on the last entry in the list */
3615 if (list_is_last(&xfer->transfer_list, &message->transfers))
3617 xfer->cs_change = 1;
3621 /* Half-duplex links include original MicroWire, and ones with
3622 * only one data pin like SPI_3WIRE (switches direction) or where
3623 * either MOSI or MISO is missing. They can also be caused by
3624 * software limitations.
3626 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3627 (spi->mode & SPI_3WIRE)) {
3628 unsigned flags = ctlr->flags;
3630 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3631 if (xfer->rx_buf && xfer->tx_buf)
3633 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3635 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3641 * Set transfer bits_per_word and max speed as spi device default if
3642 * it is not set for this transfer.
3643 * Set transfer tx_nbits and rx_nbits as single transfer default
3644 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3645 * Ensure transfer word_delay is at least as long as that required by
3648 message->frame_length = 0;
3649 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3650 xfer->effective_speed_hz = 0;
3651 message->frame_length += xfer->len;
3652 if (!xfer->bits_per_word)
3653 xfer->bits_per_word = spi->bits_per_word;
3655 if (!xfer->speed_hz)
3656 xfer->speed_hz = spi->max_speed_hz;
3658 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3659 xfer->speed_hz = ctlr->max_speed_hz;
3661 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3665 * SPI transfer length should be multiple of SPI word size
3666 * where SPI word size should be power-of-two multiple
3668 if (xfer->bits_per_word <= 8)
3670 else if (xfer->bits_per_word <= 16)
3675 /* No partial transfers accepted */
3676 if (xfer->len % w_size)
3679 if (xfer->speed_hz && ctlr->min_speed_hz &&
3680 xfer->speed_hz < ctlr->min_speed_hz)
3683 if (xfer->tx_buf && !xfer->tx_nbits)
3684 xfer->tx_nbits = SPI_NBITS_SINGLE;
3685 if (xfer->rx_buf && !xfer->rx_nbits)
3686 xfer->rx_nbits = SPI_NBITS_SINGLE;
3687 /* check transfer tx/rx_nbits:
3688 * 1. check the value matches one of single, dual and quad
3689 * 2. check tx/rx_nbits match the mode in spi_device
3692 if (spi->mode & SPI_NO_TX)
3694 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3695 xfer->tx_nbits != SPI_NBITS_DUAL &&
3696 xfer->tx_nbits != SPI_NBITS_QUAD)
3698 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3699 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3701 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3702 !(spi->mode & SPI_TX_QUAD))
3705 /* check transfer rx_nbits */
3707 if (spi->mode & SPI_NO_RX)
3709 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3710 xfer->rx_nbits != SPI_NBITS_DUAL &&
3711 xfer->rx_nbits != SPI_NBITS_QUAD)
3713 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3714 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3716 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3717 !(spi->mode & SPI_RX_QUAD))
3721 if (_spi_xfer_word_delay_update(xfer, spi))
3725 message->status = -EINPROGRESS;
3730 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3732 struct spi_controller *ctlr = spi->controller;
3733 struct spi_transfer *xfer;
3736 * Some controllers do not support doing regular SPI transfers. Return
3737 * ENOTSUPP when this is the case.
3739 if (!ctlr->transfer)
3744 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3745 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3747 trace_spi_message_submit(message);
3749 if (!ctlr->ptp_sts_supported) {
3750 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3751 xfer->ptp_sts_word_pre = 0;
3752 ptp_read_system_prets(xfer->ptp_sts);
3756 return ctlr->transfer(spi, message);
3760 * spi_async - asynchronous SPI transfer
3761 * @spi: device with which data will be exchanged
3762 * @message: describes the data transfers, including completion callback
3763 * Context: any (irqs may be blocked, etc)
3765 * This call may be used in_irq and other contexts which can't sleep,
3766 * as well as from task contexts which can sleep.
3768 * The completion callback is invoked in a context which can't sleep.
3769 * Before that invocation, the value of message->status is undefined.
3770 * When the callback is issued, message->status holds either zero (to
3771 * indicate complete success) or a negative error code. After that
3772 * callback returns, the driver which issued the transfer request may
3773 * deallocate the associated memory; it's no longer in use by any SPI
3774 * core or controller driver code.
3776 * Note that although all messages to a spi_device are handled in
3777 * FIFO order, messages may go to different devices in other orders.
3778 * Some device might be higher priority, or have various "hard" access
3779 * time requirements, for example.
3781 * On detection of any fault during the transfer, processing of
3782 * the entire message is aborted, and the device is deselected.
3783 * Until returning from the associated message completion callback,
3784 * no other spi_message queued to that device will be processed.
3785 * (This rule applies equally to all the synchronous transfer calls,
3786 * which are wrappers around this core asynchronous primitive.)
3788 * Return: zero on success, else a negative error code.
3790 int spi_async(struct spi_device *spi, struct spi_message *message)
3792 struct spi_controller *ctlr = spi->controller;
3794 unsigned long flags;
3796 ret = __spi_validate(spi, message);
3800 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3802 if (ctlr->bus_lock_flag)
3805 ret = __spi_async(spi, message);
3807 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3811 EXPORT_SYMBOL_GPL(spi_async);
3814 * spi_async_locked - version of spi_async with exclusive bus usage
3815 * @spi: device with which data will be exchanged
3816 * @message: describes the data transfers, including completion callback
3817 * Context: any (irqs may be blocked, etc)
3819 * This call may be used in_irq and other contexts which can't sleep,
3820 * as well as from task contexts which can sleep.
3822 * The completion callback is invoked in a context which can't sleep.
3823 * Before that invocation, the value of message->status is undefined.
3824 * When the callback is issued, message->status holds either zero (to
3825 * indicate complete success) or a negative error code. After that
3826 * callback returns, the driver which issued the transfer request may
3827 * deallocate the associated memory; it's no longer in use by any SPI
3828 * core or controller driver code.
3830 * Note that although all messages to a spi_device are handled in
3831 * FIFO order, messages may go to different devices in other orders.
3832 * Some device might be higher priority, or have various "hard" access
3833 * time requirements, for example.
3835 * On detection of any fault during the transfer, processing of
3836 * the entire message is aborted, and the device is deselected.
3837 * Until returning from the associated message completion callback,
3838 * no other spi_message queued to that device will be processed.
3839 * (This rule applies equally to all the synchronous transfer calls,
3840 * which are wrappers around this core asynchronous primitive.)
3842 * Return: zero on success, else a negative error code.
3844 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3846 struct spi_controller *ctlr = spi->controller;
3848 unsigned long flags;
3850 ret = __spi_validate(spi, message);
3854 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3856 ret = __spi_async(spi, message);
3858 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3863 EXPORT_SYMBOL_GPL(spi_async_locked);
3865 /*-------------------------------------------------------------------------*/
3867 /* Utility methods for SPI protocol drivers, layered on
3868 * top of the core. Some other utility methods are defined as
3872 static void spi_complete(void *arg)
3877 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3879 DECLARE_COMPLETION_ONSTACK(done);
3881 struct spi_controller *ctlr = spi->controller;
3882 unsigned long flags;
3884 status = __spi_validate(spi, message);
3888 message->complete = spi_complete;
3889 message->context = &done;
3892 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3893 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3895 /* If we're not using the legacy transfer method then we will
3896 * try to transfer in the calling context so special case.
3897 * This code would be less tricky if we could remove the
3898 * support for driver implemented message queues.
3900 if (ctlr->transfer == spi_queued_transfer) {
3901 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3903 trace_spi_message_submit(message);
3905 status = __spi_queued_transfer(spi, message, false);
3907 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3909 status = spi_async_locked(spi, message);
3913 /* Push out the messages in the calling context if we
3916 if (ctlr->transfer == spi_queued_transfer) {
3917 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3918 spi_sync_immediate);
3919 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3920 spi_sync_immediate);
3921 __spi_pump_messages(ctlr, false);
3924 wait_for_completion(&done);
3925 status = message->status;
3927 message->context = NULL;
3932 * spi_sync - blocking/synchronous SPI data transfers
3933 * @spi: device with which data will be exchanged
3934 * @message: describes the data transfers
3935 * Context: can sleep
3937 * This call may only be used from a context that may sleep. The sleep
3938 * is non-interruptible, and has no timeout. Low-overhead controller
3939 * drivers may DMA directly into and out of the message buffers.
3941 * Note that the SPI device's chip select is active during the message,
3942 * and then is normally disabled between messages. Drivers for some
3943 * frequently-used devices may want to minimize costs of selecting a chip,
3944 * by leaving it selected in anticipation that the next message will go
3945 * to the same chip. (That may increase power usage.)
3947 * Also, the caller is guaranteeing that the memory associated with the
3948 * message will not be freed before this call returns.
3950 * Return: zero on success, else a negative error code.
3952 int spi_sync(struct spi_device *spi, struct spi_message *message)
3956 mutex_lock(&spi->controller->bus_lock_mutex);
3957 ret = __spi_sync(spi, message);
3958 mutex_unlock(&spi->controller->bus_lock_mutex);
3962 EXPORT_SYMBOL_GPL(spi_sync);
3965 * spi_sync_locked - version of spi_sync with exclusive bus usage
3966 * @spi: device with which data will be exchanged
3967 * @message: describes the data transfers
3968 * Context: can sleep
3970 * This call may only be used from a context that may sleep. The sleep
3971 * is non-interruptible, and has no timeout. Low-overhead controller
3972 * drivers may DMA directly into and out of the message buffers.
3974 * This call should be used by drivers that require exclusive access to the
3975 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3976 * be released by a spi_bus_unlock call when the exclusive access is over.
3978 * Return: zero on success, else a negative error code.
3980 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3982 return __spi_sync(spi, message);
3984 EXPORT_SYMBOL_GPL(spi_sync_locked);
3987 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3988 * @ctlr: SPI bus master that should be locked for exclusive bus access
3989 * Context: can sleep
3991 * This call may only be used from a context that may sleep. The sleep
3992 * is non-interruptible, and has no timeout.
3994 * This call should be used by drivers that require exclusive access to the
3995 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3996 * exclusive access is over. Data transfer must be done by spi_sync_locked
3997 * and spi_async_locked calls when the SPI bus lock is held.
3999 * Return: always zero.
4001 int spi_bus_lock(struct spi_controller *ctlr)
4003 unsigned long flags;
4005 mutex_lock(&ctlr->bus_lock_mutex);
4007 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4008 ctlr->bus_lock_flag = 1;
4009 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4011 /* mutex remains locked until spi_bus_unlock is called */
4015 EXPORT_SYMBOL_GPL(spi_bus_lock);
4018 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4019 * @ctlr: SPI bus master that was locked for exclusive bus access
4020 * Context: can sleep
4022 * This call may only be used from a context that may sleep. The sleep
4023 * is non-interruptible, and has no timeout.
4025 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4028 * Return: always zero.
4030 int spi_bus_unlock(struct spi_controller *ctlr)
4032 ctlr->bus_lock_flag = 0;
4034 mutex_unlock(&ctlr->bus_lock_mutex);
4038 EXPORT_SYMBOL_GPL(spi_bus_unlock);
4040 /* portable code must never pass more than 32 bytes */
4041 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4046 * spi_write_then_read - SPI synchronous write followed by read
4047 * @spi: device with which data will be exchanged
4048 * @txbuf: data to be written (need not be dma-safe)
4049 * @n_tx: size of txbuf, in bytes
4050 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4051 * @n_rx: size of rxbuf, in bytes
4052 * Context: can sleep
4054 * This performs a half duplex MicroWire style transaction with the
4055 * device, sending txbuf and then reading rxbuf. The return value
4056 * is zero for success, else a negative errno status code.
4057 * This call may only be used from a context that may sleep.
4059 * Parameters to this routine are always copied using a small buffer.
4060 * Performance-sensitive or bulk transfer code should instead use
4061 * spi_{async,sync}() calls with dma-safe buffers.
4063 * Return: zero on success, else a negative error code.
4065 int spi_write_then_read(struct spi_device *spi,
4066 const void *txbuf, unsigned n_tx,
4067 void *rxbuf, unsigned n_rx)
4069 static DEFINE_MUTEX(lock);
4072 struct spi_message message;
4073 struct spi_transfer x[2];
4076 /* Use preallocated DMA-safe buffer if we can. We can't avoid
4077 * copying here, (as a pure convenience thing), but we can
4078 * keep heap costs out of the hot path unless someone else is
4079 * using the pre-allocated buffer or the transfer is too large.
4081 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4082 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4083 GFP_KERNEL | GFP_DMA);
4090 spi_message_init(&message);
4091 memset(x, 0, sizeof(x));
4094 spi_message_add_tail(&x[0], &message);
4098 spi_message_add_tail(&x[1], &message);
4101 memcpy(local_buf, txbuf, n_tx);
4102 x[0].tx_buf = local_buf;
4103 x[1].rx_buf = local_buf + n_tx;
4106 status = spi_sync(spi, &message);
4108 memcpy(rxbuf, x[1].rx_buf, n_rx);
4110 if (x[0].tx_buf == buf)
4111 mutex_unlock(&lock);
4117 EXPORT_SYMBOL_GPL(spi_write_then_read);
4119 /*-------------------------------------------------------------------------*/
4121 #if IS_ENABLED(CONFIG_OF)
4122 /* must call put_device() when done with returned spi_device device */
4123 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4125 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4127 return dev ? to_spi_device(dev) : NULL;
4129 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4130 #endif /* IS_ENABLED(CONFIG_OF) */
4132 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4133 /* the spi controllers are not using spi_bus, so we find it with another way */
4134 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4138 dev = class_find_device_by_of_node(&spi_master_class, node);
4139 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4140 dev = class_find_device_by_of_node(&spi_slave_class, node);
4144 /* reference got in class_find_device */
4145 return container_of(dev, struct spi_controller, dev);
4148 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4151 struct of_reconfig_data *rd = arg;
4152 struct spi_controller *ctlr;
4153 struct spi_device *spi;
4155 switch (of_reconfig_get_state_change(action, arg)) {
4156 case OF_RECONFIG_CHANGE_ADD:
4157 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4159 return NOTIFY_OK; /* not for us */
4161 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4162 put_device(&ctlr->dev);
4166 spi = of_register_spi_device(ctlr, rd->dn);
4167 put_device(&ctlr->dev);
4170 pr_err("%s: failed to create for '%pOF'\n",
4172 of_node_clear_flag(rd->dn, OF_POPULATED);
4173 return notifier_from_errno(PTR_ERR(spi));
4177 case OF_RECONFIG_CHANGE_REMOVE:
4178 /* already depopulated? */
4179 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4182 /* find our device by node */
4183 spi = of_find_spi_device_by_node(rd->dn);
4185 return NOTIFY_OK; /* no? not meant for us */
4187 /* unregister takes one ref away */
4188 spi_unregister_device(spi);
4190 /* and put the reference of the find */
4191 put_device(&spi->dev);
4198 static struct notifier_block spi_of_notifier = {
4199 .notifier_call = of_spi_notify,
4201 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4202 extern struct notifier_block spi_of_notifier;
4203 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4205 #if IS_ENABLED(CONFIG_ACPI)
4206 static int spi_acpi_controller_match(struct device *dev, const void *data)
4208 return ACPI_COMPANION(dev->parent) == data;
4211 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4215 dev = class_find_device(&spi_master_class, NULL, adev,
4216 spi_acpi_controller_match);
4217 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4218 dev = class_find_device(&spi_slave_class, NULL, adev,
4219 spi_acpi_controller_match);
4223 return container_of(dev, struct spi_controller, dev);
4226 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4230 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4231 return to_spi_device(dev);
4234 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4237 struct acpi_device *adev = arg;
4238 struct spi_controller *ctlr;
4239 struct spi_device *spi;
4242 case ACPI_RECONFIG_DEVICE_ADD:
4243 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4247 acpi_register_spi_device(ctlr, adev);
4248 put_device(&ctlr->dev);
4250 case ACPI_RECONFIG_DEVICE_REMOVE:
4251 if (!acpi_device_enumerated(adev))
4254 spi = acpi_spi_find_device_by_adev(adev);
4258 spi_unregister_device(spi);
4259 put_device(&spi->dev);
4266 static struct notifier_block spi_acpi_notifier = {
4267 .notifier_call = acpi_spi_notify,
4270 extern struct notifier_block spi_acpi_notifier;
4273 static int __init spi_init(void)
4277 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4283 status = bus_register(&spi_bus_type);
4287 status = class_register(&spi_master_class);
4291 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4292 status = class_register(&spi_slave_class);
4297 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4298 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4299 if (IS_ENABLED(CONFIG_ACPI))
4300 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4305 class_unregister(&spi_master_class);
4307 bus_unregister(&spi_bus_type);
4315 /* board_info is normally registered in arch_initcall(),
4316 * but even essential drivers wait till later
4318 * REVISIT only boardinfo really needs static linking. the rest (device and
4319 * driver registration) _could_ be dynamically linked (modular) ... costs
4320 * include needing to have boardinfo data structures be much more public.
4322 postcore_initcall(spi_init);