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 = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
65 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
67 static DEVICE_ATTR_RO(modalias);
69 static ssize_t driver_override_store(struct device *dev,
70 struct device_attribute *a,
71 const char *buf, size_t count)
73 struct spi_device *spi = to_spi_device(dev);
74 const char *end = memchr(buf, '\n', count);
75 const size_t len = end ? end - buf : count;
76 const char *driver_override, *old;
78 /* We need to keep extra room for a newline when displaying value */
79 if (len >= (PAGE_SIZE - 1))
82 driver_override = kstrndup(buf, len, GFP_KERNEL);
87 old = spi->driver_override;
89 spi->driver_override = driver_override;
91 /* Empty string, disable driver override */
92 spi->driver_override = NULL;
93 kfree(driver_override);
101 static ssize_t driver_override_show(struct device *dev,
102 struct device_attribute *a, char *buf)
104 const struct spi_device *spi = to_spi_device(dev);
108 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
112 static DEVICE_ATTR_RW(driver_override);
114 #define SPI_STATISTICS_ATTRS(field, file) \
115 static ssize_t spi_controller_##field##_show(struct device *dev, \
116 struct device_attribute *attr, \
119 struct spi_controller *ctlr = container_of(dev, \
120 struct spi_controller, dev); \
121 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
123 static struct device_attribute dev_attr_spi_controller_##field = { \
124 .attr = { .name = file, .mode = 0444 }, \
125 .show = spi_controller_##field##_show, \
127 static ssize_t spi_device_##field##_show(struct device *dev, \
128 struct device_attribute *attr, \
131 struct spi_device *spi = to_spi_device(dev); \
132 return spi_statistics_##field##_show(&spi->statistics, buf); \
134 static struct device_attribute dev_attr_spi_device_##field = { \
135 .attr = { .name = file, .mode = 0444 }, \
136 .show = spi_device_##field##_show, \
139 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
140 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
143 unsigned long flags; \
145 spin_lock_irqsave(&stat->lock, flags); \
146 len = sprintf(buf, format_string, stat->field); \
147 spin_unlock_irqrestore(&stat->lock, flags); \
150 SPI_STATISTICS_ATTRS(name, file)
152 #define SPI_STATISTICS_SHOW(field, format_string) \
153 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
154 field, format_string)
156 SPI_STATISTICS_SHOW(messages, "%lu");
157 SPI_STATISTICS_SHOW(transfers, "%lu");
158 SPI_STATISTICS_SHOW(errors, "%lu");
159 SPI_STATISTICS_SHOW(timedout, "%lu");
161 SPI_STATISTICS_SHOW(spi_sync, "%lu");
162 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
163 SPI_STATISTICS_SHOW(spi_async, "%lu");
165 SPI_STATISTICS_SHOW(bytes, "%llu");
166 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
167 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
169 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
170 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
171 "transfer_bytes_histo_" number, \
172 transfer_bytes_histo[index], "%lu")
173 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
174 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
175 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
176 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
191 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
193 static struct attribute *spi_dev_attrs[] = {
194 &dev_attr_modalias.attr,
195 &dev_attr_driver_override.attr,
199 static const struct attribute_group spi_dev_group = {
200 .attrs = spi_dev_attrs,
203 static struct attribute *spi_device_statistics_attrs[] = {
204 &dev_attr_spi_device_messages.attr,
205 &dev_attr_spi_device_transfers.attr,
206 &dev_attr_spi_device_errors.attr,
207 &dev_attr_spi_device_timedout.attr,
208 &dev_attr_spi_device_spi_sync.attr,
209 &dev_attr_spi_device_spi_sync_immediate.attr,
210 &dev_attr_spi_device_spi_async.attr,
211 &dev_attr_spi_device_bytes.attr,
212 &dev_attr_spi_device_bytes_rx.attr,
213 &dev_attr_spi_device_bytes_tx.attr,
214 &dev_attr_spi_device_transfer_bytes_histo0.attr,
215 &dev_attr_spi_device_transfer_bytes_histo1.attr,
216 &dev_attr_spi_device_transfer_bytes_histo2.attr,
217 &dev_attr_spi_device_transfer_bytes_histo3.attr,
218 &dev_attr_spi_device_transfer_bytes_histo4.attr,
219 &dev_attr_spi_device_transfer_bytes_histo5.attr,
220 &dev_attr_spi_device_transfer_bytes_histo6.attr,
221 &dev_attr_spi_device_transfer_bytes_histo7.attr,
222 &dev_attr_spi_device_transfer_bytes_histo8.attr,
223 &dev_attr_spi_device_transfer_bytes_histo9.attr,
224 &dev_attr_spi_device_transfer_bytes_histo10.attr,
225 &dev_attr_spi_device_transfer_bytes_histo11.attr,
226 &dev_attr_spi_device_transfer_bytes_histo12.attr,
227 &dev_attr_spi_device_transfer_bytes_histo13.attr,
228 &dev_attr_spi_device_transfer_bytes_histo14.attr,
229 &dev_attr_spi_device_transfer_bytes_histo15.attr,
230 &dev_attr_spi_device_transfer_bytes_histo16.attr,
231 &dev_attr_spi_device_transfers_split_maxsize.attr,
235 static const struct attribute_group spi_device_statistics_group = {
236 .name = "statistics",
237 .attrs = spi_device_statistics_attrs,
240 static const struct attribute_group *spi_dev_groups[] = {
242 &spi_device_statistics_group,
246 static struct attribute *spi_controller_statistics_attrs[] = {
247 &dev_attr_spi_controller_messages.attr,
248 &dev_attr_spi_controller_transfers.attr,
249 &dev_attr_spi_controller_errors.attr,
250 &dev_attr_spi_controller_timedout.attr,
251 &dev_attr_spi_controller_spi_sync.attr,
252 &dev_attr_spi_controller_spi_sync_immediate.attr,
253 &dev_attr_spi_controller_spi_async.attr,
254 &dev_attr_spi_controller_bytes.attr,
255 &dev_attr_spi_controller_bytes_rx.attr,
256 &dev_attr_spi_controller_bytes_tx.attr,
257 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
258 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
259 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
260 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
274 &dev_attr_spi_controller_transfers_split_maxsize.attr,
278 static const struct attribute_group spi_controller_statistics_group = {
279 .name = "statistics",
280 .attrs = spi_controller_statistics_attrs,
283 static const struct attribute_group *spi_master_groups[] = {
284 &spi_controller_statistics_group,
288 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
289 struct spi_transfer *xfer,
290 struct spi_controller *ctlr)
293 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
298 spin_lock_irqsave(&stats->lock, flags);
301 stats->transfer_bytes_histo[l2len]++;
303 stats->bytes += xfer->len;
304 if ((xfer->tx_buf) &&
305 (xfer->tx_buf != ctlr->dummy_tx))
306 stats->bytes_tx += xfer->len;
307 if ((xfer->rx_buf) &&
308 (xfer->rx_buf != ctlr->dummy_rx))
309 stats->bytes_rx += xfer->len;
311 spin_unlock_irqrestore(&stats->lock, flags);
313 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
315 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
316 * and the sysfs version makes coldplug work too.
319 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
320 const struct spi_device *sdev)
322 while (id->name[0]) {
323 if (!strcmp(sdev->modalias, id->name))
330 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
332 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
334 return spi_match_id(sdrv->id_table, sdev);
336 EXPORT_SYMBOL_GPL(spi_get_device_id);
338 static int spi_match_device(struct device *dev, struct device_driver *drv)
340 const struct spi_device *spi = to_spi_device(dev);
341 const struct spi_driver *sdrv = to_spi_driver(drv);
343 /* Check override first, and if set, only use the named driver */
344 if (spi->driver_override)
345 return strcmp(spi->driver_override, drv->name) == 0;
347 /* Attempt an OF style match */
348 if (of_driver_match_device(dev, drv))
352 if (acpi_driver_match_device(dev, drv))
356 return !!spi_match_id(sdrv->id_table, spi);
358 return strcmp(spi->modalias, drv->name) == 0;
361 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
363 const struct spi_device *spi = to_spi_device(dev);
366 rc = acpi_device_uevent_modalias(dev, env);
370 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
373 static int spi_probe(struct device *dev)
375 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
376 struct spi_device *spi = to_spi_device(dev);
379 ret = of_clk_set_defaults(dev->of_node, false);
384 spi->irq = of_irq_get(dev->of_node, 0);
385 if (spi->irq == -EPROBE_DEFER)
386 return -EPROBE_DEFER;
391 ret = dev_pm_domain_attach(dev, true);
396 ret = sdrv->probe(spi);
398 dev_pm_domain_detach(dev, true);
404 static void spi_remove(struct device *dev)
406 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
411 ret = sdrv->remove(to_spi_device(dev));
414 "Failed to unbind driver (%pe), ignoring\n",
418 dev_pm_domain_detach(dev, true);
421 static void spi_shutdown(struct device *dev)
424 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
427 sdrv->shutdown(to_spi_device(dev));
431 struct bus_type spi_bus_type = {
433 .dev_groups = spi_dev_groups,
434 .match = spi_match_device,
435 .uevent = spi_uevent,
437 .remove = spi_remove,
438 .shutdown = spi_shutdown,
440 EXPORT_SYMBOL_GPL(spi_bus_type);
443 * __spi_register_driver - register a SPI driver
444 * @owner: owner module of the driver to register
445 * @sdrv: the driver to register
448 * Return: zero on success, else a negative error code.
450 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
452 sdrv->driver.owner = owner;
453 sdrv->driver.bus = &spi_bus_type;
456 * For Really Good Reasons we use spi: modaliases not of:
457 * modaliases for DT so module autoloading won't work if we
458 * don't have a spi_device_id as well as a compatible string.
460 if (sdrv->driver.of_match_table) {
461 const struct of_device_id *of_id;
463 for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
467 /* Strip off any vendor prefix */
468 of_name = strnchr(of_id->compatible,
469 sizeof(of_id->compatible), ',');
473 of_name = of_id->compatible;
475 if (sdrv->id_table) {
476 const struct spi_device_id *spi_id;
478 for (spi_id = sdrv->id_table; spi_id->name[0];
480 if (strcmp(spi_id->name, of_name) == 0)
486 if (strcmp(sdrv->driver.name, of_name) == 0)
490 pr_warn("SPI driver %s has no spi_device_id for %s\n",
491 sdrv->driver.name, of_id->compatible);
495 return driver_register(&sdrv->driver);
497 EXPORT_SYMBOL_GPL(__spi_register_driver);
499 /*-------------------------------------------------------------------------*/
501 /* SPI devices should normally not be created by SPI device drivers; that
502 * would make them board-specific. Similarly with SPI controller drivers.
503 * Device registration normally goes into like arch/.../mach.../board-YYY.c
504 * with other readonly (flashable) information about mainboard devices.
508 struct list_head list;
509 struct spi_board_info board_info;
512 static LIST_HEAD(board_list);
513 static LIST_HEAD(spi_controller_list);
516 * Used to protect add/del operation for board_info list and
517 * spi_controller list, and their matching process
518 * also used to protect object of type struct idr
520 static DEFINE_MUTEX(board_lock);
523 * spi_alloc_device - Allocate a new SPI device
524 * @ctlr: Controller to which device is connected
527 * Allows a driver to allocate and initialize a spi_device without
528 * registering it immediately. This allows a driver to directly
529 * fill the spi_device with device parameters before calling
530 * spi_add_device() on it.
532 * Caller is responsible to call spi_add_device() on the returned
533 * spi_device structure to add it to the SPI controller. If the caller
534 * needs to discard the spi_device without adding it, then it should
535 * call spi_dev_put() on it.
537 * Return: a pointer to the new device, or NULL.
539 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
541 struct spi_device *spi;
543 if (!spi_controller_get(ctlr))
546 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
548 spi_controller_put(ctlr);
552 spi->master = spi->controller = ctlr;
553 spi->dev.parent = &ctlr->dev;
554 spi->dev.bus = &spi_bus_type;
555 spi->dev.release = spidev_release;
556 spi->cs_gpio = -ENOENT;
557 spi->mode = ctlr->buswidth_override_bits;
559 spin_lock_init(&spi->statistics.lock);
561 device_initialize(&spi->dev);
564 EXPORT_SYMBOL_GPL(spi_alloc_device);
566 static void spi_dev_set_name(struct spi_device *spi)
568 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
571 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
575 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
579 static int spi_dev_check(struct device *dev, void *data)
581 struct spi_device *spi = to_spi_device(dev);
582 struct spi_device *new_spi = data;
584 if (spi->controller == new_spi->controller &&
585 spi->chip_select == new_spi->chip_select)
590 static void spi_cleanup(struct spi_device *spi)
592 if (spi->controller->cleanup)
593 spi->controller->cleanup(spi);
596 static int __spi_add_device(struct spi_device *spi)
598 struct spi_controller *ctlr = spi->controller;
599 struct device *dev = ctlr->dev.parent;
602 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
604 dev_err(dev, "chipselect %d already in use\n",
609 /* Controller may unregister concurrently */
610 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
611 !device_is_registered(&ctlr->dev)) {
615 /* Descriptors take precedence */
617 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
618 else if (ctlr->cs_gpios)
619 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
621 /* Drivers may modify this initial i/o setup, but will
622 * normally rely on the device being setup. Devices
623 * using SPI_CS_HIGH can't coexist well otherwise...
625 status = spi_setup(spi);
627 dev_err(dev, "can't setup %s, status %d\n",
628 dev_name(&spi->dev), status);
632 /* Device may be bound to an active driver when this returns */
633 status = device_add(&spi->dev);
635 dev_err(dev, "can't add %s, status %d\n",
636 dev_name(&spi->dev), status);
639 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
646 * spi_add_device - Add spi_device allocated with spi_alloc_device
647 * @spi: spi_device to register
649 * Companion function to spi_alloc_device. Devices allocated with
650 * spi_alloc_device can be added onto the spi bus with this function.
652 * Return: 0 on success; negative errno on failure
654 int spi_add_device(struct spi_device *spi)
656 struct spi_controller *ctlr = spi->controller;
657 struct device *dev = ctlr->dev.parent;
660 /* Chipselects are numbered 0..max; validate. */
661 if (spi->chip_select >= ctlr->num_chipselect) {
662 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
663 ctlr->num_chipselect);
667 /* Set the bus ID string */
668 spi_dev_set_name(spi);
670 /* We need to make sure there's no other device with this
671 * chipselect **BEFORE** we call setup(), else we'll trash
672 * its configuration. Lock against concurrent add() calls.
674 mutex_lock(&ctlr->add_lock);
675 status = __spi_add_device(spi);
676 mutex_unlock(&ctlr->add_lock);
679 EXPORT_SYMBOL_GPL(spi_add_device);
681 static int spi_add_device_locked(struct spi_device *spi)
683 struct spi_controller *ctlr = spi->controller;
684 struct device *dev = ctlr->dev.parent;
686 /* Chipselects are numbered 0..max; validate. */
687 if (spi->chip_select >= ctlr->num_chipselect) {
688 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
689 ctlr->num_chipselect);
693 /* Set the bus ID string */
694 spi_dev_set_name(spi);
696 WARN_ON(!mutex_is_locked(&ctlr->add_lock));
697 return __spi_add_device(spi);
701 * spi_new_device - instantiate one new SPI device
702 * @ctlr: Controller to which device is connected
703 * @chip: Describes the SPI device
706 * On typical mainboards, this is purely internal; and it's not needed
707 * after board init creates the hard-wired devices. Some development
708 * platforms may not be able to use spi_register_board_info though, and
709 * this is exported so that for example a USB or parport based adapter
710 * driver could add devices (which it would learn about out-of-band).
712 * Return: the new device, or NULL.
714 struct spi_device *spi_new_device(struct spi_controller *ctlr,
715 struct spi_board_info *chip)
717 struct spi_device *proxy;
720 /* NOTE: caller did any chip->bus_num checks necessary.
722 * Also, unless we change the return value convention to use
723 * error-or-pointer (not NULL-or-pointer), troubleshootability
724 * suggests syslogged diagnostics are best here (ugh).
727 proxy = spi_alloc_device(ctlr);
731 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
733 proxy->chip_select = chip->chip_select;
734 proxy->max_speed_hz = chip->max_speed_hz;
735 proxy->mode = chip->mode;
736 proxy->irq = chip->irq;
737 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
738 proxy->dev.platform_data = (void *) chip->platform_data;
739 proxy->controller_data = chip->controller_data;
740 proxy->controller_state = NULL;
743 status = device_add_software_node(&proxy->dev, chip->swnode);
745 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
746 chip->modalias, status);
751 status = spi_add_device(proxy);
758 device_remove_software_node(&proxy->dev);
762 EXPORT_SYMBOL_GPL(spi_new_device);
765 * spi_unregister_device - unregister a single SPI device
766 * @spi: spi_device to unregister
768 * Start making the passed SPI device vanish. Normally this would be handled
769 * by spi_unregister_controller().
771 void spi_unregister_device(struct spi_device *spi)
776 if (spi->dev.of_node) {
777 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
778 of_node_put(spi->dev.of_node);
780 if (ACPI_COMPANION(&spi->dev))
781 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
782 device_remove_software_node(&spi->dev);
783 device_del(&spi->dev);
785 put_device(&spi->dev);
787 EXPORT_SYMBOL_GPL(spi_unregister_device);
789 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
790 struct spi_board_info *bi)
792 struct spi_device *dev;
794 if (ctlr->bus_num != bi->bus_num)
797 dev = spi_new_device(ctlr, bi);
799 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
804 * spi_register_board_info - register SPI devices for a given board
805 * @info: array of chip descriptors
806 * @n: how many descriptors are provided
809 * Board-specific early init code calls this (probably during arch_initcall)
810 * with segments of the SPI device table. Any device nodes are created later,
811 * after the relevant parent SPI controller (bus_num) is defined. We keep
812 * this table of devices forever, so that reloading a controller driver will
813 * not make Linux forget about these hard-wired devices.
815 * Other code can also call this, e.g. a particular add-on board might provide
816 * SPI devices through its expansion connector, so code initializing that board
817 * would naturally declare its SPI devices.
819 * The board info passed can safely be __initdata ... but be careful of
820 * any embedded pointers (platform_data, etc), they're copied as-is.
822 * Return: zero on success, else a negative error code.
824 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
826 struct boardinfo *bi;
832 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
836 for (i = 0; i < n; i++, bi++, info++) {
837 struct spi_controller *ctlr;
839 memcpy(&bi->board_info, info, sizeof(*info));
841 mutex_lock(&board_lock);
842 list_add_tail(&bi->list, &board_list);
843 list_for_each_entry(ctlr, &spi_controller_list, list)
844 spi_match_controller_to_boardinfo(ctlr,
846 mutex_unlock(&board_lock);
852 /*-------------------------------------------------------------------------*/
854 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
856 bool activate = enable;
859 * Avoid calling into the driver (or doing delays) if the chip select
860 * isn't actually changing from the last time this was called.
862 if (!force && (spi->controller->last_cs_enable == enable) &&
863 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
866 trace_spi_set_cs(spi, activate);
868 spi->controller->last_cs_enable = enable;
869 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
871 if ((spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
872 !spi->controller->set_cs_timing) && !activate) {
873 spi_delay_exec(&spi->cs_hold, NULL);
876 if (spi->mode & SPI_CS_HIGH)
879 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
880 if (!(spi->mode & SPI_NO_CS)) {
883 * Historically ACPI has no means of the GPIO polarity and
884 * thus the SPISerialBus() resource defines it on the per-chip
885 * basis. In order to avoid a chain of negations, the GPIO
886 * polarity is considered being Active High. Even for the cases
887 * when _DSD() is involved (in the updated versions of ACPI)
888 * the GPIO CS polarity must be defined Active High to avoid
889 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
892 if (has_acpi_companion(&spi->dev))
893 gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
895 /* Polarity handled by GPIO library */
896 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
899 * invert the enable line, as active low is
902 gpio_set_value_cansleep(spi->cs_gpio, !enable);
905 /* Some SPI masters need both GPIO CS & slave_select */
906 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
907 spi->controller->set_cs)
908 spi->controller->set_cs(spi, !enable);
909 } else if (spi->controller->set_cs) {
910 spi->controller->set_cs(spi, !enable);
913 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
914 !spi->controller->set_cs_timing) {
916 spi_delay_exec(&spi->cs_setup, NULL);
918 spi_delay_exec(&spi->cs_inactive, NULL);
922 #ifdef CONFIG_HAS_DMA
923 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
924 struct sg_table *sgt, void *buf, size_t len,
925 enum dma_data_direction dir)
927 const bool vmalloced_buf = is_vmalloc_addr(buf);
928 unsigned int max_seg_size = dma_get_max_seg_size(dev);
929 #ifdef CONFIG_HIGHMEM
930 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
931 (unsigned long)buf < (PKMAP_BASE +
932 (LAST_PKMAP * PAGE_SIZE)));
934 const bool kmap_buf = false;
938 struct page *vm_page;
939 struct scatterlist *sg;
944 if (vmalloced_buf || kmap_buf) {
945 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
946 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
947 } else if (virt_addr_valid(buf)) {
948 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
949 sgs = DIV_ROUND_UP(len, desc_len);
954 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
959 for (i = 0; i < sgs; i++) {
961 if (vmalloced_buf || kmap_buf) {
963 * Next scatterlist entry size is the minimum between
964 * the desc_len and the remaining buffer length that
967 min = min_t(size_t, desc_len,
969 PAGE_SIZE - offset_in_page(buf)));
971 vm_page = vmalloc_to_page(buf);
973 vm_page = kmap_to_page(buf);
978 sg_set_page(sg, vm_page,
979 min, offset_in_page(buf));
981 min = min_t(size_t, len, desc_len);
983 sg_set_buf(sg, sg_buf, min);
991 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
1004 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
1005 struct sg_table *sgt, enum dma_data_direction dir)
1007 if (sgt->orig_nents) {
1008 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
1013 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1015 struct device *tx_dev, *rx_dev;
1016 struct spi_transfer *xfer;
1023 tx_dev = ctlr->dma_tx->device->dev;
1024 else if (ctlr->dma_map_dev)
1025 tx_dev = ctlr->dma_map_dev;
1027 tx_dev = ctlr->dev.parent;
1030 rx_dev = ctlr->dma_rx->device->dev;
1031 else if (ctlr->dma_map_dev)
1032 rx_dev = ctlr->dma_map_dev;
1034 rx_dev = ctlr->dev.parent;
1036 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1037 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1040 if (xfer->tx_buf != NULL) {
1041 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
1042 (void *)xfer->tx_buf, xfer->len,
1048 if (xfer->rx_buf != NULL) {
1049 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
1050 xfer->rx_buf, xfer->len,
1053 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
1060 ctlr->cur_msg_mapped = true;
1065 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1067 struct spi_transfer *xfer;
1068 struct device *tx_dev, *rx_dev;
1070 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1074 tx_dev = ctlr->dma_tx->device->dev;
1075 else if (ctlr->dma_map_dev)
1076 tx_dev = ctlr->dma_map_dev;
1078 tx_dev = ctlr->dev.parent;
1081 rx_dev = ctlr->dma_rx->device->dev;
1082 else if (ctlr->dma_map_dev)
1083 rx_dev = ctlr->dma_map_dev;
1085 rx_dev = ctlr->dev.parent;
1087 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1088 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1091 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1092 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1095 ctlr->cur_msg_mapped = false;
1099 #else /* !CONFIG_HAS_DMA */
1100 static inline int __spi_map_msg(struct spi_controller *ctlr,
1101 struct spi_message *msg)
1106 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1107 struct spi_message *msg)
1111 #endif /* !CONFIG_HAS_DMA */
1113 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1114 struct spi_message *msg)
1116 struct spi_transfer *xfer;
1118 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1120 * Restore the original value of tx_buf or rx_buf if they are
1123 if (xfer->tx_buf == ctlr->dummy_tx)
1124 xfer->tx_buf = NULL;
1125 if (xfer->rx_buf == ctlr->dummy_rx)
1126 xfer->rx_buf = NULL;
1129 return __spi_unmap_msg(ctlr, msg);
1132 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1134 struct spi_transfer *xfer;
1136 unsigned int max_tx, max_rx;
1138 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1139 && !(msg->spi->mode & SPI_3WIRE)) {
1143 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1144 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1146 max_tx = max(xfer->len, max_tx);
1147 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1149 max_rx = max(xfer->len, max_rx);
1153 tmp = krealloc(ctlr->dummy_tx, max_tx,
1154 GFP_KERNEL | GFP_DMA);
1157 ctlr->dummy_tx = tmp;
1158 memset(tmp, 0, max_tx);
1162 tmp = krealloc(ctlr->dummy_rx, max_rx,
1163 GFP_KERNEL | GFP_DMA);
1166 ctlr->dummy_rx = tmp;
1169 if (max_tx || max_rx) {
1170 list_for_each_entry(xfer, &msg->transfers,
1175 xfer->tx_buf = ctlr->dummy_tx;
1177 xfer->rx_buf = ctlr->dummy_rx;
1182 return __spi_map_msg(ctlr, msg);
1185 static int spi_transfer_wait(struct spi_controller *ctlr,
1186 struct spi_message *msg,
1187 struct spi_transfer *xfer)
1189 struct spi_statistics *statm = &ctlr->statistics;
1190 struct spi_statistics *stats = &msg->spi->statistics;
1191 u32 speed_hz = xfer->speed_hz;
1192 unsigned long long ms;
1194 if (spi_controller_is_slave(ctlr)) {
1195 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1196 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1204 * For each byte we wait for 8 cycles of the SPI clock.
1205 * Since speed is defined in Hz and we want milliseconds,
1206 * use respective multiplier, but before the division,
1207 * otherwise we may get 0 for short transfers.
1209 ms = 8LL * MSEC_PER_SEC * xfer->len;
1210 do_div(ms, speed_hz);
1213 * Increase it twice and add 200 ms tolerance, use
1214 * predefined maximum in case of overflow.
1220 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1221 msecs_to_jiffies(ms));
1224 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1225 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1226 dev_err(&msg->spi->dev,
1227 "SPI transfer timed out\n");
1235 static void _spi_transfer_delay_ns(u32 ns)
1239 if (ns <= NSEC_PER_USEC) {
1242 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1247 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1251 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1253 u32 delay = _delay->value;
1254 u32 unit = _delay->unit;
1261 case SPI_DELAY_UNIT_USECS:
1262 delay *= NSEC_PER_USEC;
1264 case SPI_DELAY_UNIT_NSECS:
1265 /* Nothing to do here */
1267 case SPI_DELAY_UNIT_SCK:
1268 /* clock cycles need to be obtained from spi_transfer */
1272 * If there is unknown effective speed, approximate it
1273 * by underestimating with half of the requested hz.
1275 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1279 /* Convert delay to nanoseconds */
1280 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1288 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1290 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1299 delay = spi_delay_to_ns(_delay, xfer);
1303 _spi_transfer_delay_ns(delay);
1307 EXPORT_SYMBOL_GPL(spi_delay_exec);
1309 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1310 struct spi_transfer *xfer)
1312 u32 default_delay_ns = 10 * NSEC_PER_USEC;
1313 u32 delay = xfer->cs_change_delay.value;
1314 u32 unit = xfer->cs_change_delay.unit;
1317 /* return early on "fast" mode - for everything but USECS */
1319 if (unit == SPI_DELAY_UNIT_USECS)
1320 _spi_transfer_delay_ns(default_delay_ns);
1324 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1326 dev_err_once(&msg->spi->dev,
1327 "Use of unsupported delay unit %i, using default of %luus\n",
1328 unit, default_delay_ns / NSEC_PER_USEC);
1329 _spi_transfer_delay_ns(default_delay_ns);
1334 * spi_transfer_one_message - Default implementation of transfer_one_message()
1336 * This is a standard implementation of transfer_one_message() for
1337 * drivers which implement a transfer_one() operation. It provides
1338 * standard handling of delays and chip select management.
1340 static int spi_transfer_one_message(struct spi_controller *ctlr,
1341 struct spi_message *msg)
1343 struct spi_transfer *xfer;
1344 bool keep_cs = false;
1346 struct spi_statistics *statm = &ctlr->statistics;
1347 struct spi_statistics *stats = &msg->spi->statistics;
1349 spi_set_cs(msg->spi, true, false);
1351 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1352 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1354 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1355 trace_spi_transfer_start(msg, xfer);
1357 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1358 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1360 if (!ctlr->ptp_sts_supported) {
1361 xfer->ptp_sts_word_pre = 0;
1362 ptp_read_system_prets(xfer->ptp_sts);
1365 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1366 reinit_completion(&ctlr->xfer_completion);
1369 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1371 if (ctlr->cur_msg_mapped &&
1372 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1373 __spi_unmap_msg(ctlr, msg);
1374 ctlr->fallback = true;
1375 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1379 SPI_STATISTICS_INCREMENT_FIELD(statm,
1381 SPI_STATISTICS_INCREMENT_FIELD(stats,
1383 dev_err(&msg->spi->dev,
1384 "SPI transfer failed: %d\n", ret);
1389 ret = spi_transfer_wait(ctlr, msg, xfer);
1395 dev_err(&msg->spi->dev,
1396 "Bufferless transfer has length %u\n",
1400 if (!ctlr->ptp_sts_supported) {
1401 ptp_read_system_postts(xfer->ptp_sts);
1402 xfer->ptp_sts_word_post = xfer->len;
1405 trace_spi_transfer_stop(msg, xfer);
1407 if (msg->status != -EINPROGRESS)
1410 spi_transfer_delay_exec(xfer);
1412 if (xfer->cs_change) {
1413 if (list_is_last(&xfer->transfer_list,
1417 spi_set_cs(msg->spi, false, false);
1418 _spi_transfer_cs_change_delay(msg, xfer);
1419 spi_set_cs(msg->spi, true, false);
1423 msg->actual_length += xfer->len;
1427 if (ret != 0 || !keep_cs)
1428 spi_set_cs(msg->spi, false, false);
1430 if (msg->status == -EINPROGRESS)
1433 if (msg->status && ctlr->handle_err)
1434 ctlr->handle_err(ctlr, msg);
1436 spi_finalize_current_message(ctlr);
1442 * spi_finalize_current_transfer - report completion of a transfer
1443 * @ctlr: the controller reporting completion
1445 * Called by SPI drivers using the core transfer_one_message()
1446 * implementation to notify it that the current interrupt driven
1447 * transfer has finished and the next one may be scheduled.
1449 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1451 complete(&ctlr->xfer_completion);
1453 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1455 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1457 if (ctlr->auto_runtime_pm) {
1458 pm_runtime_mark_last_busy(ctlr->dev.parent);
1459 pm_runtime_put_autosuspend(ctlr->dev.parent);
1464 * __spi_pump_messages - function which processes spi message queue
1465 * @ctlr: controller to process queue for
1466 * @in_kthread: true if we are in the context of the message pump thread
1468 * This function checks if there is any spi message in the queue that
1469 * needs processing and if so call out to the driver to initialize hardware
1470 * and transfer each message.
1472 * Note that it is called both from the kthread itself and also from
1473 * inside spi_sync(); the queue extraction handling at the top of the
1474 * function should deal with this safely.
1476 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1478 struct spi_transfer *xfer;
1479 struct spi_message *msg;
1480 bool was_busy = false;
1481 unsigned long flags;
1485 spin_lock_irqsave(&ctlr->queue_lock, flags);
1487 /* Make sure we are not already running a message */
1488 if (ctlr->cur_msg) {
1489 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1493 /* If another context is idling the device then defer */
1495 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1496 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1500 /* Check if the queue is idle */
1501 if (list_empty(&ctlr->queue) || !ctlr->running) {
1503 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1507 /* Defer any non-atomic teardown to the thread */
1509 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1510 !ctlr->unprepare_transfer_hardware) {
1511 spi_idle_runtime_pm(ctlr);
1513 trace_spi_controller_idle(ctlr);
1515 kthread_queue_work(ctlr->kworker,
1516 &ctlr->pump_messages);
1518 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1523 ctlr->idling = true;
1524 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1526 kfree(ctlr->dummy_rx);
1527 ctlr->dummy_rx = NULL;
1528 kfree(ctlr->dummy_tx);
1529 ctlr->dummy_tx = NULL;
1530 if (ctlr->unprepare_transfer_hardware &&
1531 ctlr->unprepare_transfer_hardware(ctlr))
1533 "failed to unprepare transfer hardware\n");
1534 spi_idle_runtime_pm(ctlr);
1535 trace_spi_controller_idle(ctlr);
1537 spin_lock_irqsave(&ctlr->queue_lock, flags);
1538 ctlr->idling = false;
1539 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1543 /* Extract head of queue */
1544 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1545 ctlr->cur_msg = msg;
1547 list_del_init(&msg->queue);
1552 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1554 mutex_lock(&ctlr->io_mutex);
1556 if (!was_busy && ctlr->auto_runtime_pm) {
1557 ret = pm_runtime_get_sync(ctlr->dev.parent);
1559 pm_runtime_put_noidle(ctlr->dev.parent);
1560 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1562 mutex_unlock(&ctlr->io_mutex);
1568 trace_spi_controller_busy(ctlr);
1570 if (!was_busy && ctlr->prepare_transfer_hardware) {
1571 ret = ctlr->prepare_transfer_hardware(ctlr);
1574 "failed to prepare transfer hardware: %d\n",
1577 if (ctlr->auto_runtime_pm)
1578 pm_runtime_put(ctlr->dev.parent);
1581 spi_finalize_current_message(ctlr);
1583 mutex_unlock(&ctlr->io_mutex);
1588 trace_spi_message_start(msg);
1590 if (ctlr->prepare_message) {
1591 ret = ctlr->prepare_message(ctlr, msg);
1593 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1596 spi_finalize_current_message(ctlr);
1599 ctlr->cur_msg_prepared = true;
1602 ret = spi_map_msg(ctlr, msg);
1605 spi_finalize_current_message(ctlr);
1609 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1610 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1611 xfer->ptp_sts_word_pre = 0;
1612 ptp_read_system_prets(xfer->ptp_sts);
1616 ret = ctlr->transfer_one_message(ctlr, msg);
1619 "failed to transfer one message from queue\n");
1624 mutex_unlock(&ctlr->io_mutex);
1626 /* Prod the scheduler in case transfer_one() was busy waiting */
1632 * spi_pump_messages - kthread work function which processes spi message queue
1633 * @work: pointer to kthread work struct contained in the controller struct
1635 static void spi_pump_messages(struct kthread_work *work)
1637 struct spi_controller *ctlr =
1638 container_of(work, struct spi_controller, pump_messages);
1640 __spi_pump_messages(ctlr, true);
1644 * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1645 * TX timestamp for the requested byte from the SPI
1646 * transfer. The frequency with which this function
1647 * must be called (once per word, once for the whole
1648 * transfer, once per batch of words etc) is arbitrary
1649 * as long as the @tx buffer offset is greater than or
1650 * equal to the requested byte at the time of the
1651 * call. The timestamp is only taken once, at the
1652 * first such call. It is assumed that the driver
1653 * advances its @tx buffer pointer monotonically.
1654 * @ctlr: Pointer to the spi_controller structure of the driver
1655 * @xfer: Pointer to the transfer being timestamped
1656 * @progress: How many words (not bytes) have been transferred so far
1657 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1658 * transfer, for less jitter in time measurement. Only compatible
1659 * with PIO drivers. If true, must follow up with
1660 * spi_take_timestamp_post or otherwise system will crash.
1661 * WARNING: for fully predictable results, the CPU frequency must
1662 * also be under control (governor).
1664 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1665 struct spi_transfer *xfer,
1666 size_t progress, bool irqs_off)
1671 if (xfer->timestamped)
1674 if (progress > xfer->ptp_sts_word_pre)
1677 /* Capture the resolution of the timestamp */
1678 xfer->ptp_sts_word_pre = progress;
1681 local_irq_save(ctlr->irq_flags);
1685 ptp_read_system_prets(xfer->ptp_sts);
1687 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1690 * spi_take_timestamp_post - helper for drivers to collect the end of the
1691 * TX timestamp for the requested byte from the SPI
1692 * transfer. Can be called with an arbitrary
1693 * frequency: only the first call where @tx exceeds
1694 * or is equal to the requested word will be
1696 * @ctlr: Pointer to the spi_controller structure of the driver
1697 * @xfer: Pointer to the transfer being timestamped
1698 * @progress: How many words (not bytes) have been transferred so far
1699 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1701 void spi_take_timestamp_post(struct spi_controller *ctlr,
1702 struct spi_transfer *xfer,
1703 size_t progress, bool irqs_off)
1708 if (xfer->timestamped)
1711 if (progress < xfer->ptp_sts_word_post)
1714 ptp_read_system_postts(xfer->ptp_sts);
1717 local_irq_restore(ctlr->irq_flags);
1721 /* Capture the resolution of the timestamp */
1722 xfer->ptp_sts_word_post = progress;
1724 xfer->timestamped = true;
1726 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1729 * spi_set_thread_rt - set the controller to pump at realtime priority
1730 * @ctlr: controller to boost priority of
1732 * This can be called because the controller requested realtime priority
1733 * (by setting the ->rt value before calling spi_register_controller()) or
1734 * because a device on the bus said that its transfers needed realtime
1737 * NOTE: at the moment if any device on a bus says it needs realtime then
1738 * the thread will be at realtime priority for all transfers on that
1739 * controller. If this eventually becomes a problem we may see if we can
1740 * find a way to boost the priority only temporarily during relevant
1743 static void spi_set_thread_rt(struct spi_controller *ctlr)
1745 dev_info(&ctlr->dev,
1746 "will run message pump with realtime priority\n");
1747 sched_set_fifo(ctlr->kworker->task);
1750 static int spi_init_queue(struct spi_controller *ctlr)
1752 ctlr->running = false;
1755 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1756 if (IS_ERR(ctlr->kworker)) {
1757 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1758 return PTR_ERR(ctlr->kworker);
1761 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1764 * Controller config will indicate if this controller should run the
1765 * message pump with high (realtime) priority to reduce the transfer
1766 * latency on the bus by minimising the delay between a transfer
1767 * request and the scheduling of the message pump thread. Without this
1768 * setting the message pump thread will remain at default priority.
1771 spi_set_thread_rt(ctlr);
1777 * spi_get_next_queued_message() - called by driver to check for queued
1779 * @ctlr: the controller to check for queued messages
1781 * If there are more messages in the queue, the next message is returned from
1784 * Return: the next message in the queue, else NULL if the queue is empty.
1786 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1788 struct spi_message *next;
1789 unsigned long flags;
1791 /* get a pointer to the next message, if any */
1792 spin_lock_irqsave(&ctlr->queue_lock, flags);
1793 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1795 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1799 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1802 * spi_finalize_current_message() - the current message is complete
1803 * @ctlr: the controller to return the message to
1805 * Called by the driver to notify the core that the message in the front of the
1806 * queue is complete and can be removed from the queue.
1808 void spi_finalize_current_message(struct spi_controller *ctlr)
1810 struct spi_transfer *xfer;
1811 struct spi_message *mesg;
1812 unsigned long flags;
1815 spin_lock_irqsave(&ctlr->queue_lock, flags);
1816 mesg = ctlr->cur_msg;
1817 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1819 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1820 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1821 ptp_read_system_postts(xfer->ptp_sts);
1822 xfer->ptp_sts_word_post = xfer->len;
1826 if (unlikely(ctlr->ptp_sts_supported))
1827 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1828 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1830 spi_unmap_msg(ctlr, mesg);
1832 /* In the prepare_messages callback the spi bus has the opportunity to
1833 * split a transfer to smaller chunks.
1834 * Release splited transfers here since spi_map_msg is done on the
1835 * splited transfers.
1837 spi_res_release(ctlr, mesg);
1839 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1840 ret = ctlr->unprepare_message(ctlr, mesg);
1842 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1847 spin_lock_irqsave(&ctlr->queue_lock, flags);
1848 ctlr->cur_msg = NULL;
1849 ctlr->cur_msg_prepared = false;
1850 ctlr->fallback = false;
1851 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1852 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1854 trace_spi_message_done(mesg);
1858 mesg->complete(mesg->context);
1860 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1862 static int spi_start_queue(struct spi_controller *ctlr)
1864 unsigned long flags;
1866 spin_lock_irqsave(&ctlr->queue_lock, flags);
1868 if (ctlr->running || ctlr->busy) {
1869 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1873 ctlr->running = true;
1874 ctlr->cur_msg = NULL;
1875 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1877 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1882 static int spi_stop_queue(struct spi_controller *ctlr)
1884 unsigned long flags;
1885 unsigned limit = 500;
1888 spin_lock_irqsave(&ctlr->queue_lock, flags);
1891 * This is a bit lame, but is optimized for the common execution path.
1892 * A wait_queue on the ctlr->busy could be used, but then the common
1893 * execution path (pump_messages) would be required to call wake_up or
1894 * friends on every SPI message. Do this instead.
1896 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1897 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1898 usleep_range(10000, 11000);
1899 spin_lock_irqsave(&ctlr->queue_lock, flags);
1902 if (!list_empty(&ctlr->queue) || ctlr->busy)
1905 ctlr->running = false;
1907 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1910 dev_warn(&ctlr->dev, "could not stop message queue\n");
1916 static int spi_destroy_queue(struct spi_controller *ctlr)
1920 ret = spi_stop_queue(ctlr);
1923 * kthread_flush_worker will block until all work is done.
1924 * If the reason that stop_queue timed out is that the work will never
1925 * finish, then it does no good to call flush/stop thread, so
1929 dev_err(&ctlr->dev, "problem destroying queue\n");
1933 kthread_destroy_worker(ctlr->kworker);
1938 static int __spi_queued_transfer(struct spi_device *spi,
1939 struct spi_message *msg,
1942 struct spi_controller *ctlr = spi->controller;
1943 unsigned long flags;
1945 spin_lock_irqsave(&ctlr->queue_lock, flags);
1947 if (!ctlr->running) {
1948 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1951 msg->actual_length = 0;
1952 msg->status = -EINPROGRESS;
1954 list_add_tail(&msg->queue, &ctlr->queue);
1955 if (!ctlr->busy && need_pump)
1956 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1958 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1963 * spi_queued_transfer - transfer function for queued transfers
1964 * @spi: spi device which is requesting transfer
1965 * @msg: spi message which is to handled is queued to driver queue
1967 * Return: zero on success, else a negative error code.
1969 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1971 return __spi_queued_transfer(spi, msg, true);
1974 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1978 ctlr->transfer = spi_queued_transfer;
1979 if (!ctlr->transfer_one_message)
1980 ctlr->transfer_one_message = spi_transfer_one_message;
1982 /* Initialize and start queue */
1983 ret = spi_init_queue(ctlr);
1985 dev_err(&ctlr->dev, "problem initializing queue\n");
1986 goto err_init_queue;
1988 ctlr->queued = true;
1989 ret = spi_start_queue(ctlr);
1991 dev_err(&ctlr->dev, "problem starting queue\n");
1992 goto err_start_queue;
1998 spi_destroy_queue(ctlr);
2004 * spi_flush_queue - Send all pending messages in the queue from the callers'
2006 * @ctlr: controller to process queue for
2008 * This should be used when one wants to ensure all pending messages have been
2009 * sent before doing something. Is used by the spi-mem code to make sure SPI
2010 * memory operations do not preempt regular SPI transfers that have been queued
2011 * before the spi-mem operation.
2013 void spi_flush_queue(struct spi_controller *ctlr)
2015 if (ctlr->transfer == spi_queued_transfer)
2016 __spi_pump_messages(ctlr, false);
2019 /*-------------------------------------------------------------------------*/
2021 #if defined(CONFIG_OF)
2022 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2023 struct device_node *nc)
2028 /* Mode (clock phase/polarity/etc.) */
2029 if (of_property_read_bool(nc, "spi-cpha"))
2030 spi->mode |= SPI_CPHA;
2031 if (of_property_read_bool(nc, "spi-cpol"))
2032 spi->mode |= SPI_CPOL;
2033 if (of_property_read_bool(nc, "spi-3wire"))
2034 spi->mode |= SPI_3WIRE;
2035 if (of_property_read_bool(nc, "spi-lsb-first"))
2036 spi->mode |= SPI_LSB_FIRST;
2037 if (of_property_read_bool(nc, "spi-cs-high"))
2038 spi->mode |= SPI_CS_HIGH;
2040 /* Device DUAL/QUAD mode */
2041 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2044 spi->mode |= SPI_NO_TX;
2049 spi->mode |= SPI_TX_DUAL;
2052 spi->mode |= SPI_TX_QUAD;
2055 spi->mode |= SPI_TX_OCTAL;
2058 dev_warn(&ctlr->dev,
2059 "spi-tx-bus-width %d not supported\n",
2065 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2068 spi->mode |= SPI_NO_RX;
2073 spi->mode |= SPI_RX_DUAL;
2076 spi->mode |= SPI_RX_QUAD;
2079 spi->mode |= SPI_RX_OCTAL;
2082 dev_warn(&ctlr->dev,
2083 "spi-rx-bus-width %d not supported\n",
2089 if (spi_controller_is_slave(ctlr)) {
2090 if (!of_node_name_eq(nc, "slave")) {
2091 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2098 /* Device address */
2099 rc = of_property_read_u32(nc, "reg", &value);
2101 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2105 spi->chip_select = value;
2108 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2109 spi->max_speed_hz = value;
2114 static struct spi_device *
2115 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2117 struct spi_device *spi;
2120 /* Alloc an spi_device */
2121 spi = spi_alloc_device(ctlr);
2123 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2128 /* Select device driver */
2129 rc = of_modalias_node(nc, spi->modalias,
2130 sizeof(spi->modalias));
2132 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2136 rc = of_spi_parse_dt(ctlr, spi, nc);
2140 /* Store a pointer to the node in the device structure */
2142 spi->dev.of_node = nc;
2143 spi->dev.fwnode = of_fwnode_handle(nc);
2145 /* Register the new device */
2146 rc = spi_add_device(spi);
2148 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2149 goto err_of_node_put;
2162 * of_register_spi_devices() - Register child devices onto the SPI bus
2163 * @ctlr: Pointer to spi_controller device
2165 * Registers an spi_device for each child node of controller node which
2166 * represents a valid SPI slave.
2168 static void of_register_spi_devices(struct spi_controller *ctlr)
2170 struct spi_device *spi;
2171 struct device_node *nc;
2173 if (!ctlr->dev.of_node)
2176 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2177 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2179 spi = of_register_spi_device(ctlr, nc);
2181 dev_warn(&ctlr->dev,
2182 "Failed to create SPI device for %pOF\n", nc);
2183 of_node_clear_flag(nc, OF_POPULATED);
2188 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2192 * spi_new_ancillary_device() - Register ancillary SPI device
2193 * @spi: Pointer to the main SPI device registering the ancillary device
2194 * @chip_select: Chip Select of the ancillary device
2196 * Register an ancillary SPI device; for example some chips have a chip-select
2197 * for normal device usage and another one for setup/firmware upload.
2199 * This may only be called from main SPI device's probe routine.
2201 * Return: 0 on success; negative errno on failure
2203 struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2206 struct spi_device *ancillary;
2209 /* Alloc an spi_device */
2210 ancillary = spi_alloc_device(spi->controller);
2216 strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2218 /* Use provided chip-select for ancillary device */
2219 ancillary->chip_select = chip_select;
2221 /* Take over SPI mode/speed from SPI main device */
2222 ancillary->max_speed_hz = spi->max_speed_hz;
2223 ancillary->mode = spi->mode;
2225 /* Register the new device */
2226 rc = spi_add_device_locked(ancillary);
2228 dev_err(&spi->dev, "failed to register ancillary device\n");
2235 spi_dev_put(ancillary);
2238 EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2241 struct acpi_spi_lookup {
2242 struct spi_controller *ctlr;
2250 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2251 struct acpi_spi_lookup *lookup)
2253 const union acpi_object *obj;
2255 if (!x86_apple_machine)
2258 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2259 && obj->buffer.length >= 4)
2260 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2262 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2263 && obj->buffer.length == 8)
2264 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2266 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2267 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2268 lookup->mode |= SPI_LSB_FIRST;
2270 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2271 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2272 lookup->mode |= SPI_CPOL;
2274 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2275 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2276 lookup->mode |= SPI_CPHA;
2279 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2281 struct acpi_spi_lookup *lookup = data;
2282 struct spi_controller *ctlr = lookup->ctlr;
2284 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2285 struct acpi_resource_spi_serialbus *sb;
2286 acpi_handle parent_handle;
2289 sb = &ares->data.spi_serial_bus;
2290 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2292 status = acpi_get_handle(NULL,
2293 sb->resource_source.string_ptr,
2296 if (ACPI_FAILURE(status) ||
2297 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2301 * ACPI DeviceSelection numbering is handled by the
2302 * host controller driver in Windows and can vary
2303 * from driver to driver. In Linux we always expect
2304 * 0 .. max - 1 so we need to ask the driver to
2305 * translate between the two schemes.
2307 if (ctlr->fw_translate_cs) {
2308 int cs = ctlr->fw_translate_cs(ctlr,
2309 sb->device_selection);
2312 lookup->chip_select = cs;
2314 lookup->chip_select = sb->device_selection;
2317 lookup->max_speed_hz = sb->connection_speed;
2318 lookup->bits_per_word = sb->data_bit_length;
2320 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2321 lookup->mode |= SPI_CPHA;
2322 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2323 lookup->mode |= SPI_CPOL;
2324 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2325 lookup->mode |= SPI_CS_HIGH;
2327 } else if (lookup->irq < 0) {
2330 if (acpi_dev_resource_interrupt(ares, 0, &r))
2331 lookup->irq = r.start;
2334 /* Always tell the ACPI core to skip this resource */
2338 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2339 struct acpi_device *adev)
2341 acpi_handle parent_handle = NULL;
2342 struct list_head resource_list;
2343 struct acpi_spi_lookup lookup = {};
2344 struct spi_device *spi;
2347 if (acpi_bus_get_status(adev) || !adev->status.present ||
2348 acpi_device_enumerated(adev))
2354 INIT_LIST_HEAD(&resource_list);
2355 ret = acpi_dev_get_resources(adev, &resource_list,
2356 acpi_spi_add_resource, &lookup);
2357 acpi_dev_free_resource_list(&resource_list);
2360 /* found SPI in _CRS but it points to another controller */
2363 if (!lookup.max_speed_hz &&
2364 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2365 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2366 /* Apple does not use _CRS but nested devices for SPI slaves */
2367 acpi_spi_parse_apple_properties(adev, &lookup);
2370 if (!lookup.max_speed_hz)
2373 spi = spi_alloc_device(ctlr);
2375 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2376 dev_name(&adev->dev));
2377 return AE_NO_MEMORY;
2381 ACPI_COMPANION_SET(&spi->dev, adev);
2382 spi->max_speed_hz = lookup.max_speed_hz;
2383 spi->mode |= lookup.mode;
2384 spi->irq = lookup.irq;
2385 spi->bits_per_word = lookup.bits_per_word;
2386 spi->chip_select = lookup.chip_select;
2388 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2389 sizeof(spi->modalias));
2392 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2394 acpi_device_set_enumerated(adev);
2396 adev->power.flags.ignore_parent = true;
2397 if (spi_add_device(spi)) {
2398 adev->power.flags.ignore_parent = false;
2399 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2400 dev_name(&adev->dev));
2407 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2408 void *data, void **return_value)
2410 struct spi_controller *ctlr = data;
2411 struct acpi_device *adev;
2413 if (acpi_bus_get_device(handle, &adev))
2416 return acpi_register_spi_device(ctlr, adev);
2419 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2421 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2426 handle = ACPI_HANDLE(ctlr->dev.parent);
2430 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2431 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2432 acpi_spi_add_device, NULL, ctlr, NULL);
2433 if (ACPI_FAILURE(status))
2434 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2437 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2438 #endif /* CONFIG_ACPI */
2440 static void spi_controller_release(struct device *dev)
2442 struct spi_controller *ctlr;
2444 ctlr = container_of(dev, struct spi_controller, dev);
2448 static struct class spi_master_class = {
2449 .name = "spi_master",
2450 .owner = THIS_MODULE,
2451 .dev_release = spi_controller_release,
2452 .dev_groups = spi_master_groups,
2455 #ifdef CONFIG_SPI_SLAVE
2457 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2459 * @spi: device used for the current transfer
2461 int spi_slave_abort(struct spi_device *spi)
2463 struct spi_controller *ctlr = spi->controller;
2465 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2466 return ctlr->slave_abort(ctlr);
2470 EXPORT_SYMBOL_GPL(spi_slave_abort);
2472 static int match_true(struct device *dev, void *data)
2477 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2480 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2482 struct device *child;
2484 child = device_find_child(&ctlr->dev, NULL, match_true);
2485 return sprintf(buf, "%s\n",
2486 child ? to_spi_device(child)->modalias : NULL);
2489 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2490 const char *buf, size_t count)
2492 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2494 struct spi_device *spi;
2495 struct device *child;
2499 rc = sscanf(buf, "%31s", name);
2500 if (rc != 1 || !name[0])
2503 child = device_find_child(&ctlr->dev, NULL, match_true);
2505 /* Remove registered slave */
2506 device_unregister(child);
2510 if (strcmp(name, "(null)")) {
2511 /* Register new slave */
2512 spi = spi_alloc_device(ctlr);
2516 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2518 rc = spi_add_device(spi);
2528 static DEVICE_ATTR_RW(slave);
2530 static struct attribute *spi_slave_attrs[] = {
2531 &dev_attr_slave.attr,
2535 static const struct attribute_group spi_slave_group = {
2536 .attrs = spi_slave_attrs,
2539 static const struct attribute_group *spi_slave_groups[] = {
2540 &spi_controller_statistics_group,
2545 static struct class spi_slave_class = {
2546 .name = "spi_slave",
2547 .owner = THIS_MODULE,
2548 .dev_release = spi_controller_release,
2549 .dev_groups = spi_slave_groups,
2552 extern struct class spi_slave_class; /* dummy */
2556 * __spi_alloc_controller - allocate an SPI master or slave controller
2557 * @dev: the controller, possibly using the platform_bus
2558 * @size: how much zeroed driver-private data to allocate; the pointer to this
2559 * memory is in the driver_data field of the returned device, accessible
2560 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2561 * drivers granting DMA access to portions of their private data need to
2562 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2563 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2564 * slave (true) controller
2565 * Context: can sleep
2567 * This call is used only by SPI controller drivers, which are the
2568 * only ones directly touching chip registers. It's how they allocate
2569 * an spi_controller structure, prior to calling spi_register_controller().
2571 * This must be called from context that can sleep.
2573 * The caller is responsible for assigning the bus number and initializing the
2574 * controller's methods before calling spi_register_controller(); and (after
2575 * errors adding the device) calling spi_controller_put() to prevent a memory
2578 * Return: the SPI controller structure on success, else NULL.
2580 struct spi_controller *__spi_alloc_controller(struct device *dev,
2581 unsigned int size, bool slave)
2583 struct spi_controller *ctlr;
2584 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2589 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2593 device_initialize(&ctlr->dev);
2594 INIT_LIST_HEAD(&ctlr->queue);
2595 spin_lock_init(&ctlr->queue_lock);
2596 spin_lock_init(&ctlr->bus_lock_spinlock);
2597 mutex_init(&ctlr->bus_lock_mutex);
2598 mutex_init(&ctlr->io_mutex);
2599 mutex_init(&ctlr->add_lock);
2601 ctlr->num_chipselect = 1;
2602 ctlr->slave = slave;
2603 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2604 ctlr->dev.class = &spi_slave_class;
2606 ctlr->dev.class = &spi_master_class;
2607 ctlr->dev.parent = dev;
2608 pm_suspend_ignore_children(&ctlr->dev, true);
2609 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2613 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2615 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2617 spi_controller_put(*(struct spi_controller **)ctlr);
2621 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2622 * @dev: physical device of SPI controller
2623 * @size: how much zeroed driver-private data to allocate
2624 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2625 * Context: can sleep
2627 * Allocate an SPI controller and automatically release a reference on it
2628 * when @dev is unbound from its driver. Drivers are thus relieved from
2629 * having to call spi_controller_put().
2631 * The arguments to this function are identical to __spi_alloc_controller().
2633 * Return: the SPI controller structure on success, else NULL.
2635 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2639 struct spi_controller **ptr, *ctlr;
2641 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2646 ctlr = __spi_alloc_controller(dev, size, slave);
2648 ctlr->devm_allocated = true;
2650 devres_add(dev, ptr);
2657 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2660 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2663 struct device_node *np = ctlr->dev.of_node;
2668 nb = of_gpio_named_count(np, "cs-gpios");
2669 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2671 /* Return error only for an incorrectly formed cs-gpios property */
2672 if (nb == 0 || nb == -ENOENT)
2677 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2679 ctlr->cs_gpios = cs;
2681 if (!ctlr->cs_gpios)
2684 for (i = 0; i < ctlr->num_chipselect; i++)
2687 for (i = 0; i < nb; i++)
2688 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2693 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2700 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2701 * @ctlr: The SPI master to grab GPIO descriptors for
2703 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2706 struct gpio_desc **cs;
2707 struct device *dev = &ctlr->dev;
2708 unsigned long native_cs_mask = 0;
2709 unsigned int num_cs_gpios = 0;
2711 nb = gpiod_count(dev, "cs");
2713 /* No GPIOs at all is fine, else return the error */
2719 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2721 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2725 ctlr->cs_gpiods = cs;
2727 for (i = 0; i < nb; i++) {
2729 * Most chipselects are active low, the inverted
2730 * semantics are handled by special quirks in gpiolib,
2731 * so initializing them GPIOD_OUT_LOW here means
2732 * "unasserted", in most cases this will drive the physical
2735 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2738 return PTR_ERR(cs[i]);
2742 * If we find a CS GPIO, name it after the device and
2747 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2751 gpiod_set_consumer_name(cs[i], gpioname);
2756 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2757 dev_err(dev, "Invalid native chip select %d\n", i);
2760 native_cs_mask |= BIT(i);
2763 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2765 if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2766 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2767 dev_err(dev, "No unused native chip select available\n");
2774 static int spi_controller_check_ops(struct spi_controller *ctlr)
2777 * The controller may implement only the high-level SPI-memory like
2778 * operations if it does not support regular SPI transfers, and this is
2780 * If ->mem_ops is NULL, we request that at least one of the
2781 * ->transfer_xxx() method be implemented.
2783 if (ctlr->mem_ops) {
2784 if (!ctlr->mem_ops->exec_op)
2786 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2787 !ctlr->transfer_one_message) {
2795 * spi_register_controller - register SPI master or slave controller
2796 * @ctlr: initialized master, originally from spi_alloc_master() or
2798 * Context: can sleep
2800 * SPI controllers connect to their drivers using some non-SPI bus,
2801 * such as the platform bus. The final stage of probe() in that code
2802 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2804 * SPI controllers use board specific (often SOC specific) bus numbers,
2805 * and board-specific addressing for SPI devices combines those numbers
2806 * with chip select numbers. Since SPI does not directly support dynamic
2807 * device identification, boards need configuration tables telling which
2808 * chip is at which address.
2810 * This must be called from context that can sleep. It returns zero on
2811 * success, else a negative error code (dropping the controller's refcount).
2812 * After a successful return, the caller is responsible for calling
2813 * spi_unregister_controller().
2815 * Return: zero on success, else a negative error code.
2817 int spi_register_controller(struct spi_controller *ctlr)
2819 struct device *dev = ctlr->dev.parent;
2820 struct boardinfo *bi;
2822 int id, first_dynamic;
2828 * Make sure all necessary hooks are implemented before registering
2829 * the SPI controller.
2831 status = spi_controller_check_ops(ctlr);
2835 if (ctlr->bus_num >= 0) {
2836 /* devices with a fixed bus num must check-in with the num */
2837 mutex_lock(&board_lock);
2838 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2839 ctlr->bus_num + 1, GFP_KERNEL);
2840 mutex_unlock(&board_lock);
2841 if (WARN(id < 0, "couldn't get idr"))
2842 return id == -ENOSPC ? -EBUSY : id;
2844 } else if (ctlr->dev.of_node) {
2845 /* allocate dynamic bus number using Linux idr */
2846 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2849 mutex_lock(&board_lock);
2850 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2851 ctlr->bus_num + 1, GFP_KERNEL);
2852 mutex_unlock(&board_lock);
2853 if (WARN(id < 0, "couldn't get idr"))
2854 return id == -ENOSPC ? -EBUSY : id;
2857 if (ctlr->bus_num < 0) {
2858 first_dynamic = of_alias_get_highest_id("spi");
2859 if (first_dynamic < 0)
2864 mutex_lock(&board_lock);
2865 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2867 mutex_unlock(&board_lock);
2868 if (WARN(id < 0, "couldn't get idr"))
2872 ctlr->bus_lock_flag = 0;
2873 init_completion(&ctlr->xfer_completion);
2874 if (!ctlr->max_dma_len)
2875 ctlr->max_dma_len = INT_MAX;
2877 /* register the device, then userspace will see it.
2878 * registration fails if the bus ID is in use.
2880 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2882 if (!spi_controller_is_slave(ctlr)) {
2883 if (ctlr->use_gpio_descriptors) {
2884 status = spi_get_gpio_descs(ctlr);
2888 * A controller using GPIO descriptors always
2889 * supports SPI_CS_HIGH if need be.
2891 ctlr->mode_bits |= SPI_CS_HIGH;
2893 /* Legacy code path for GPIOs from DT */
2894 status = of_spi_get_gpio_numbers(ctlr);
2901 * Even if it's just one always-selected device, there must
2902 * be at least one chipselect.
2904 if (!ctlr->num_chipselect) {
2909 status = device_add(&ctlr->dev);
2912 dev_dbg(dev, "registered %s %s\n",
2913 spi_controller_is_slave(ctlr) ? "slave" : "master",
2914 dev_name(&ctlr->dev));
2917 * If we're using a queued driver, start the queue. Note that we don't
2918 * need the queueing logic if the driver is only supporting high-level
2919 * memory operations.
2921 if (ctlr->transfer) {
2922 dev_info(dev, "controller is unqueued, this is deprecated\n");
2923 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2924 status = spi_controller_initialize_queue(ctlr);
2926 device_del(&ctlr->dev);
2930 /* add statistics */
2931 spin_lock_init(&ctlr->statistics.lock);
2933 mutex_lock(&board_lock);
2934 list_add_tail(&ctlr->list, &spi_controller_list);
2935 list_for_each_entry(bi, &board_list, list)
2936 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2937 mutex_unlock(&board_lock);
2939 /* Register devices from the device tree and ACPI */
2940 of_register_spi_devices(ctlr);
2941 acpi_register_spi_devices(ctlr);
2945 mutex_lock(&board_lock);
2946 idr_remove(&spi_master_idr, ctlr->bus_num);
2947 mutex_unlock(&board_lock);
2950 EXPORT_SYMBOL_GPL(spi_register_controller);
2952 static void devm_spi_unregister(void *ctlr)
2954 spi_unregister_controller(ctlr);
2958 * devm_spi_register_controller - register managed SPI master or slave
2960 * @dev: device managing SPI controller
2961 * @ctlr: initialized controller, originally from spi_alloc_master() or
2963 * Context: can sleep
2965 * Register a SPI device as with spi_register_controller() which will
2966 * automatically be unregistered and freed.
2968 * Return: zero on success, else a negative error code.
2970 int devm_spi_register_controller(struct device *dev,
2971 struct spi_controller *ctlr)
2975 ret = spi_register_controller(ctlr);
2979 return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
2981 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2983 static int __unregister(struct device *dev, void *null)
2985 spi_unregister_device(to_spi_device(dev));
2990 * spi_unregister_controller - unregister SPI master or slave controller
2991 * @ctlr: the controller being unregistered
2992 * Context: can sleep
2994 * This call is used only by SPI controller drivers, which are the
2995 * only ones directly touching chip registers.
2997 * This must be called from context that can sleep.
2999 * Note that this function also drops a reference to the controller.
3001 void spi_unregister_controller(struct spi_controller *ctlr)
3003 struct spi_controller *found;
3004 int id = ctlr->bus_num;
3006 /* Prevent addition of new devices, unregister existing ones */
3007 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3008 mutex_lock(&ctlr->add_lock);
3010 device_for_each_child(&ctlr->dev, NULL, __unregister);
3012 /* First make sure that this controller was ever added */
3013 mutex_lock(&board_lock);
3014 found = idr_find(&spi_master_idr, id);
3015 mutex_unlock(&board_lock);
3017 if (spi_destroy_queue(ctlr))
3018 dev_err(&ctlr->dev, "queue remove failed\n");
3020 mutex_lock(&board_lock);
3021 list_del(&ctlr->list);
3022 mutex_unlock(&board_lock);
3024 device_del(&ctlr->dev);
3027 mutex_lock(&board_lock);
3029 idr_remove(&spi_master_idr, id);
3030 mutex_unlock(&board_lock);
3032 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3033 mutex_unlock(&ctlr->add_lock);
3035 /* Release the last reference on the controller if its driver
3036 * has not yet been converted to devm_spi_alloc_master/slave().
3038 if (!ctlr->devm_allocated)
3039 put_device(&ctlr->dev);
3041 EXPORT_SYMBOL_GPL(spi_unregister_controller);
3043 int spi_controller_suspend(struct spi_controller *ctlr)
3047 /* Basically no-ops for non-queued controllers */
3051 ret = spi_stop_queue(ctlr);
3053 dev_err(&ctlr->dev, "queue stop failed\n");
3057 EXPORT_SYMBOL_GPL(spi_controller_suspend);
3059 int spi_controller_resume(struct spi_controller *ctlr)
3066 ret = spi_start_queue(ctlr);
3068 dev_err(&ctlr->dev, "queue restart failed\n");
3072 EXPORT_SYMBOL_GPL(spi_controller_resume);
3074 static int __spi_controller_match(struct device *dev, const void *data)
3076 struct spi_controller *ctlr;
3077 const u16 *bus_num = data;
3079 ctlr = container_of(dev, struct spi_controller, dev);
3080 return ctlr->bus_num == *bus_num;
3084 * spi_busnum_to_master - look up master associated with bus_num
3085 * @bus_num: the master's bus number
3086 * Context: can sleep
3088 * This call may be used with devices that are registered after
3089 * arch init time. It returns a refcounted pointer to the relevant
3090 * spi_controller (which the caller must release), or NULL if there is
3091 * no such master registered.
3093 * Return: the SPI master structure on success, else NULL.
3095 struct spi_controller *spi_busnum_to_master(u16 bus_num)
3098 struct spi_controller *ctlr = NULL;
3100 dev = class_find_device(&spi_master_class, NULL, &bus_num,
3101 __spi_controller_match);
3103 ctlr = container_of(dev, struct spi_controller, dev);
3104 /* reference got in class_find_device */
3107 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
3109 /*-------------------------------------------------------------------------*/
3111 /* Core methods for SPI resource management */
3114 * spi_res_alloc - allocate a spi resource that is life-cycle managed
3115 * during the processing of a spi_message while using
3117 * @spi: the spi device for which we allocate memory
3118 * @release: the release code to execute for this resource
3119 * @size: size to alloc and return
3120 * @gfp: GFP allocation flags
3122 * Return: the pointer to the allocated data
3124 * This may get enhanced in the future to allocate from a memory pool
3125 * of the @spi_device or @spi_controller to avoid repeated allocations.
3127 void *spi_res_alloc(struct spi_device *spi,
3128 spi_res_release_t release,
3129 size_t size, gfp_t gfp)
3131 struct spi_res *sres;
3133 sres = kzalloc(sizeof(*sres) + size, gfp);
3137 INIT_LIST_HEAD(&sres->entry);
3138 sres->release = release;
3142 EXPORT_SYMBOL_GPL(spi_res_alloc);
3145 * spi_res_free - free an spi resource
3146 * @res: pointer to the custom data of a resource
3149 void spi_res_free(void *res)
3151 struct spi_res *sres = container_of(res, struct spi_res, data);
3156 WARN_ON(!list_empty(&sres->entry));
3159 EXPORT_SYMBOL_GPL(spi_res_free);
3162 * spi_res_add - add a spi_res to the spi_message
3163 * @message: the spi message
3164 * @res: the spi_resource
3166 void spi_res_add(struct spi_message *message, void *res)
3168 struct spi_res *sres = container_of(res, struct spi_res, data);
3170 WARN_ON(!list_empty(&sres->entry));
3171 list_add_tail(&sres->entry, &message->resources);
3173 EXPORT_SYMBOL_GPL(spi_res_add);
3176 * spi_res_release - release all spi resources for this message
3177 * @ctlr: the @spi_controller
3178 * @message: the @spi_message
3180 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3182 struct spi_res *res, *tmp;
3184 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3186 res->release(ctlr, message, res->data);
3188 list_del(&res->entry);
3193 EXPORT_SYMBOL_GPL(spi_res_release);
3195 /*-------------------------------------------------------------------------*/
3197 /* Core methods for spi_message alterations */
3199 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3200 struct spi_message *msg,
3203 struct spi_replaced_transfers *rxfer = res;
3206 /* call extra callback if requested */
3208 rxfer->release(ctlr, msg, res);
3210 /* insert replaced transfers back into the message */
3211 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3213 /* remove the formerly inserted entries */
3214 for (i = 0; i < rxfer->inserted; i++)
3215 list_del(&rxfer->inserted_transfers[i].transfer_list);
3219 * spi_replace_transfers - replace transfers with several transfers
3220 * and register change with spi_message.resources
3221 * @msg: the spi_message we work upon
3222 * @xfer_first: the first spi_transfer we want to replace
3223 * @remove: number of transfers to remove
3224 * @insert: the number of transfers we want to insert instead
3225 * @release: extra release code necessary in some circumstances
3226 * @extradatasize: extra data to allocate (with alignment guarantees
3227 * of struct @spi_transfer)
3230 * Returns: pointer to @spi_replaced_transfers,
3231 * PTR_ERR(...) in case of errors.
3233 struct spi_replaced_transfers *spi_replace_transfers(
3234 struct spi_message *msg,
3235 struct spi_transfer *xfer_first,
3238 spi_replaced_release_t release,
3239 size_t extradatasize,
3242 struct spi_replaced_transfers *rxfer;
3243 struct spi_transfer *xfer;
3246 /* allocate the structure using spi_res */
3247 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3248 struct_size(rxfer, inserted_transfers, insert)
3252 return ERR_PTR(-ENOMEM);
3254 /* the release code to invoke before running the generic release */
3255 rxfer->release = release;
3257 /* assign extradata */
3260 &rxfer->inserted_transfers[insert];
3262 /* init the replaced_transfers list */
3263 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3265 /* assign the list_entry after which we should reinsert
3266 * the @replaced_transfers - it may be spi_message.messages!
3268 rxfer->replaced_after = xfer_first->transfer_list.prev;
3270 /* remove the requested number of transfers */
3271 for (i = 0; i < remove; i++) {
3272 /* if the entry after replaced_after it is msg->transfers
3273 * then we have been requested to remove more transfers
3274 * than are in the list
3276 if (rxfer->replaced_after->next == &msg->transfers) {
3277 dev_err(&msg->spi->dev,
3278 "requested to remove more spi_transfers than are available\n");
3279 /* insert replaced transfers back into the message */
3280 list_splice(&rxfer->replaced_transfers,
3281 rxfer->replaced_after);
3283 /* free the spi_replace_transfer structure */
3284 spi_res_free(rxfer);
3286 /* and return with an error */
3287 return ERR_PTR(-EINVAL);
3290 /* remove the entry after replaced_after from list of
3291 * transfers and add it to list of replaced_transfers
3293 list_move_tail(rxfer->replaced_after->next,
3294 &rxfer->replaced_transfers);
3297 /* create copy of the given xfer with identical settings
3298 * based on the first transfer to get removed
3300 for (i = 0; i < insert; i++) {
3301 /* we need to run in reverse order */
3302 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3304 /* copy all spi_transfer data */
3305 memcpy(xfer, xfer_first, sizeof(*xfer));
3308 list_add(&xfer->transfer_list, rxfer->replaced_after);
3310 /* clear cs_change and delay for all but the last */
3312 xfer->cs_change = false;
3313 xfer->delay.value = 0;
3317 /* set up inserted */
3318 rxfer->inserted = insert;
3320 /* and register it with spi_res/spi_message */
3321 spi_res_add(msg, rxfer);
3325 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3327 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3328 struct spi_message *msg,
3329 struct spi_transfer **xferp,
3333 struct spi_transfer *xfer = *xferp, *xfers;
3334 struct spi_replaced_transfers *srt;
3338 /* calculate how many we have to replace */
3339 count = DIV_ROUND_UP(xfer->len, maxsize);
3341 /* create replacement */
3342 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3344 return PTR_ERR(srt);
3345 xfers = srt->inserted_transfers;
3347 /* now handle each of those newly inserted spi_transfers
3348 * note that the replacements spi_transfers all are preset
3349 * to the same values as *xferp, so tx_buf, rx_buf and len
3350 * are all identical (as well as most others)
3351 * so we just have to fix up len and the pointers.
3353 * this also includes support for the depreciated
3354 * spi_message.is_dma_mapped interface
3357 /* the first transfer just needs the length modified, so we
3358 * run it outside the loop
3360 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3362 /* all the others need rx_buf/tx_buf also set */
3363 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3364 /* update rx_buf, tx_buf and dma */
3365 if (xfers[i].rx_buf)
3366 xfers[i].rx_buf += offset;
3367 if (xfers[i].rx_dma)
3368 xfers[i].rx_dma += offset;
3369 if (xfers[i].tx_buf)
3370 xfers[i].tx_buf += offset;
3371 if (xfers[i].tx_dma)
3372 xfers[i].tx_dma += offset;
3375 xfers[i].len = min(maxsize, xfers[i].len - offset);
3378 /* we set up xferp to the last entry we have inserted,
3379 * so that we skip those already split transfers
3381 *xferp = &xfers[count - 1];
3383 /* increment statistics counters */
3384 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3385 transfers_split_maxsize);
3386 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3387 transfers_split_maxsize);
3393 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3394 * when an individual transfer exceeds a
3396 * @ctlr: the @spi_controller for this transfer
3397 * @msg: the @spi_message to transform
3398 * @maxsize: the maximum when to apply this
3399 * @gfp: GFP allocation flags
3401 * Return: status of transformation
3403 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3404 struct spi_message *msg,
3408 struct spi_transfer *xfer;
3411 /* iterate over the transfer_list,
3412 * but note that xfer is advanced to the last transfer inserted
3413 * to avoid checking sizes again unnecessarily (also xfer does
3414 * potentiall belong to a different list by the time the
3415 * replacement has happened
3417 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3418 if (xfer->len > maxsize) {
3419 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3428 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3430 /*-------------------------------------------------------------------------*/
3432 /* Core methods for SPI controller protocol drivers. Some of the
3433 * other core methods are currently defined as inline functions.
3436 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3439 if (ctlr->bits_per_word_mask) {
3440 /* Only 32 bits fit in the mask */
3441 if (bits_per_word > 32)
3443 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3451 * spi_setup - setup SPI mode and clock rate
3452 * @spi: the device whose settings are being modified
3453 * Context: can sleep, and no requests are queued to the device
3455 * SPI protocol drivers may need to update the transfer mode if the
3456 * device doesn't work with its default. They may likewise need
3457 * to update clock rates or word sizes from initial values. This function
3458 * changes those settings, and must be called from a context that can sleep.
3459 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3460 * effect the next time the device is selected and data is transferred to
3461 * or from it. When this function returns, the spi device is deselected.
3463 * Note that this call will fail if the protocol driver specifies an option
3464 * that the underlying controller or its driver does not support. For
3465 * example, not all hardware supports wire transfers using nine bit words,
3466 * LSB-first wire encoding, or active-high chipselects.
3468 * Return: zero on success, else a negative error code.
3470 int spi_setup(struct spi_device *spi)
3472 struct spi_controller *ctlr = spi->controller;
3473 unsigned bad_bits, ugly_bits;
3477 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3478 * are set at the same time
3480 if ((hweight_long(spi->mode &
3481 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3482 (hweight_long(spi->mode &
3483 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3485 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3488 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3490 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3491 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3492 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3495 if (ctlr->use_gpio_descriptors && ctlr->cs_gpiods &&
3496 ctlr->cs_gpiods[spi->chip_select] && !(spi->mode & SPI_CS_HIGH)) {
3498 "setup: forcing CS_HIGH (use_gpio_descriptors)\n");
3499 spi->mode |= SPI_CS_HIGH;
3502 /* help drivers fail *cleanly* when they need options
3503 * that aren't supported with their current controller
3504 * SPI_CS_WORD has a fallback software implementation,
3505 * so it is ignored here.
3507 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3508 SPI_NO_TX | SPI_NO_RX);
3509 /* nothing prevents from working with active-high CS in case if it
3510 * is driven by GPIO.
3512 if (gpio_is_valid(spi->cs_gpio))
3513 bad_bits &= ~SPI_CS_HIGH;
3514 ugly_bits = bad_bits &
3515 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3516 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3519 "setup: ignoring unsupported mode bits %x\n",
3521 spi->mode &= ~ugly_bits;
3522 bad_bits &= ~ugly_bits;
3525 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3530 if (!spi->bits_per_word)
3531 spi->bits_per_word = 8;
3533 status = __spi_validate_bits_per_word(spi->controller,
3534 spi->bits_per_word);
3538 if (spi->controller->max_speed_hz &&
3539 (!spi->max_speed_hz ||
3540 spi->max_speed_hz > spi->controller->max_speed_hz))
3541 spi->max_speed_hz = spi->controller->max_speed_hz;
3543 mutex_lock(&spi->controller->io_mutex);
3545 if (spi->controller->setup) {
3546 status = spi->controller->setup(spi);
3548 mutex_unlock(&spi->controller->io_mutex);
3549 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3555 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3556 status = pm_runtime_get_sync(spi->controller->dev.parent);
3558 mutex_unlock(&spi->controller->io_mutex);
3559 pm_runtime_put_noidle(spi->controller->dev.parent);
3560 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3566 * We do not want to return positive value from pm_runtime_get,
3567 * there are many instances of devices calling spi_setup() and
3568 * checking for a non-zero return value instead of a negative
3573 spi_set_cs(spi, false, true);
3574 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3575 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3577 spi_set_cs(spi, false, true);
3580 mutex_unlock(&spi->controller->io_mutex);
3582 if (spi->rt && !spi->controller->rt) {
3583 spi->controller->rt = true;
3584 spi_set_thread_rt(spi->controller);
3587 trace_spi_setup(spi, status);
3589 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3590 spi->mode & SPI_MODE_X_MASK,
3591 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3592 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3593 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3594 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3595 spi->bits_per_word, spi->max_speed_hz,
3600 EXPORT_SYMBOL_GPL(spi_setup);
3602 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3603 struct spi_device *spi)
3607 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3611 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3615 if (delay1 < delay2)
3616 memcpy(&xfer->word_delay, &spi->word_delay,
3617 sizeof(xfer->word_delay));
3622 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3624 struct spi_controller *ctlr = spi->controller;
3625 struct spi_transfer *xfer;
3628 if (list_empty(&message->transfers))
3631 /* If an SPI controller does not support toggling the CS line on each
3632 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3633 * for the CS line, we can emulate the CS-per-word hardware function by
3634 * splitting transfers into one-word transfers and ensuring that
3635 * cs_change is set for each transfer.
3637 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3639 gpio_is_valid(spi->cs_gpio))) {
3643 maxsize = (spi->bits_per_word + 7) / 8;
3645 /* spi_split_transfers_maxsize() requires message->spi */
3648 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3653 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3654 /* don't change cs_change on the last entry in the list */
3655 if (list_is_last(&xfer->transfer_list, &message->transfers))
3657 xfer->cs_change = 1;
3661 /* Half-duplex links include original MicroWire, and ones with
3662 * only one data pin like SPI_3WIRE (switches direction) or where
3663 * either MOSI or MISO is missing. They can also be caused by
3664 * software limitations.
3666 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3667 (spi->mode & SPI_3WIRE)) {
3668 unsigned flags = ctlr->flags;
3670 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3671 if (xfer->rx_buf && xfer->tx_buf)
3673 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3675 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3681 * Set transfer bits_per_word and max speed as spi device default if
3682 * it is not set for this transfer.
3683 * Set transfer tx_nbits and rx_nbits as single transfer default
3684 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3685 * Ensure transfer word_delay is at least as long as that required by
3688 message->frame_length = 0;
3689 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3690 xfer->effective_speed_hz = 0;
3691 message->frame_length += xfer->len;
3692 if (!xfer->bits_per_word)
3693 xfer->bits_per_word = spi->bits_per_word;
3695 if (!xfer->speed_hz)
3696 xfer->speed_hz = spi->max_speed_hz;
3698 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3699 xfer->speed_hz = ctlr->max_speed_hz;
3701 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3705 * SPI transfer length should be multiple of SPI word size
3706 * where SPI word size should be power-of-two multiple
3708 if (xfer->bits_per_word <= 8)
3710 else if (xfer->bits_per_word <= 16)
3715 /* No partial transfers accepted */
3716 if (xfer->len % w_size)
3719 if (xfer->speed_hz && ctlr->min_speed_hz &&
3720 xfer->speed_hz < ctlr->min_speed_hz)
3723 if (xfer->tx_buf && !xfer->tx_nbits)
3724 xfer->tx_nbits = SPI_NBITS_SINGLE;
3725 if (xfer->rx_buf && !xfer->rx_nbits)
3726 xfer->rx_nbits = SPI_NBITS_SINGLE;
3727 /* check transfer tx/rx_nbits:
3728 * 1. check the value matches one of single, dual and quad
3729 * 2. check tx/rx_nbits match the mode in spi_device
3732 if (spi->mode & SPI_NO_TX)
3734 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3735 xfer->tx_nbits != SPI_NBITS_DUAL &&
3736 xfer->tx_nbits != SPI_NBITS_QUAD)
3738 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3739 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3741 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3742 !(spi->mode & SPI_TX_QUAD))
3745 /* check transfer rx_nbits */
3747 if (spi->mode & SPI_NO_RX)
3749 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3750 xfer->rx_nbits != SPI_NBITS_DUAL &&
3751 xfer->rx_nbits != SPI_NBITS_QUAD)
3753 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3754 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3756 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3757 !(spi->mode & SPI_RX_QUAD))
3761 if (_spi_xfer_word_delay_update(xfer, spi))
3765 message->status = -EINPROGRESS;
3770 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3772 struct spi_controller *ctlr = spi->controller;
3773 struct spi_transfer *xfer;
3776 * Some controllers do not support doing regular SPI transfers. Return
3777 * ENOTSUPP when this is the case.
3779 if (!ctlr->transfer)
3784 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3785 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3787 trace_spi_message_submit(message);
3789 if (!ctlr->ptp_sts_supported) {
3790 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3791 xfer->ptp_sts_word_pre = 0;
3792 ptp_read_system_prets(xfer->ptp_sts);
3796 return ctlr->transfer(spi, message);
3800 * spi_async - asynchronous SPI transfer
3801 * @spi: device with which data will be exchanged
3802 * @message: describes the data transfers, including completion callback
3803 * Context: any (irqs may be blocked, etc)
3805 * This call may be used in_irq and other contexts which can't sleep,
3806 * as well as from task contexts which can sleep.
3808 * The completion callback is invoked in a context which can't sleep.
3809 * Before that invocation, the value of message->status is undefined.
3810 * When the callback is issued, message->status holds either zero (to
3811 * indicate complete success) or a negative error code. After that
3812 * callback returns, the driver which issued the transfer request may
3813 * deallocate the associated memory; it's no longer in use by any SPI
3814 * core or controller driver code.
3816 * Note that although all messages to a spi_device are handled in
3817 * FIFO order, messages may go to different devices in other orders.
3818 * Some device might be higher priority, or have various "hard" access
3819 * time requirements, for example.
3821 * On detection of any fault during the transfer, processing of
3822 * the entire message is aborted, and the device is deselected.
3823 * Until returning from the associated message completion callback,
3824 * no other spi_message queued to that device will be processed.
3825 * (This rule applies equally to all the synchronous transfer calls,
3826 * which are wrappers around this core asynchronous primitive.)
3828 * Return: zero on success, else a negative error code.
3830 int spi_async(struct spi_device *spi, struct spi_message *message)
3832 struct spi_controller *ctlr = spi->controller;
3834 unsigned long flags;
3836 ret = __spi_validate(spi, message);
3840 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3842 if (ctlr->bus_lock_flag)
3845 ret = __spi_async(spi, message);
3847 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3851 EXPORT_SYMBOL_GPL(spi_async);
3854 * spi_async_locked - version of spi_async with exclusive bus usage
3855 * @spi: device with which data will be exchanged
3856 * @message: describes the data transfers, including completion callback
3857 * Context: any (irqs may be blocked, etc)
3859 * This call may be used in_irq and other contexts which can't sleep,
3860 * as well as from task contexts which can sleep.
3862 * The completion callback is invoked in a context which can't sleep.
3863 * Before that invocation, the value of message->status is undefined.
3864 * When the callback is issued, message->status holds either zero (to
3865 * indicate complete success) or a negative error code. After that
3866 * callback returns, the driver which issued the transfer request may
3867 * deallocate the associated memory; it's no longer in use by any SPI
3868 * core or controller driver code.
3870 * Note that although all messages to a spi_device are handled in
3871 * FIFO order, messages may go to different devices in other orders.
3872 * Some device might be higher priority, or have various "hard" access
3873 * time requirements, for example.
3875 * On detection of any fault during the transfer, processing of
3876 * the entire message is aborted, and the device is deselected.
3877 * Until returning from the associated message completion callback,
3878 * no other spi_message queued to that device will be processed.
3879 * (This rule applies equally to all the synchronous transfer calls,
3880 * which are wrappers around this core asynchronous primitive.)
3882 * Return: zero on success, else a negative error code.
3884 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3886 struct spi_controller *ctlr = spi->controller;
3888 unsigned long flags;
3890 ret = __spi_validate(spi, message);
3894 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3896 ret = __spi_async(spi, message);
3898 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3903 EXPORT_SYMBOL_GPL(spi_async_locked);
3905 /*-------------------------------------------------------------------------*/
3907 /* Utility methods for SPI protocol drivers, layered on
3908 * top of the core. Some other utility methods are defined as
3912 static void spi_complete(void *arg)
3917 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3919 DECLARE_COMPLETION_ONSTACK(done);
3921 struct spi_controller *ctlr = spi->controller;
3922 unsigned long flags;
3924 status = __spi_validate(spi, message);
3928 message->complete = spi_complete;
3929 message->context = &done;
3932 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3933 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3935 /* If we're not using the legacy transfer method then we will
3936 * try to transfer in the calling context so special case.
3937 * This code would be less tricky if we could remove the
3938 * support for driver implemented message queues.
3940 if (ctlr->transfer == spi_queued_transfer) {
3941 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3943 trace_spi_message_submit(message);
3945 status = __spi_queued_transfer(spi, message, false);
3947 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3949 status = spi_async_locked(spi, message);
3953 /* Push out the messages in the calling context if we
3956 if (ctlr->transfer == spi_queued_transfer) {
3957 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3958 spi_sync_immediate);
3959 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3960 spi_sync_immediate);
3961 __spi_pump_messages(ctlr, false);
3964 wait_for_completion(&done);
3965 status = message->status;
3967 message->context = NULL;
3972 * spi_sync - blocking/synchronous SPI data transfers
3973 * @spi: device with which data will be exchanged
3974 * @message: describes the data transfers
3975 * Context: can sleep
3977 * This call may only be used from a context that may sleep. The sleep
3978 * is non-interruptible, and has no timeout. Low-overhead controller
3979 * drivers may DMA directly into and out of the message buffers.
3981 * Note that the SPI device's chip select is active during the message,
3982 * and then is normally disabled between messages. Drivers for some
3983 * frequently-used devices may want to minimize costs of selecting a chip,
3984 * by leaving it selected in anticipation that the next message will go
3985 * to the same chip. (That may increase power usage.)
3987 * Also, the caller is guaranteeing that the memory associated with the
3988 * message will not be freed before this call returns.
3990 * Return: zero on success, else a negative error code.
3992 int spi_sync(struct spi_device *spi, struct spi_message *message)
3996 mutex_lock(&spi->controller->bus_lock_mutex);
3997 ret = __spi_sync(spi, message);
3998 mutex_unlock(&spi->controller->bus_lock_mutex);
4002 EXPORT_SYMBOL_GPL(spi_sync);
4005 * spi_sync_locked - version of spi_sync with exclusive bus usage
4006 * @spi: device with which data will be exchanged
4007 * @message: describes the data transfers
4008 * Context: can sleep
4010 * This call may only be used from a context that may sleep. The sleep
4011 * is non-interruptible, and has no timeout. Low-overhead controller
4012 * drivers may DMA directly into and out of the message buffers.
4014 * This call should be used by drivers that require exclusive access to the
4015 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4016 * be released by a spi_bus_unlock call when the exclusive access is over.
4018 * Return: zero on success, else a negative error code.
4020 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4022 return __spi_sync(spi, message);
4024 EXPORT_SYMBOL_GPL(spi_sync_locked);
4027 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
4028 * @ctlr: SPI bus master that should be locked for exclusive bus access
4029 * Context: can sleep
4031 * This call may only be used from a context that may sleep. The sleep
4032 * is non-interruptible, and has no timeout.
4034 * This call should be used by drivers that require exclusive access to the
4035 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4036 * exclusive access is over. Data transfer must be done by spi_sync_locked
4037 * and spi_async_locked calls when the SPI bus lock is held.
4039 * Return: always zero.
4041 int spi_bus_lock(struct spi_controller *ctlr)
4043 unsigned long flags;
4045 mutex_lock(&ctlr->bus_lock_mutex);
4047 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4048 ctlr->bus_lock_flag = 1;
4049 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4051 /* mutex remains locked until spi_bus_unlock is called */
4055 EXPORT_SYMBOL_GPL(spi_bus_lock);
4058 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4059 * @ctlr: SPI bus master that was locked for exclusive bus access
4060 * Context: can sleep
4062 * This call may only be used from a context that may sleep. The sleep
4063 * is non-interruptible, and has no timeout.
4065 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4068 * Return: always zero.
4070 int spi_bus_unlock(struct spi_controller *ctlr)
4072 ctlr->bus_lock_flag = 0;
4074 mutex_unlock(&ctlr->bus_lock_mutex);
4078 EXPORT_SYMBOL_GPL(spi_bus_unlock);
4080 /* portable code must never pass more than 32 bytes */
4081 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4086 * spi_write_then_read - SPI synchronous write followed by read
4087 * @spi: device with which data will be exchanged
4088 * @txbuf: data to be written (need not be dma-safe)
4089 * @n_tx: size of txbuf, in bytes
4090 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4091 * @n_rx: size of rxbuf, in bytes
4092 * Context: can sleep
4094 * This performs a half duplex MicroWire style transaction with the
4095 * device, sending txbuf and then reading rxbuf. The return value
4096 * is zero for success, else a negative errno status code.
4097 * This call may only be used from a context that may sleep.
4099 * Parameters to this routine are always copied using a small buffer.
4100 * Performance-sensitive or bulk transfer code should instead use
4101 * spi_{async,sync}() calls with dma-safe buffers.
4103 * Return: zero on success, else a negative error code.
4105 int spi_write_then_read(struct spi_device *spi,
4106 const void *txbuf, unsigned n_tx,
4107 void *rxbuf, unsigned n_rx)
4109 static DEFINE_MUTEX(lock);
4112 struct spi_message message;
4113 struct spi_transfer x[2];
4116 /* Use preallocated DMA-safe buffer if we can. We can't avoid
4117 * copying here, (as a pure convenience thing), but we can
4118 * keep heap costs out of the hot path unless someone else is
4119 * using the pre-allocated buffer or the transfer is too large.
4121 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4122 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4123 GFP_KERNEL | GFP_DMA);
4130 spi_message_init(&message);
4131 memset(x, 0, sizeof(x));
4134 spi_message_add_tail(&x[0], &message);
4138 spi_message_add_tail(&x[1], &message);
4141 memcpy(local_buf, txbuf, n_tx);
4142 x[0].tx_buf = local_buf;
4143 x[1].rx_buf = local_buf + n_tx;
4146 status = spi_sync(spi, &message);
4148 memcpy(rxbuf, x[1].rx_buf, n_rx);
4150 if (x[0].tx_buf == buf)
4151 mutex_unlock(&lock);
4157 EXPORT_SYMBOL_GPL(spi_write_then_read);
4159 /*-------------------------------------------------------------------------*/
4161 #if IS_ENABLED(CONFIG_OF)
4162 /* must call put_device() when done with returned spi_device device */
4163 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4165 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4167 return dev ? to_spi_device(dev) : NULL;
4169 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4170 #endif /* IS_ENABLED(CONFIG_OF) */
4172 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4173 /* the spi controllers are not using spi_bus, so we find it with another way */
4174 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4178 dev = class_find_device_by_of_node(&spi_master_class, node);
4179 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4180 dev = class_find_device_by_of_node(&spi_slave_class, node);
4184 /* reference got in class_find_device */
4185 return container_of(dev, struct spi_controller, dev);
4188 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4191 struct of_reconfig_data *rd = arg;
4192 struct spi_controller *ctlr;
4193 struct spi_device *spi;
4195 switch (of_reconfig_get_state_change(action, arg)) {
4196 case OF_RECONFIG_CHANGE_ADD:
4197 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4199 return NOTIFY_OK; /* not for us */
4201 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4202 put_device(&ctlr->dev);
4206 spi = of_register_spi_device(ctlr, rd->dn);
4207 put_device(&ctlr->dev);
4210 pr_err("%s: failed to create for '%pOF'\n",
4212 of_node_clear_flag(rd->dn, OF_POPULATED);
4213 return notifier_from_errno(PTR_ERR(spi));
4217 case OF_RECONFIG_CHANGE_REMOVE:
4218 /* already depopulated? */
4219 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4222 /* find our device by node */
4223 spi = of_find_spi_device_by_node(rd->dn);
4225 return NOTIFY_OK; /* no? not meant for us */
4227 /* unregister takes one ref away */
4228 spi_unregister_device(spi);
4230 /* and put the reference of the find */
4231 put_device(&spi->dev);
4238 static struct notifier_block spi_of_notifier = {
4239 .notifier_call = of_spi_notify,
4241 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4242 extern struct notifier_block spi_of_notifier;
4243 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4245 #if IS_ENABLED(CONFIG_ACPI)
4246 static int spi_acpi_controller_match(struct device *dev, const void *data)
4248 return ACPI_COMPANION(dev->parent) == data;
4251 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4255 dev = class_find_device(&spi_master_class, NULL, adev,
4256 spi_acpi_controller_match);
4257 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4258 dev = class_find_device(&spi_slave_class, NULL, adev,
4259 spi_acpi_controller_match);
4263 return container_of(dev, struct spi_controller, dev);
4266 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4270 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4271 return to_spi_device(dev);
4274 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4277 struct acpi_device *adev = arg;
4278 struct spi_controller *ctlr;
4279 struct spi_device *spi;
4282 case ACPI_RECONFIG_DEVICE_ADD:
4283 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4287 acpi_register_spi_device(ctlr, adev);
4288 put_device(&ctlr->dev);
4290 case ACPI_RECONFIG_DEVICE_REMOVE:
4291 if (!acpi_device_enumerated(adev))
4294 spi = acpi_spi_find_device_by_adev(adev);
4298 spi_unregister_device(spi);
4299 put_device(&spi->dev);
4306 static struct notifier_block spi_acpi_notifier = {
4307 .notifier_call = acpi_spi_notify,
4310 extern struct notifier_block spi_acpi_notifier;
4313 static int __init spi_init(void)
4317 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4323 status = bus_register(&spi_bus_type);
4327 status = class_register(&spi_master_class);
4331 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4332 status = class_register(&spi_slave_class);
4337 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4338 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4339 if (IS_ENABLED(CONFIG_ACPI))
4340 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4345 class_unregister(&spi_master_class);
4347 bus_unregister(&spi_bus_type);
4355 /* board_info is normally registered in arch_initcall(),
4356 * but even essential drivers wait till later
4358 * REVISIT only boardinfo really needs static linking. the rest (device and
4359 * driver registration) _could_ be dynamically linked (modular) ... costs
4360 * include needing to have boardinfo data structures be much more public.
4362 postcore_initcall(spi_init);