1 // SPDX-License-Identifier: GPL-2.0-or-later
4 // Copyright (C) 2005 David Brownell
5 // Copyright (C) 2008 Secret Lab Technologies Ltd.
7 #include <linux/kernel.h>
8 #include <linux/device.h>
9 #include <linux/init.h>
10 #include <linux/cache.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/dmaengine.h>
13 #include <linux/mutex.h>
14 #include <linux/of_device.h>
15 #include <linux/of_irq.h>
16 #include <linux/clk/clk-conf.h>
17 #include <linux/slab.h>
18 #include <linux/mod_devicetable.h>
19 #include <linux/spi/spi.h>
20 #include <linux/spi/spi-mem.h>
21 #include <linux/gpio/consumer.h>
22 #include <linux/pm_runtime.h>
23 #include <linux/pm_domain.h>
24 #include <linux/property.h>
25 #include <linux/export.h>
26 #include <linux/sched/rt.h>
27 #include <uapi/linux/sched/types.h>
28 #include <linux/delay.h>
29 #include <linux/kthread.h>
30 #include <linux/ioport.h>
31 #include <linux/acpi.h>
32 #include <linux/highmem.h>
33 #include <linux/idr.h>
34 #include <linux/platform_data/x86/apple.h>
35 #include <linux/ptp_clock_kernel.h>
36 #include <linux/percpu.h>
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/spi.h>
40 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
41 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
43 #include "internals.h"
45 static DEFINE_IDR(spi_master_idr);
47 static void spidev_release(struct device *dev)
49 struct spi_device *spi = to_spi_device(dev);
51 spi_controller_put(spi->controller);
52 kfree(spi->driver_override);
53 free_percpu(spi->pcpu_statistics);
58 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
60 const struct spi_device *spi = to_spi_device(dev);
63 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
67 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
69 static DEVICE_ATTR_RO(modalias);
71 static ssize_t driver_override_store(struct device *dev,
72 struct device_attribute *a,
73 const char *buf, size_t count)
75 struct spi_device *spi = to_spi_device(dev);
78 ret = driver_set_override(dev, &spi->driver_override, buf, count);
85 static ssize_t driver_override_show(struct device *dev,
86 struct device_attribute *a, char *buf)
88 const struct spi_device *spi = to_spi_device(dev);
92 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
96 static DEVICE_ATTR_RW(driver_override);
98 static struct spi_statistics __percpu *spi_alloc_pcpu_stats(struct device *dev)
100 struct spi_statistics __percpu *pcpu_stats;
103 pcpu_stats = devm_alloc_percpu(dev, struct spi_statistics);
105 pcpu_stats = alloc_percpu_gfp(struct spi_statistics, GFP_KERNEL);
110 for_each_possible_cpu(cpu) {
111 struct spi_statistics *stat;
113 stat = per_cpu_ptr(pcpu_stats, cpu);
114 u64_stats_init(&stat->syncp);
120 #define spi_pcpu_stats_totalize(ret, in, field) \
124 for_each_possible_cpu(i) { \
125 const struct spi_statistics *pcpu_stats; \
127 unsigned int start; \
128 pcpu_stats = per_cpu_ptr(in, i); \
130 start = u64_stats_fetch_begin_irq( \
131 &pcpu_stats->syncp); \
132 inc = u64_stats_read(&pcpu_stats->field); \
133 } while (u64_stats_fetch_retry_irq( \
134 &pcpu_stats->syncp, start)); \
139 #define SPI_STATISTICS_ATTRS(field, file) \
140 static ssize_t spi_controller_##field##_show(struct device *dev, \
141 struct device_attribute *attr, \
144 struct spi_controller *ctlr = container_of(dev, \
145 struct spi_controller, dev); \
146 return spi_statistics_##field##_show(ctlr->pcpu_statistics, buf); \
148 static struct device_attribute dev_attr_spi_controller_##field = { \
149 .attr = { .name = file, .mode = 0444 }, \
150 .show = spi_controller_##field##_show, \
152 static ssize_t spi_device_##field##_show(struct device *dev, \
153 struct device_attribute *attr, \
156 struct spi_device *spi = to_spi_device(dev); \
157 return spi_statistics_##field##_show(spi->pcpu_statistics, buf); \
159 static struct device_attribute dev_attr_spi_device_##field = { \
160 .attr = { .name = file, .mode = 0444 }, \
161 .show = spi_device_##field##_show, \
164 #define SPI_STATISTICS_SHOW_NAME(name, file, field) \
165 static ssize_t spi_statistics_##name##_show(struct spi_statistics __percpu *stat, \
170 spi_pcpu_stats_totalize(val, stat, field); \
171 len = sysfs_emit(buf, "%llu\n", val); \
174 SPI_STATISTICS_ATTRS(name, file)
176 #define SPI_STATISTICS_SHOW(field) \
177 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
180 SPI_STATISTICS_SHOW(messages);
181 SPI_STATISTICS_SHOW(transfers);
182 SPI_STATISTICS_SHOW(errors);
183 SPI_STATISTICS_SHOW(timedout);
185 SPI_STATISTICS_SHOW(spi_sync);
186 SPI_STATISTICS_SHOW(spi_sync_immediate);
187 SPI_STATISTICS_SHOW(spi_async);
189 SPI_STATISTICS_SHOW(bytes);
190 SPI_STATISTICS_SHOW(bytes_rx);
191 SPI_STATISTICS_SHOW(bytes_tx);
193 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
194 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
195 "transfer_bytes_histo_" number, \
196 transfer_bytes_histo[index])
197 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
198 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
199 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
200 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
201 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
202 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
203 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
204 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
205 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
206 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
207 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
208 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
209 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
210 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
211 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
212 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
213 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
215 SPI_STATISTICS_SHOW(transfers_split_maxsize);
217 static struct attribute *spi_dev_attrs[] = {
218 &dev_attr_modalias.attr,
219 &dev_attr_driver_override.attr,
223 static const struct attribute_group spi_dev_group = {
224 .attrs = spi_dev_attrs,
227 static struct attribute *spi_device_statistics_attrs[] = {
228 &dev_attr_spi_device_messages.attr,
229 &dev_attr_spi_device_transfers.attr,
230 &dev_attr_spi_device_errors.attr,
231 &dev_attr_spi_device_timedout.attr,
232 &dev_attr_spi_device_spi_sync.attr,
233 &dev_attr_spi_device_spi_sync_immediate.attr,
234 &dev_attr_spi_device_spi_async.attr,
235 &dev_attr_spi_device_bytes.attr,
236 &dev_attr_spi_device_bytes_rx.attr,
237 &dev_attr_spi_device_bytes_tx.attr,
238 &dev_attr_spi_device_transfer_bytes_histo0.attr,
239 &dev_attr_spi_device_transfer_bytes_histo1.attr,
240 &dev_attr_spi_device_transfer_bytes_histo2.attr,
241 &dev_attr_spi_device_transfer_bytes_histo3.attr,
242 &dev_attr_spi_device_transfer_bytes_histo4.attr,
243 &dev_attr_spi_device_transfer_bytes_histo5.attr,
244 &dev_attr_spi_device_transfer_bytes_histo6.attr,
245 &dev_attr_spi_device_transfer_bytes_histo7.attr,
246 &dev_attr_spi_device_transfer_bytes_histo8.attr,
247 &dev_attr_spi_device_transfer_bytes_histo9.attr,
248 &dev_attr_spi_device_transfer_bytes_histo10.attr,
249 &dev_attr_spi_device_transfer_bytes_histo11.attr,
250 &dev_attr_spi_device_transfer_bytes_histo12.attr,
251 &dev_attr_spi_device_transfer_bytes_histo13.attr,
252 &dev_attr_spi_device_transfer_bytes_histo14.attr,
253 &dev_attr_spi_device_transfer_bytes_histo15.attr,
254 &dev_attr_spi_device_transfer_bytes_histo16.attr,
255 &dev_attr_spi_device_transfers_split_maxsize.attr,
259 static const struct attribute_group spi_device_statistics_group = {
260 .name = "statistics",
261 .attrs = spi_device_statistics_attrs,
264 static const struct attribute_group *spi_dev_groups[] = {
266 &spi_device_statistics_group,
270 static struct attribute *spi_controller_statistics_attrs[] = {
271 &dev_attr_spi_controller_messages.attr,
272 &dev_attr_spi_controller_transfers.attr,
273 &dev_attr_spi_controller_errors.attr,
274 &dev_attr_spi_controller_timedout.attr,
275 &dev_attr_spi_controller_spi_sync.attr,
276 &dev_attr_spi_controller_spi_sync_immediate.attr,
277 &dev_attr_spi_controller_spi_async.attr,
278 &dev_attr_spi_controller_bytes.attr,
279 &dev_attr_spi_controller_bytes_rx.attr,
280 &dev_attr_spi_controller_bytes_tx.attr,
281 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
282 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
283 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
284 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
285 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
286 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
287 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
288 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
289 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
290 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
291 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
292 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
293 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
294 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
295 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
296 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
297 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
298 &dev_attr_spi_controller_transfers_split_maxsize.attr,
302 static const struct attribute_group spi_controller_statistics_group = {
303 .name = "statistics",
304 .attrs = spi_controller_statistics_attrs,
307 static const struct attribute_group *spi_master_groups[] = {
308 &spi_controller_statistics_group,
312 static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
313 struct spi_transfer *xfer,
314 struct spi_controller *ctlr)
316 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
317 struct spi_statistics *stats;
323 stats = this_cpu_ptr(pcpu_stats);
324 u64_stats_update_begin(&stats->syncp);
326 u64_stats_inc(&stats->transfers);
327 u64_stats_inc(&stats->transfer_bytes_histo[l2len]);
329 u64_stats_add(&stats->bytes, xfer->len);
330 if ((xfer->tx_buf) &&
331 (xfer->tx_buf != ctlr->dummy_tx))
332 u64_stats_add(&stats->bytes_tx, xfer->len);
333 if ((xfer->rx_buf) &&
334 (xfer->rx_buf != ctlr->dummy_rx))
335 u64_stats_add(&stats->bytes_rx, xfer->len);
337 u64_stats_update_end(&stats->syncp);
342 * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
343 * and the sysfs version makes coldplug work too.
345 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
347 while (id->name[0]) {
348 if (!strcmp(name, id->name))
355 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
357 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
359 return spi_match_id(sdrv->id_table, sdev->modalias);
361 EXPORT_SYMBOL_GPL(spi_get_device_id);
363 static int spi_match_device(struct device *dev, struct device_driver *drv)
365 const struct spi_device *spi = to_spi_device(dev);
366 const struct spi_driver *sdrv = to_spi_driver(drv);
368 /* Check override first, and if set, only use the named driver */
369 if (spi->driver_override)
370 return strcmp(spi->driver_override, drv->name) == 0;
372 /* Attempt an OF style match */
373 if (of_driver_match_device(dev, drv))
377 if (acpi_driver_match_device(dev, drv))
381 return !!spi_match_id(sdrv->id_table, spi->modalias);
383 return strcmp(spi->modalias, drv->name) == 0;
386 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
388 const struct spi_device *spi = to_spi_device(dev);
391 rc = acpi_device_uevent_modalias(dev, env);
395 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
398 static int spi_probe(struct device *dev)
400 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
401 struct spi_device *spi = to_spi_device(dev);
404 ret = of_clk_set_defaults(dev->of_node, false);
409 spi->irq = of_irq_get(dev->of_node, 0);
410 if (spi->irq == -EPROBE_DEFER)
411 return -EPROBE_DEFER;
416 ret = dev_pm_domain_attach(dev, true);
421 ret = sdrv->probe(spi);
423 dev_pm_domain_detach(dev, true);
429 static void spi_remove(struct device *dev)
431 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
434 sdrv->remove(to_spi_device(dev));
436 dev_pm_domain_detach(dev, true);
439 static void spi_shutdown(struct device *dev)
442 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
445 sdrv->shutdown(to_spi_device(dev));
449 struct bus_type spi_bus_type = {
451 .dev_groups = spi_dev_groups,
452 .match = spi_match_device,
453 .uevent = spi_uevent,
455 .remove = spi_remove,
456 .shutdown = spi_shutdown,
458 EXPORT_SYMBOL_GPL(spi_bus_type);
461 * __spi_register_driver - register a SPI driver
462 * @owner: owner module of the driver to register
463 * @sdrv: the driver to register
466 * Return: zero on success, else a negative error code.
468 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
470 sdrv->driver.owner = owner;
471 sdrv->driver.bus = &spi_bus_type;
474 * For Really Good Reasons we use spi: modaliases not of:
475 * modaliases for DT so module autoloading won't work if we
476 * don't have a spi_device_id as well as a compatible string.
478 if (sdrv->driver.of_match_table) {
479 const struct of_device_id *of_id;
481 for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
485 /* Strip off any vendor prefix */
486 of_name = strnchr(of_id->compatible,
487 sizeof(of_id->compatible), ',');
491 of_name = of_id->compatible;
493 if (sdrv->id_table) {
494 const struct spi_device_id *spi_id;
496 spi_id = spi_match_id(sdrv->id_table, of_name);
500 if (strcmp(sdrv->driver.name, of_name) == 0)
504 pr_warn("SPI driver %s has no spi_device_id for %s\n",
505 sdrv->driver.name, of_id->compatible);
509 return driver_register(&sdrv->driver);
511 EXPORT_SYMBOL_GPL(__spi_register_driver);
513 /*-------------------------------------------------------------------------*/
516 * SPI devices should normally not be created by SPI device drivers; that
517 * would make them board-specific. Similarly with SPI controller drivers.
518 * Device registration normally goes into like arch/.../mach.../board-YYY.c
519 * with other readonly (flashable) information about mainboard devices.
523 struct list_head list;
524 struct spi_board_info board_info;
527 static LIST_HEAD(board_list);
528 static LIST_HEAD(spi_controller_list);
531 * Used to protect add/del operation for board_info list and
532 * spi_controller list, and their matching process also used
533 * to protect object of type struct idr.
535 static DEFINE_MUTEX(board_lock);
538 * spi_alloc_device - Allocate a new SPI device
539 * @ctlr: Controller to which device is connected
542 * Allows a driver to allocate and initialize a spi_device without
543 * registering it immediately. This allows a driver to directly
544 * fill the spi_device with device parameters before calling
545 * spi_add_device() on it.
547 * Caller is responsible to call spi_add_device() on the returned
548 * spi_device structure to add it to the SPI controller. If the caller
549 * needs to discard the spi_device without adding it, then it should
550 * call spi_dev_put() on it.
552 * Return: a pointer to the new device, or NULL.
554 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
556 struct spi_device *spi;
558 if (!spi_controller_get(ctlr))
561 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
563 spi_controller_put(ctlr);
567 spi->pcpu_statistics = spi_alloc_pcpu_stats(NULL);
568 if (!spi->pcpu_statistics) {
570 spi_controller_put(ctlr);
574 spi->master = spi->controller = ctlr;
575 spi->dev.parent = &ctlr->dev;
576 spi->dev.bus = &spi_bus_type;
577 spi->dev.release = spidev_release;
578 spi->mode = ctlr->buswidth_override_bits;
580 device_initialize(&spi->dev);
583 EXPORT_SYMBOL_GPL(spi_alloc_device);
585 static void spi_dev_set_name(struct spi_device *spi)
587 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
590 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
594 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
598 static int spi_dev_check(struct device *dev, void *data)
600 struct spi_device *spi = to_spi_device(dev);
601 struct spi_device *new_spi = data;
603 if (spi->controller == new_spi->controller &&
604 spi->chip_select == new_spi->chip_select)
609 static void spi_cleanup(struct spi_device *spi)
611 if (spi->controller->cleanup)
612 spi->controller->cleanup(spi);
615 static int __spi_add_device(struct spi_device *spi)
617 struct spi_controller *ctlr = spi->controller;
618 struct device *dev = ctlr->dev.parent;
622 * We need to make sure there's no other device with this
623 * chipselect **BEFORE** we call setup(), else we'll trash
626 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
628 dev_err(dev, "chipselect %d already in use\n",
633 /* Controller may unregister concurrently */
634 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
635 !device_is_registered(&ctlr->dev)) {
640 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
643 * Drivers may modify this initial i/o setup, but will
644 * normally rely on the device being setup. Devices
645 * using SPI_CS_HIGH can't coexist well otherwise...
647 status = spi_setup(spi);
649 dev_err(dev, "can't setup %s, status %d\n",
650 dev_name(&spi->dev), status);
654 /* Device may be bound to an active driver when this returns */
655 status = device_add(&spi->dev);
657 dev_err(dev, "can't add %s, status %d\n",
658 dev_name(&spi->dev), status);
661 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
668 * spi_add_device - Add spi_device allocated with spi_alloc_device
669 * @spi: spi_device to register
671 * Companion function to spi_alloc_device. Devices allocated with
672 * spi_alloc_device can be added onto the spi bus with this function.
674 * Return: 0 on success; negative errno on failure
676 int spi_add_device(struct spi_device *spi)
678 struct spi_controller *ctlr = spi->controller;
679 struct device *dev = ctlr->dev.parent;
682 /* Chipselects are numbered 0..max; validate. */
683 if (spi->chip_select >= ctlr->num_chipselect) {
684 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
685 ctlr->num_chipselect);
689 /* Set the bus ID string */
690 spi_dev_set_name(spi);
692 mutex_lock(&ctlr->add_lock);
693 status = __spi_add_device(spi);
694 mutex_unlock(&ctlr->add_lock);
697 EXPORT_SYMBOL_GPL(spi_add_device);
699 static int spi_add_device_locked(struct spi_device *spi)
701 struct spi_controller *ctlr = spi->controller;
702 struct device *dev = ctlr->dev.parent;
704 /* Chipselects are numbered 0..max; validate. */
705 if (spi->chip_select >= ctlr->num_chipselect) {
706 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
707 ctlr->num_chipselect);
711 /* Set the bus ID string */
712 spi_dev_set_name(spi);
714 WARN_ON(!mutex_is_locked(&ctlr->add_lock));
715 return __spi_add_device(spi);
719 * spi_new_device - instantiate one new SPI device
720 * @ctlr: Controller to which device is connected
721 * @chip: Describes the SPI device
724 * On typical mainboards, this is purely internal; and it's not needed
725 * after board init creates the hard-wired devices. Some development
726 * platforms may not be able to use spi_register_board_info though, and
727 * this is exported so that for example a USB or parport based adapter
728 * driver could add devices (which it would learn about out-of-band).
730 * Return: the new device, or NULL.
732 struct spi_device *spi_new_device(struct spi_controller *ctlr,
733 struct spi_board_info *chip)
735 struct spi_device *proxy;
739 * NOTE: caller did any chip->bus_num checks necessary.
741 * Also, unless we change the return value convention to use
742 * error-or-pointer (not NULL-or-pointer), troubleshootability
743 * suggests syslogged diagnostics are best here (ugh).
746 proxy = spi_alloc_device(ctlr);
750 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
752 proxy->chip_select = chip->chip_select;
753 proxy->max_speed_hz = chip->max_speed_hz;
754 proxy->mode = chip->mode;
755 proxy->irq = chip->irq;
756 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
757 proxy->dev.platform_data = (void *) chip->platform_data;
758 proxy->controller_data = chip->controller_data;
759 proxy->controller_state = NULL;
762 status = device_add_software_node(&proxy->dev, chip->swnode);
764 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
765 chip->modalias, status);
770 status = spi_add_device(proxy);
777 device_remove_software_node(&proxy->dev);
781 EXPORT_SYMBOL_GPL(spi_new_device);
784 * spi_unregister_device - unregister a single SPI device
785 * @spi: spi_device to unregister
787 * Start making the passed SPI device vanish. Normally this would be handled
788 * by spi_unregister_controller().
790 void spi_unregister_device(struct spi_device *spi)
795 if (spi->dev.of_node) {
796 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
797 of_node_put(spi->dev.of_node);
799 if (ACPI_COMPANION(&spi->dev))
800 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
801 device_remove_software_node(&spi->dev);
802 device_del(&spi->dev);
804 put_device(&spi->dev);
806 EXPORT_SYMBOL_GPL(spi_unregister_device);
808 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
809 struct spi_board_info *bi)
811 struct spi_device *dev;
813 if (ctlr->bus_num != bi->bus_num)
816 dev = spi_new_device(ctlr, bi);
818 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
823 * spi_register_board_info - register SPI devices for a given board
824 * @info: array of chip descriptors
825 * @n: how many descriptors are provided
828 * Board-specific early init code calls this (probably during arch_initcall)
829 * with segments of the SPI device table. Any device nodes are created later,
830 * after the relevant parent SPI controller (bus_num) is defined. We keep
831 * this table of devices forever, so that reloading a controller driver will
832 * not make Linux forget about these hard-wired devices.
834 * Other code can also call this, e.g. a particular add-on board might provide
835 * SPI devices through its expansion connector, so code initializing that board
836 * would naturally declare its SPI devices.
838 * The board info passed can safely be __initdata ... but be careful of
839 * any embedded pointers (platform_data, etc), they're copied as-is.
841 * Return: zero on success, else a negative error code.
843 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
845 struct boardinfo *bi;
851 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
855 for (i = 0; i < n; i++, bi++, info++) {
856 struct spi_controller *ctlr;
858 memcpy(&bi->board_info, info, sizeof(*info));
860 mutex_lock(&board_lock);
861 list_add_tail(&bi->list, &board_list);
862 list_for_each_entry(ctlr, &spi_controller_list, list)
863 spi_match_controller_to_boardinfo(ctlr,
865 mutex_unlock(&board_lock);
871 /*-------------------------------------------------------------------------*/
873 /* Core methods for SPI resource management */
876 * spi_res_alloc - allocate a spi resource that is life-cycle managed
877 * during the processing of a spi_message while using
879 * @spi: the spi device for which we allocate memory
880 * @release: the release code to execute for this resource
881 * @size: size to alloc and return
882 * @gfp: GFP allocation flags
884 * Return: the pointer to the allocated data
886 * This may get enhanced in the future to allocate from a memory pool
887 * of the @spi_device or @spi_controller to avoid repeated allocations.
889 static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
890 size_t size, gfp_t gfp)
892 struct spi_res *sres;
894 sres = kzalloc(sizeof(*sres) + size, gfp);
898 INIT_LIST_HEAD(&sres->entry);
899 sres->release = release;
905 * spi_res_free - free an spi resource
906 * @res: pointer to the custom data of a resource
908 static void spi_res_free(void *res)
910 struct spi_res *sres = container_of(res, struct spi_res, data);
915 WARN_ON(!list_empty(&sres->entry));
920 * spi_res_add - add a spi_res to the spi_message
921 * @message: the spi message
922 * @res: the spi_resource
924 static void spi_res_add(struct spi_message *message, void *res)
926 struct spi_res *sres = container_of(res, struct spi_res, data);
928 WARN_ON(!list_empty(&sres->entry));
929 list_add_tail(&sres->entry, &message->resources);
933 * spi_res_release - release all spi resources for this message
934 * @ctlr: the @spi_controller
935 * @message: the @spi_message
937 static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
939 struct spi_res *res, *tmp;
941 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
943 res->release(ctlr, message, res->data);
945 list_del(&res->entry);
951 /*-------------------------------------------------------------------------*/
953 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
955 bool activate = enable;
958 * Avoid calling into the driver (or doing delays) if the chip select
959 * isn't actually changing from the last time this was called.
961 if (!force && ((enable && spi->controller->last_cs == spi->chip_select) ||
962 (!enable && spi->controller->last_cs != spi->chip_select)) &&
963 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
966 trace_spi_set_cs(spi, activate);
968 spi->controller->last_cs = enable ? spi->chip_select : -1;
969 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
971 if ((spi->cs_gpiod || !spi->controller->set_cs_timing) && !activate) {
972 spi_delay_exec(&spi->cs_hold, NULL);
975 if (spi->mode & SPI_CS_HIGH)
979 if (!(spi->mode & SPI_NO_CS)) {
981 * Historically ACPI has no means of the GPIO polarity and
982 * thus the SPISerialBus() resource defines it on the per-chip
983 * basis. In order to avoid a chain of negations, the GPIO
984 * polarity is considered being Active High. Even for the cases
985 * when _DSD() is involved (in the updated versions of ACPI)
986 * the GPIO CS polarity must be defined Active High to avoid
987 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
990 if (has_acpi_companion(&spi->dev))
991 gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
993 /* Polarity handled by GPIO library */
994 gpiod_set_value_cansleep(spi->cs_gpiod, activate);
996 /* Some SPI masters need both GPIO CS & slave_select */
997 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
998 spi->controller->set_cs)
999 spi->controller->set_cs(spi, !enable);
1000 } else if (spi->controller->set_cs) {
1001 spi->controller->set_cs(spi, !enable);
1004 if (spi->cs_gpiod || !spi->controller->set_cs_timing) {
1006 spi_delay_exec(&spi->cs_setup, NULL);
1008 spi_delay_exec(&spi->cs_inactive, NULL);
1012 #ifdef CONFIG_HAS_DMA
1013 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
1014 struct sg_table *sgt, void *buf, size_t len,
1015 enum dma_data_direction dir)
1017 const bool vmalloced_buf = is_vmalloc_addr(buf);
1018 unsigned int max_seg_size = dma_get_max_seg_size(dev);
1019 #ifdef CONFIG_HIGHMEM
1020 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
1021 (unsigned long)buf < (PKMAP_BASE +
1022 (LAST_PKMAP * PAGE_SIZE)));
1024 const bool kmap_buf = false;
1028 struct page *vm_page;
1029 struct scatterlist *sg;
1034 if (vmalloced_buf || kmap_buf) {
1035 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
1036 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
1037 } else if (virt_addr_valid(buf)) {
1038 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
1039 sgs = DIV_ROUND_UP(len, desc_len);
1044 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
1049 for (i = 0; i < sgs; i++) {
1051 if (vmalloced_buf || kmap_buf) {
1053 * Next scatterlist entry size is the minimum between
1054 * the desc_len and the remaining buffer length that
1057 min = min_t(size_t, desc_len,
1059 PAGE_SIZE - offset_in_page(buf)));
1061 vm_page = vmalloc_to_page(buf);
1063 vm_page = kmap_to_page(buf);
1068 sg_set_page(sg, vm_page,
1069 min, offset_in_page(buf));
1071 min = min_t(size_t, len, desc_len);
1073 sg_set_buf(sg, sg_buf, min);
1081 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
1094 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
1095 struct sg_table *sgt, enum dma_data_direction dir)
1097 if (sgt->orig_nents) {
1098 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
1103 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1105 struct device *tx_dev, *rx_dev;
1106 struct spi_transfer *xfer;
1113 tx_dev = ctlr->dma_tx->device->dev;
1114 else if (ctlr->dma_map_dev)
1115 tx_dev = ctlr->dma_map_dev;
1117 tx_dev = ctlr->dev.parent;
1120 rx_dev = ctlr->dma_rx->device->dev;
1121 else if (ctlr->dma_map_dev)
1122 rx_dev = ctlr->dma_map_dev;
1124 rx_dev = ctlr->dev.parent;
1126 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1127 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1130 if (xfer->tx_buf != NULL) {
1131 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
1132 (void *)xfer->tx_buf, xfer->len,
1138 if (xfer->rx_buf != NULL) {
1139 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
1140 xfer->rx_buf, xfer->len,
1143 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
1150 ctlr->cur_msg_mapped = true;
1155 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1157 struct spi_transfer *xfer;
1158 struct device *tx_dev, *rx_dev;
1160 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1164 tx_dev = ctlr->dma_tx->device->dev;
1165 else if (ctlr->dma_map_dev)
1166 tx_dev = ctlr->dma_map_dev;
1168 tx_dev = ctlr->dev.parent;
1171 rx_dev = ctlr->dma_rx->device->dev;
1172 else if (ctlr->dma_map_dev)
1173 rx_dev = ctlr->dma_map_dev;
1175 rx_dev = ctlr->dev.parent;
1177 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1178 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1181 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1182 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1185 ctlr->cur_msg_mapped = false;
1189 #else /* !CONFIG_HAS_DMA */
1190 static inline int __spi_map_msg(struct spi_controller *ctlr,
1191 struct spi_message *msg)
1196 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1197 struct spi_message *msg)
1201 #endif /* !CONFIG_HAS_DMA */
1203 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1204 struct spi_message *msg)
1206 struct spi_transfer *xfer;
1208 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1210 * Restore the original value of tx_buf or rx_buf if they are
1213 if (xfer->tx_buf == ctlr->dummy_tx)
1214 xfer->tx_buf = NULL;
1215 if (xfer->rx_buf == ctlr->dummy_rx)
1216 xfer->rx_buf = NULL;
1219 return __spi_unmap_msg(ctlr, msg);
1222 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1224 struct spi_transfer *xfer;
1226 unsigned int max_tx, max_rx;
1228 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1229 && !(msg->spi->mode & SPI_3WIRE)) {
1233 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1234 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1236 max_tx = max(xfer->len, max_tx);
1237 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1239 max_rx = max(xfer->len, max_rx);
1243 tmp = krealloc(ctlr->dummy_tx, max_tx,
1244 GFP_KERNEL | GFP_DMA | __GFP_ZERO);
1247 ctlr->dummy_tx = tmp;
1251 tmp = krealloc(ctlr->dummy_rx, max_rx,
1252 GFP_KERNEL | GFP_DMA);
1255 ctlr->dummy_rx = tmp;
1258 if (max_tx || max_rx) {
1259 list_for_each_entry(xfer, &msg->transfers,
1264 xfer->tx_buf = ctlr->dummy_tx;
1266 xfer->rx_buf = ctlr->dummy_rx;
1271 return __spi_map_msg(ctlr, msg);
1274 static int spi_transfer_wait(struct spi_controller *ctlr,
1275 struct spi_message *msg,
1276 struct spi_transfer *xfer)
1278 struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1279 struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1280 u32 speed_hz = xfer->speed_hz;
1281 unsigned long long ms;
1283 if (spi_controller_is_slave(ctlr)) {
1284 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1285 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1293 * For each byte we wait for 8 cycles of the SPI clock.
1294 * Since speed is defined in Hz and we want milliseconds,
1295 * use respective multiplier, but before the division,
1296 * otherwise we may get 0 for short transfers.
1298 ms = 8LL * MSEC_PER_SEC * xfer->len;
1299 do_div(ms, speed_hz);
1302 * Increase it twice and add 200 ms tolerance, use
1303 * predefined maximum in case of overflow.
1309 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1310 msecs_to_jiffies(ms));
1313 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1314 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1315 dev_err(&msg->spi->dev,
1316 "SPI transfer timed out\n");
1324 static void _spi_transfer_delay_ns(u32 ns)
1328 if (ns <= NSEC_PER_USEC) {
1331 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1336 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1340 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1342 u32 delay = _delay->value;
1343 u32 unit = _delay->unit;
1350 case SPI_DELAY_UNIT_USECS:
1351 delay *= NSEC_PER_USEC;
1353 case SPI_DELAY_UNIT_NSECS:
1354 /* Nothing to do here */
1356 case SPI_DELAY_UNIT_SCK:
1357 /* Clock cycles need to be obtained from spi_transfer */
1361 * If there is unknown effective speed, approximate it
1362 * by underestimating with half of the requested hz.
1364 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1368 /* Convert delay to nanoseconds */
1369 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1377 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1379 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1388 delay = spi_delay_to_ns(_delay, xfer);
1392 _spi_transfer_delay_ns(delay);
1396 EXPORT_SYMBOL_GPL(spi_delay_exec);
1398 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1399 struct spi_transfer *xfer)
1401 u32 default_delay_ns = 10 * NSEC_PER_USEC;
1402 u32 delay = xfer->cs_change_delay.value;
1403 u32 unit = xfer->cs_change_delay.unit;
1406 /* Return early on "fast" mode - for everything but USECS */
1408 if (unit == SPI_DELAY_UNIT_USECS)
1409 _spi_transfer_delay_ns(default_delay_ns);
1413 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1415 dev_err_once(&msg->spi->dev,
1416 "Use of unsupported delay unit %i, using default of %luus\n",
1417 unit, default_delay_ns / NSEC_PER_USEC);
1418 _spi_transfer_delay_ns(default_delay_ns);
1423 * spi_transfer_one_message - Default implementation of transfer_one_message()
1425 * This is a standard implementation of transfer_one_message() for
1426 * drivers which implement a transfer_one() operation. It provides
1427 * standard handling of delays and chip select management.
1429 static int spi_transfer_one_message(struct spi_controller *ctlr,
1430 struct spi_message *msg)
1432 struct spi_transfer *xfer;
1433 bool keep_cs = false;
1435 struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1436 struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1438 spi_set_cs(msg->spi, true, false);
1440 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1441 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1443 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1444 trace_spi_transfer_start(msg, xfer);
1446 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1447 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1449 if (!ctlr->ptp_sts_supported) {
1450 xfer->ptp_sts_word_pre = 0;
1451 ptp_read_system_prets(xfer->ptp_sts);
1454 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1455 reinit_completion(&ctlr->xfer_completion);
1458 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1460 if (ctlr->cur_msg_mapped &&
1461 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1462 __spi_unmap_msg(ctlr, msg);
1463 ctlr->fallback = true;
1464 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1468 SPI_STATISTICS_INCREMENT_FIELD(statm,
1470 SPI_STATISTICS_INCREMENT_FIELD(stats,
1472 dev_err(&msg->spi->dev,
1473 "SPI transfer failed: %d\n", ret);
1478 ret = spi_transfer_wait(ctlr, msg, xfer);
1484 dev_err(&msg->spi->dev,
1485 "Bufferless transfer has length %u\n",
1489 if (!ctlr->ptp_sts_supported) {
1490 ptp_read_system_postts(xfer->ptp_sts);
1491 xfer->ptp_sts_word_post = xfer->len;
1494 trace_spi_transfer_stop(msg, xfer);
1496 if (msg->status != -EINPROGRESS)
1499 spi_transfer_delay_exec(xfer);
1501 if (xfer->cs_change) {
1502 if (list_is_last(&xfer->transfer_list,
1506 spi_set_cs(msg->spi, false, false);
1507 _spi_transfer_cs_change_delay(msg, xfer);
1508 spi_set_cs(msg->spi, true, false);
1512 msg->actual_length += xfer->len;
1516 if (ret != 0 || !keep_cs)
1517 spi_set_cs(msg->spi, false, false);
1519 if (msg->status == -EINPROGRESS)
1522 if (msg->status && ctlr->handle_err)
1523 ctlr->handle_err(ctlr, msg);
1525 spi_finalize_current_message(ctlr);
1531 * spi_finalize_current_transfer - report completion of a transfer
1532 * @ctlr: the controller reporting completion
1534 * Called by SPI drivers using the core transfer_one_message()
1535 * implementation to notify it that the current interrupt driven
1536 * transfer has finished and the next one may be scheduled.
1538 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1540 complete(&ctlr->xfer_completion);
1542 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1544 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1546 if (ctlr->auto_runtime_pm) {
1547 pm_runtime_mark_last_busy(ctlr->dev.parent);
1548 pm_runtime_put_autosuspend(ctlr->dev.parent);
1552 static int __spi_pump_transfer_message(struct spi_controller *ctlr,
1553 struct spi_message *msg, bool was_busy)
1555 struct spi_transfer *xfer;
1558 if (!was_busy && ctlr->auto_runtime_pm) {
1559 ret = pm_runtime_get_sync(ctlr->dev.parent);
1561 pm_runtime_put_noidle(ctlr->dev.parent);
1562 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1569 trace_spi_controller_busy(ctlr);
1571 if (!was_busy && ctlr->prepare_transfer_hardware) {
1572 ret = ctlr->prepare_transfer_hardware(ctlr);
1575 "failed to prepare transfer hardware: %d\n",
1578 if (ctlr->auto_runtime_pm)
1579 pm_runtime_put(ctlr->dev.parent);
1582 spi_finalize_current_message(ctlr);
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 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);
1617 * Drivers implementation of transfer_one_message() must arrange for
1618 * spi_finalize_current_message() to get called. Most drivers will do
1619 * this in the calling context, but some don't. For those cases, a
1620 * completion is used to guarantee that this function does not return
1621 * until spi_finalize_current_message() is done accessing
1623 * Use of the following two flags enable to opportunistically skip the
1624 * use of the completion since its use involves expensive spin locks.
1625 * In case of a race with the context that calls
1626 * spi_finalize_current_message() the completion will always be used,
1627 * due to strict ordering of these flags using barriers.
1629 WRITE_ONCE(ctlr->cur_msg_incomplete, true);
1630 WRITE_ONCE(ctlr->cur_msg_need_completion, false);
1631 reinit_completion(&ctlr->cur_msg_completion);
1632 smp_wmb(); /* Make these available to spi_finalize_current_message() */
1634 ret = ctlr->transfer_one_message(ctlr, msg);
1637 "failed to transfer one message from queue\n");
1641 WRITE_ONCE(ctlr->cur_msg_need_completion, true);
1642 smp_mb(); /* See spi_finalize_current_message()... */
1643 if (READ_ONCE(ctlr->cur_msg_incomplete))
1644 wait_for_completion(&ctlr->cur_msg_completion);
1650 * __spi_pump_messages - function which processes spi message queue
1651 * @ctlr: controller to process queue for
1652 * @in_kthread: true if we are in the context of the message pump thread
1654 * This function checks if there is any spi message in the queue that
1655 * needs processing and if so call out to the driver to initialize hardware
1656 * and transfer each message.
1658 * Note that it is called both from the kthread itself and also from
1659 * inside spi_sync(); the queue extraction handling at the top of the
1660 * function should deal with this safely.
1662 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1664 struct spi_message *msg;
1665 bool was_busy = false;
1666 unsigned long flags;
1669 /* Take the IO mutex */
1670 mutex_lock(&ctlr->io_mutex);
1673 spin_lock_irqsave(&ctlr->queue_lock, flags);
1675 /* Make sure we are not already running a message */
1679 /* Check if the queue is idle */
1680 if (list_empty(&ctlr->queue) || !ctlr->running) {
1684 /* Defer any non-atomic teardown to the thread */
1686 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1687 !ctlr->unprepare_transfer_hardware) {
1688 spi_idle_runtime_pm(ctlr);
1690 ctlr->queue_empty = true;
1691 trace_spi_controller_idle(ctlr);
1693 kthread_queue_work(ctlr->kworker,
1694 &ctlr->pump_messages);
1700 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1702 kfree(ctlr->dummy_rx);
1703 ctlr->dummy_rx = NULL;
1704 kfree(ctlr->dummy_tx);
1705 ctlr->dummy_tx = NULL;
1706 if (ctlr->unprepare_transfer_hardware &&
1707 ctlr->unprepare_transfer_hardware(ctlr))
1709 "failed to unprepare transfer hardware\n");
1710 spi_idle_runtime_pm(ctlr);
1711 trace_spi_controller_idle(ctlr);
1713 spin_lock_irqsave(&ctlr->queue_lock, flags);
1714 ctlr->queue_empty = true;
1718 /* Extract head of queue */
1719 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1720 ctlr->cur_msg = msg;
1722 list_del_init(&msg->queue);
1727 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1729 ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
1731 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1733 ctlr->cur_msg = NULL;
1734 ctlr->fallback = false;
1736 mutex_unlock(&ctlr->io_mutex);
1738 /* Prod the scheduler in case transfer_one() was busy waiting */
1744 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1745 mutex_unlock(&ctlr->io_mutex);
1749 * spi_pump_messages - kthread work function which processes spi message queue
1750 * @work: pointer to kthread work struct contained in the controller struct
1752 static void spi_pump_messages(struct kthread_work *work)
1754 struct spi_controller *ctlr =
1755 container_of(work, struct spi_controller, pump_messages);
1757 __spi_pump_messages(ctlr, true);
1761 * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1762 * @ctlr: Pointer to the spi_controller structure of the driver
1763 * @xfer: Pointer to the transfer being timestamped
1764 * @progress: How many words (not bytes) have been transferred so far
1765 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1766 * transfer, for less jitter in time measurement. Only compatible
1767 * with PIO drivers. If true, must follow up with
1768 * spi_take_timestamp_post or otherwise system will crash.
1769 * WARNING: for fully predictable results, the CPU frequency must
1770 * also be under control (governor).
1772 * This is a helper for drivers to collect the beginning of the TX timestamp
1773 * for the requested byte from the SPI transfer. The frequency with which this
1774 * function must be called (once per word, once for the whole transfer, once
1775 * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1776 * greater than or equal to the requested byte at the time of the call. The
1777 * timestamp is only taken once, at the first such call. It is assumed that
1778 * the driver advances its @tx buffer pointer monotonically.
1780 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1781 struct spi_transfer *xfer,
1782 size_t progress, bool irqs_off)
1787 if (xfer->timestamped)
1790 if (progress > xfer->ptp_sts_word_pre)
1793 /* Capture the resolution of the timestamp */
1794 xfer->ptp_sts_word_pre = progress;
1797 local_irq_save(ctlr->irq_flags);
1801 ptp_read_system_prets(xfer->ptp_sts);
1803 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1806 * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1807 * @ctlr: Pointer to the spi_controller structure of the driver
1808 * @xfer: Pointer to the transfer being timestamped
1809 * @progress: How many words (not bytes) have been transferred so far
1810 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1812 * This is a helper for drivers to collect the end of the TX timestamp for
1813 * the requested byte from the SPI transfer. Can be called with an arbitrary
1814 * frequency: only the first call where @tx exceeds or is equal to the
1815 * requested word will be timestamped.
1817 void spi_take_timestamp_post(struct spi_controller *ctlr,
1818 struct spi_transfer *xfer,
1819 size_t progress, bool irqs_off)
1824 if (xfer->timestamped)
1827 if (progress < xfer->ptp_sts_word_post)
1830 ptp_read_system_postts(xfer->ptp_sts);
1833 local_irq_restore(ctlr->irq_flags);
1837 /* Capture the resolution of the timestamp */
1838 xfer->ptp_sts_word_post = progress;
1840 xfer->timestamped = true;
1842 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1845 * spi_set_thread_rt - set the controller to pump at realtime priority
1846 * @ctlr: controller to boost priority of
1848 * This can be called because the controller requested realtime priority
1849 * (by setting the ->rt value before calling spi_register_controller()) or
1850 * because a device on the bus said that its transfers needed realtime
1853 * NOTE: at the moment if any device on a bus says it needs realtime then
1854 * the thread will be at realtime priority for all transfers on that
1855 * controller. If this eventually becomes a problem we may see if we can
1856 * find a way to boost the priority only temporarily during relevant
1859 static void spi_set_thread_rt(struct spi_controller *ctlr)
1861 dev_info(&ctlr->dev,
1862 "will run message pump with realtime priority\n");
1863 sched_set_fifo(ctlr->kworker->task);
1866 static int spi_init_queue(struct spi_controller *ctlr)
1868 ctlr->running = false;
1870 ctlr->queue_empty = true;
1872 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1873 if (IS_ERR(ctlr->kworker)) {
1874 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1875 return PTR_ERR(ctlr->kworker);
1878 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1881 * Controller config will indicate if this controller should run the
1882 * message pump with high (realtime) priority to reduce the transfer
1883 * latency on the bus by minimising the delay between a transfer
1884 * request and the scheduling of the message pump thread. Without this
1885 * setting the message pump thread will remain at default priority.
1888 spi_set_thread_rt(ctlr);
1894 * spi_get_next_queued_message() - called by driver to check for queued
1896 * @ctlr: the controller to check for queued messages
1898 * If there are more messages in the queue, the next message is returned from
1901 * Return: the next message in the queue, else NULL if the queue is empty.
1903 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1905 struct spi_message *next;
1906 unsigned long flags;
1908 /* Get a pointer to the next message, if any */
1909 spin_lock_irqsave(&ctlr->queue_lock, flags);
1910 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1912 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1916 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1919 * spi_finalize_current_message() - the current message is complete
1920 * @ctlr: the controller to return the message to
1922 * Called by the driver to notify the core that the message in the front of the
1923 * queue is complete and can be removed from the queue.
1925 void spi_finalize_current_message(struct spi_controller *ctlr)
1927 struct spi_transfer *xfer;
1928 struct spi_message *mesg;
1931 mesg = ctlr->cur_msg;
1933 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1934 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1935 ptp_read_system_postts(xfer->ptp_sts);
1936 xfer->ptp_sts_word_post = xfer->len;
1940 if (unlikely(ctlr->ptp_sts_supported))
1941 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1942 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1944 spi_unmap_msg(ctlr, mesg);
1947 * In the prepare_messages callback the SPI bus has the opportunity
1948 * to split a transfer to smaller chunks.
1950 * Release the split transfers here since spi_map_msg() is done on
1951 * the split transfers.
1953 spi_res_release(ctlr, mesg);
1955 if (mesg->prepared && ctlr->unprepare_message) {
1956 ret = ctlr->unprepare_message(ctlr, mesg);
1958 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1963 mesg->prepared = false;
1965 WRITE_ONCE(ctlr->cur_msg_incomplete, false);
1966 smp_mb(); /* See __spi_pump_transfer_message()... */
1967 if (READ_ONCE(ctlr->cur_msg_need_completion))
1968 complete(&ctlr->cur_msg_completion);
1970 trace_spi_message_done(mesg);
1974 mesg->complete(mesg->context);
1976 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1978 static int spi_start_queue(struct spi_controller *ctlr)
1980 unsigned long flags;
1982 spin_lock_irqsave(&ctlr->queue_lock, flags);
1984 if (ctlr->running || ctlr->busy) {
1985 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1989 ctlr->running = true;
1990 ctlr->cur_msg = NULL;
1991 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1993 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1998 static int spi_stop_queue(struct spi_controller *ctlr)
2000 unsigned long flags;
2001 unsigned limit = 500;
2004 spin_lock_irqsave(&ctlr->queue_lock, flags);
2007 * This is a bit lame, but is optimized for the common execution path.
2008 * A wait_queue on the ctlr->busy could be used, but then the common
2009 * execution path (pump_messages) would be required to call wake_up or
2010 * friends on every SPI message. Do this instead.
2012 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
2013 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2014 usleep_range(10000, 11000);
2015 spin_lock_irqsave(&ctlr->queue_lock, flags);
2018 if (!list_empty(&ctlr->queue) || ctlr->busy)
2021 ctlr->running = false;
2023 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2026 dev_warn(&ctlr->dev, "could not stop message queue\n");
2032 static int spi_destroy_queue(struct spi_controller *ctlr)
2036 ret = spi_stop_queue(ctlr);
2039 * kthread_flush_worker will block until all work is done.
2040 * If the reason that stop_queue timed out is that the work will never
2041 * finish, then it does no good to call flush/stop thread, so
2045 dev_err(&ctlr->dev, "problem destroying queue\n");
2049 kthread_destroy_worker(ctlr->kworker);
2054 static int __spi_queued_transfer(struct spi_device *spi,
2055 struct spi_message *msg,
2058 struct spi_controller *ctlr = spi->controller;
2059 unsigned long flags;
2061 spin_lock_irqsave(&ctlr->queue_lock, flags);
2063 if (!ctlr->running) {
2064 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2067 msg->actual_length = 0;
2068 msg->status = -EINPROGRESS;
2070 list_add_tail(&msg->queue, &ctlr->queue);
2071 ctlr->queue_empty = false;
2072 if (!ctlr->busy && need_pump)
2073 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2075 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2080 * spi_queued_transfer - transfer function for queued transfers
2081 * @spi: spi device which is requesting transfer
2082 * @msg: spi message which is to handled is queued to driver queue
2084 * Return: zero on success, else a negative error code.
2086 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
2088 return __spi_queued_transfer(spi, msg, true);
2091 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2095 ctlr->transfer = spi_queued_transfer;
2096 if (!ctlr->transfer_one_message)
2097 ctlr->transfer_one_message = spi_transfer_one_message;
2099 /* Initialize and start queue */
2100 ret = spi_init_queue(ctlr);
2102 dev_err(&ctlr->dev, "problem initializing queue\n");
2103 goto err_init_queue;
2105 ctlr->queued = true;
2106 ret = spi_start_queue(ctlr);
2108 dev_err(&ctlr->dev, "problem starting queue\n");
2109 goto err_start_queue;
2115 spi_destroy_queue(ctlr);
2121 * spi_flush_queue - Send all pending messages in the queue from the callers'
2123 * @ctlr: controller to process queue for
2125 * This should be used when one wants to ensure all pending messages have been
2126 * sent before doing something. Is used by the spi-mem code to make sure SPI
2127 * memory operations do not preempt regular SPI transfers that have been queued
2128 * before the spi-mem operation.
2130 void spi_flush_queue(struct spi_controller *ctlr)
2132 if (ctlr->transfer == spi_queued_transfer)
2133 __spi_pump_messages(ctlr, false);
2136 /*-------------------------------------------------------------------------*/
2138 #if defined(CONFIG_OF)
2139 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2140 struct device_node *nc)
2145 /* Mode (clock phase/polarity/etc.) */
2146 if (of_property_read_bool(nc, "spi-cpha"))
2147 spi->mode |= SPI_CPHA;
2148 if (of_property_read_bool(nc, "spi-cpol"))
2149 spi->mode |= SPI_CPOL;
2150 if (of_property_read_bool(nc, "spi-3wire"))
2151 spi->mode |= SPI_3WIRE;
2152 if (of_property_read_bool(nc, "spi-lsb-first"))
2153 spi->mode |= SPI_LSB_FIRST;
2154 if (of_property_read_bool(nc, "spi-cs-high"))
2155 spi->mode |= SPI_CS_HIGH;
2157 /* Device DUAL/QUAD mode */
2158 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2161 spi->mode |= SPI_NO_TX;
2166 spi->mode |= SPI_TX_DUAL;
2169 spi->mode |= SPI_TX_QUAD;
2172 spi->mode |= SPI_TX_OCTAL;
2175 dev_warn(&ctlr->dev,
2176 "spi-tx-bus-width %d not supported\n",
2182 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2185 spi->mode |= SPI_NO_RX;
2190 spi->mode |= SPI_RX_DUAL;
2193 spi->mode |= SPI_RX_QUAD;
2196 spi->mode |= SPI_RX_OCTAL;
2199 dev_warn(&ctlr->dev,
2200 "spi-rx-bus-width %d not supported\n",
2206 if (spi_controller_is_slave(ctlr)) {
2207 if (!of_node_name_eq(nc, "slave")) {
2208 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2215 /* Device address */
2216 rc = of_property_read_u32(nc, "reg", &value);
2218 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2222 spi->chip_select = value;
2225 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2226 spi->max_speed_hz = value;
2231 static struct spi_device *
2232 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2234 struct spi_device *spi;
2237 /* Alloc an spi_device */
2238 spi = spi_alloc_device(ctlr);
2240 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2245 /* Select device driver */
2246 rc = of_modalias_node(nc, spi->modalias,
2247 sizeof(spi->modalias));
2249 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2253 rc = of_spi_parse_dt(ctlr, spi, nc);
2257 /* Store a pointer to the node in the device structure */
2259 spi->dev.of_node = nc;
2260 spi->dev.fwnode = of_fwnode_handle(nc);
2262 /* Register the new device */
2263 rc = spi_add_device(spi);
2265 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2266 goto err_of_node_put;
2279 * of_register_spi_devices() - Register child devices onto the SPI bus
2280 * @ctlr: Pointer to spi_controller device
2282 * Registers an spi_device for each child node of controller node which
2283 * represents a valid SPI slave.
2285 static void of_register_spi_devices(struct spi_controller *ctlr)
2287 struct spi_device *spi;
2288 struct device_node *nc;
2290 if (!ctlr->dev.of_node)
2293 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2294 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2296 spi = of_register_spi_device(ctlr, nc);
2298 dev_warn(&ctlr->dev,
2299 "Failed to create SPI device for %pOF\n", nc);
2300 of_node_clear_flag(nc, OF_POPULATED);
2305 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2309 * spi_new_ancillary_device() - Register ancillary SPI device
2310 * @spi: Pointer to the main SPI device registering the ancillary device
2311 * @chip_select: Chip Select of the ancillary device
2313 * Register an ancillary SPI device; for example some chips have a chip-select
2314 * for normal device usage and another one for setup/firmware upload.
2316 * This may only be called from main SPI device's probe routine.
2318 * Return: 0 on success; negative errno on failure
2320 struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2323 struct spi_device *ancillary;
2326 /* Alloc an spi_device */
2327 ancillary = spi_alloc_device(spi->controller);
2333 strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2335 /* Use provided chip-select for ancillary device */
2336 ancillary->chip_select = chip_select;
2338 /* Take over SPI mode/speed from SPI main device */
2339 ancillary->max_speed_hz = spi->max_speed_hz;
2340 ancillary->mode = spi->mode;
2342 /* Register the new device */
2343 rc = spi_add_device_locked(ancillary);
2345 dev_err(&spi->dev, "failed to register ancillary device\n");
2352 spi_dev_put(ancillary);
2355 EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2358 struct acpi_spi_lookup {
2359 struct spi_controller *ctlr;
2369 static int acpi_spi_count(struct acpi_resource *ares, void *data)
2371 struct acpi_resource_spi_serialbus *sb;
2374 if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2377 sb = &ares->data.spi_serial_bus;
2378 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2381 *count = *count + 1;
2387 * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2388 * @adev: ACPI device
2390 * Returns the number of SpiSerialBus resources in the ACPI-device's
2391 * resource-list; or a negative error code.
2393 int acpi_spi_count_resources(struct acpi_device *adev)
2399 ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2403 acpi_dev_free_resource_list(&r);
2407 EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2409 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2410 struct acpi_spi_lookup *lookup)
2412 const union acpi_object *obj;
2414 if (!x86_apple_machine)
2417 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2418 && obj->buffer.length >= 4)
2419 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2421 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2422 && obj->buffer.length == 8)
2423 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2425 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2426 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2427 lookup->mode |= SPI_LSB_FIRST;
2429 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2430 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2431 lookup->mode |= SPI_CPOL;
2433 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2434 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2435 lookup->mode |= SPI_CPHA;
2438 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
2440 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2442 struct acpi_spi_lookup *lookup = data;
2443 struct spi_controller *ctlr = lookup->ctlr;
2445 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2446 struct acpi_resource_spi_serialbus *sb;
2447 acpi_handle parent_handle;
2450 sb = &ares->data.spi_serial_bus;
2451 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2453 if (lookup->index != -1 && lookup->n++ != lookup->index)
2456 status = acpi_get_handle(NULL,
2457 sb->resource_source.string_ptr,
2460 if (ACPI_FAILURE(status))
2464 if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2467 struct acpi_device *adev;
2469 adev = acpi_fetch_acpi_dev(parent_handle);
2473 ctlr = acpi_spi_find_controller_by_adev(adev);
2475 return -EPROBE_DEFER;
2477 lookup->ctlr = ctlr;
2481 * ACPI DeviceSelection numbering is handled by the
2482 * host controller driver in Windows and can vary
2483 * from driver to driver. In Linux we always expect
2484 * 0 .. max - 1 so we need to ask the driver to
2485 * translate between the two schemes.
2487 if (ctlr->fw_translate_cs) {
2488 int cs = ctlr->fw_translate_cs(ctlr,
2489 sb->device_selection);
2492 lookup->chip_select = cs;
2494 lookup->chip_select = sb->device_selection;
2497 lookup->max_speed_hz = sb->connection_speed;
2498 lookup->bits_per_word = sb->data_bit_length;
2500 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2501 lookup->mode |= SPI_CPHA;
2502 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2503 lookup->mode |= SPI_CPOL;
2504 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2505 lookup->mode |= SPI_CS_HIGH;
2507 } else if (lookup->irq < 0) {
2510 if (acpi_dev_resource_interrupt(ares, 0, &r))
2511 lookup->irq = r.start;
2514 /* Always tell the ACPI core to skip this resource */
2519 * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2520 * @ctlr: controller to which the spi device belongs
2521 * @adev: ACPI Device for the spi device
2522 * @index: Index of the spi resource inside the ACPI Node
2524 * This should be used to allocate a new spi device from and ACPI Node.
2525 * The caller is responsible for calling spi_add_device to register the spi device.
2527 * If ctlr is set to NULL, the Controller for the spi device will be looked up
2528 * using the resource.
2529 * If index is set to -1, index is not used.
2530 * Note: If index is -1, ctlr must be set.
2532 * Return: a pointer to the new device, or ERR_PTR on error.
2534 struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
2535 struct acpi_device *adev,
2538 acpi_handle parent_handle = NULL;
2539 struct list_head resource_list;
2540 struct acpi_spi_lookup lookup = {};
2541 struct spi_device *spi;
2544 if (!ctlr && index == -1)
2545 return ERR_PTR(-EINVAL);
2549 lookup.index = index;
2552 INIT_LIST_HEAD(&resource_list);
2553 ret = acpi_dev_get_resources(adev, &resource_list,
2554 acpi_spi_add_resource, &lookup);
2555 acpi_dev_free_resource_list(&resource_list);
2558 /* Found SPI in _CRS but it points to another controller */
2559 return ERR_PTR(ret);
2561 if (!lookup.max_speed_hz &&
2562 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2563 ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
2564 /* Apple does not use _CRS but nested devices for SPI slaves */
2565 acpi_spi_parse_apple_properties(adev, &lookup);
2568 if (!lookup.max_speed_hz)
2569 return ERR_PTR(-ENODEV);
2571 spi = spi_alloc_device(lookup.ctlr);
2573 dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
2574 dev_name(&adev->dev));
2575 return ERR_PTR(-ENOMEM);
2578 ACPI_COMPANION_SET(&spi->dev, adev);
2579 spi->max_speed_hz = lookup.max_speed_hz;
2580 spi->mode |= lookup.mode;
2581 spi->irq = lookup.irq;
2582 spi->bits_per_word = lookup.bits_per_word;
2583 spi->chip_select = lookup.chip_select;
2587 EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2589 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2590 struct acpi_device *adev)
2592 struct spi_device *spi;
2594 if (acpi_bus_get_status(adev) || !adev->status.present ||
2595 acpi_device_enumerated(adev))
2598 spi = acpi_spi_device_alloc(ctlr, adev, -1);
2600 if (PTR_ERR(spi) == -ENOMEM)
2601 return AE_NO_MEMORY;
2606 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2607 sizeof(spi->modalias));
2610 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2612 acpi_device_set_enumerated(adev);
2614 adev->power.flags.ignore_parent = true;
2615 if (spi_add_device(spi)) {
2616 adev->power.flags.ignore_parent = false;
2617 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2618 dev_name(&adev->dev));
2625 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2626 void *data, void **return_value)
2628 struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
2629 struct spi_controller *ctlr = data;
2634 return acpi_register_spi_device(ctlr, adev);
2637 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2639 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2644 handle = ACPI_HANDLE(ctlr->dev.parent);
2648 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2649 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2650 acpi_spi_add_device, NULL, ctlr, NULL);
2651 if (ACPI_FAILURE(status))
2652 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2655 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2656 #endif /* CONFIG_ACPI */
2658 static void spi_controller_release(struct device *dev)
2660 struct spi_controller *ctlr;
2662 ctlr = container_of(dev, struct spi_controller, dev);
2666 static struct class spi_master_class = {
2667 .name = "spi_master",
2668 .owner = THIS_MODULE,
2669 .dev_release = spi_controller_release,
2670 .dev_groups = spi_master_groups,
2673 #ifdef CONFIG_SPI_SLAVE
2675 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2677 * @spi: device used for the current transfer
2679 int spi_slave_abort(struct spi_device *spi)
2681 struct spi_controller *ctlr = spi->controller;
2683 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2684 return ctlr->slave_abort(ctlr);
2688 EXPORT_SYMBOL_GPL(spi_slave_abort);
2690 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2693 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2695 struct device *child;
2697 child = device_find_any_child(&ctlr->dev);
2698 return sprintf(buf, "%s\n",
2699 child ? to_spi_device(child)->modalias : NULL);
2702 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2703 const char *buf, size_t count)
2705 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2707 struct spi_device *spi;
2708 struct device *child;
2712 rc = sscanf(buf, "%31s", name);
2713 if (rc != 1 || !name[0])
2716 child = device_find_any_child(&ctlr->dev);
2718 /* Remove registered slave */
2719 device_unregister(child);
2723 if (strcmp(name, "(null)")) {
2724 /* Register new slave */
2725 spi = spi_alloc_device(ctlr);
2729 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2731 rc = spi_add_device(spi);
2741 static DEVICE_ATTR_RW(slave);
2743 static struct attribute *spi_slave_attrs[] = {
2744 &dev_attr_slave.attr,
2748 static const struct attribute_group spi_slave_group = {
2749 .attrs = spi_slave_attrs,
2752 static const struct attribute_group *spi_slave_groups[] = {
2753 &spi_controller_statistics_group,
2758 static struct class spi_slave_class = {
2759 .name = "spi_slave",
2760 .owner = THIS_MODULE,
2761 .dev_release = spi_controller_release,
2762 .dev_groups = spi_slave_groups,
2765 extern struct class spi_slave_class; /* dummy */
2769 * __spi_alloc_controller - allocate an SPI master or slave controller
2770 * @dev: the controller, possibly using the platform_bus
2771 * @size: how much zeroed driver-private data to allocate; the pointer to this
2772 * memory is in the driver_data field of the returned device, accessible
2773 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2774 * drivers granting DMA access to portions of their private data need to
2775 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2776 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2777 * slave (true) controller
2778 * Context: can sleep
2780 * This call is used only by SPI controller drivers, which are the
2781 * only ones directly touching chip registers. It's how they allocate
2782 * an spi_controller structure, prior to calling spi_register_controller().
2784 * This must be called from context that can sleep.
2786 * The caller is responsible for assigning the bus number and initializing the
2787 * controller's methods before calling spi_register_controller(); and (after
2788 * errors adding the device) calling spi_controller_put() to prevent a memory
2791 * Return: the SPI controller structure on success, else NULL.
2793 struct spi_controller *__spi_alloc_controller(struct device *dev,
2794 unsigned int size, bool slave)
2796 struct spi_controller *ctlr;
2797 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2802 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2806 device_initialize(&ctlr->dev);
2807 INIT_LIST_HEAD(&ctlr->queue);
2808 spin_lock_init(&ctlr->queue_lock);
2809 spin_lock_init(&ctlr->bus_lock_spinlock);
2810 mutex_init(&ctlr->bus_lock_mutex);
2811 mutex_init(&ctlr->io_mutex);
2812 mutex_init(&ctlr->add_lock);
2814 ctlr->num_chipselect = 1;
2815 ctlr->slave = slave;
2816 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2817 ctlr->dev.class = &spi_slave_class;
2819 ctlr->dev.class = &spi_master_class;
2820 ctlr->dev.parent = dev;
2821 pm_suspend_ignore_children(&ctlr->dev, true);
2822 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2826 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2828 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2830 spi_controller_put(*(struct spi_controller **)ctlr);
2834 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2835 * @dev: physical device of SPI controller
2836 * @size: how much zeroed driver-private data to allocate
2837 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2838 * Context: can sleep
2840 * Allocate an SPI controller and automatically release a reference on it
2841 * when @dev is unbound from its driver. Drivers are thus relieved from
2842 * having to call spi_controller_put().
2844 * The arguments to this function are identical to __spi_alloc_controller().
2846 * Return: the SPI controller structure on success, else NULL.
2848 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2852 struct spi_controller **ptr, *ctlr;
2854 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2859 ctlr = __spi_alloc_controller(dev, size, slave);
2861 ctlr->devm_allocated = true;
2863 devres_add(dev, ptr);
2870 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2873 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2874 * @ctlr: The SPI master to grab GPIO descriptors for
2876 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2879 struct gpio_desc **cs;
2880 struct device *dev = &ctlr->dev;
2881 unsigned long native_cs_mask = 0;
2882 unsigned int num_cs_gpios = 0;
2884 nb = gpiod_count(dev, "cs");
2886 /* No GPIOs at all is fine, else return the error */
2892 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2894 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2898 ctlr->cs_gpiods = cs;
2900 for (i = 0; i < nb; i++) {
2902 * Most chipselects are active low, the inverted
2903 * semantics are handled by special quirks in gpiolib,
2904 * so initializing them GPIOD_OUT_LOW here means
2905 * "unasserted", in most cases this will drive the physical
2908 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2911 return PTR_ERR(cs[i]);
2915 * If we find a CS GPIO, name it after the device and
2920 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2924 gpiod_set_consumer_name(cs[i], gpioname);
2929 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2930 dev_err(dev, "Invalid native chip select %d\n", i);
2933 native_cs_mask |= BIT(i);
2936 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2938 if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2939 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2940 dev_err(dev, "No unused native chip select available\n");
2947 static int spi_controller_check_ops(struct spi_controller *ctlr)
2950 * The controller may implement only the high-level SPI-memory like
2951 * operations if it does not support regular SPI transfers, and this is
2953 * If ->mem_ops is NULL, we request that at least one of the
2954 * ->transfer_xxx() method be implemented.
2956 if (ctlr->mem_ops) {
2957 if (!ctlr->mem_ops->exec_op)
2959 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2960 !ctlr->transfer_one_message) {
2968 * spi_register_controller - register SPI master or slave controller
2969 * @ctlr: initialized master, originally from spi_alloc_master() or
2971 * Context: can sleep
2973 * SPI controllers connect to their drivers using some non-SPI bus,
2974 * such as the platform bus. The final stage of probe() in that code
2975 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2977 * SPI controllers use board specific (often SOC specific) bus numbers,
2978 * and board-specific addressing for SPI devices combines those numbers
2979 * with chip select numbers. Since SPI does not directly support dynamic
2980 * device identification, boards need configuration tables telling which
2981 * chip is at which address.
2983 * This must be called from context that can sleep. It returns zero on
2984 * success, else a negative error code (dropping the controller's refcount).
2985 * After a successful return, the caller is responsible for calling
2986 * spi_unregister_controller().
2988 * Return: zero on success, else a negative error code.
2990 int spi_register_controller(struct spi_controller *ctlr)
2992 struct device *dev = ctlr->dev.parent;
2993 struct boardinfo *bi;
2995 int id, first_dynamic;
3001 * Make sure all necessary hooks are implemented before registering
3002 * the SPI controller.
3004 status = spi_controller_check_ops(ctlr);
3008 if (ctlr->bus_num >= 0) {
3009 /* Devices with a fixed bus num must check-in with the num */
3010 mutex_lock(&board_lock);
3011 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
3012 ctlr->bus_num + 1, GFP_KERNEL);
3013 mutex_unlock(&board_lock);
3014 if (WARN(id < 0, "couldn't get idr"))
3015 return id == -ENOSPC ? -EBUSY : id;
3017 } else if (ctlr->dev.of_node) {
3018 /* Allocate dynamic bus number using Linux idr */
3019 id = of_alias_get_id(ctlr->dev.of_node, "spi");
3022 mutex_lock(&board_lock);
3023 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
3024 ctlr->bus_num + 1, GFP_KERNEL);
3025 mutex_unlock(&board_lock);
3026 if (WARN(id < 0, "couldn't get idr"))
3027 return id == -ENOSPC ? -EBUSY : id;
3030 if (ctlr->bus_num < 0) {
3031 first_dynamic = of_alias_get_highest_id("spi");
3032 if (first_dynamic < 0)
3037 mutex_lock(&board_lock);
3038 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
3040 mutex_unlock(&board_lock);
3041 if (WARN(id < 0, "couldn't get idr"))
3045 ctlr->bus_lock_flag = 0;
3046 init_completion(&ctlr->xfer_completion);
3047 init_completion(&ctlr->cur_msg_completion);
3048 if (!ctlr->max_dma_len)
3049 ctlr->max_dma_len = INT_MAX;
3052 * Register the device, then userspace will see it.
3053 * Registration fails if the bus ID is in use.
3055 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
3057 if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
3058 status = spi_get_gpio_descs(ctlr);
3062 * A controller using GPIO descriptors always
3063 * supports SPI_CS_HIGH if need be.
3065 ctlr->mode_bits |= SPI_CS_HIGH;
3069 * Even if it's just one always-selected device, there must
3070 * be at least one chipselect.
3072 if (!ctlr->num_chipselect) {
3077 /* Setting last_cs to -1 means no chip selected */
3080 status = device_add(&ctlr->dev);
3083 dev_dbg(dev, "registered %s %s\n",
3084 spi_controller_is_slave(ctlr) ? "slave" : "master",
3085 dev_name(&ctlr->dev));
3088 * If we're using a queued driver, start the queue. Note that we don't
3089 * need the queueing logic if the driver is only supporting high-level
3090 * memory operations.
3092 if (ctlr->transfer) {
3093 dev_info(dev, "controller is unqueued, this is deprecated\n");
3094 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
3095 status = spi_controller_initialize_queue(ctlr);
3097 device_del(&ctlr->dev);
3101 /* Add statistics */
3102 ctlr->pcpu_statistics = spi_alloc_pcpu_stats(dev);
3103 if (!ctlr->pcpu_statistics) {
3104 dev_err(dev, "Error allocating per-cpu statistics\n");
3109 mutex_lock(&board_lock);
3110 list_add_tail(&ctlr->list, &spi_controller_list);
3111 list_for_each_entry(bi, &board_list, list)
3112 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
3113 mutex_unlock(&board_lock);
3115 /* Register devices from the device tree and ACPI */
3116 of_register_spi_devices(ctlr);
3117 acpi_register_spi_devices(ctlr);
3121 spi_destroy_queue(ctlr);
3123 mutex_lock(&board_lock);
3124 idr_remove(&spi_master_idr, ctlr->bus_num);
3125 mutex_unlock(&board_lock);
3128 EXPORT_SYMBOL_GPL(spi_register_controller);
3130 static void devm_spi_unregister(struct device *dev, void *res)
3132 spi_unregister_controller(*(struct spi_controller **)res);
3136 * devm_spi_register_controller - register managed SPI master or slave
3138 * @dev: device managing SPI controller
3139 * @ctlr: initialized controller, originally from spi_alloc_master() or
3141 * Context: can sleep
3143 * Register a SPI device as with spi_register_controller() which will
3144 * automatically be unregistered and freed.
3146 * Return: zero on success, else a negative error code.
3148 int devm_spi_register_controller(struct device *dev,
3149 struct spi_controller *ctlr)
3151 struct spi_controller **ptr;
3154 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
3158 ret = spi_register_controller(ctlr);
3161 devres_add(dev, ptr);
3168 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3170 static int __unregister(struct device *dev, void *null)
3172 spi_unregister_device(to_spi_device(dev));
3177 * spi_unregister_controller - unregister SPI master or slave controller
3178 * @ctlr: the controller being unregistered
3179 * Context: can sleep
3181 * This call is used only by SPI controller drivers, which are the
3182 * only ones directly touching chip registers.
3184 * This must be called from context that can sleep.
3186 * Note that this function also drops a reference to the controller.
3188 void spi_unregister_controller(struct spi_controller *ctlr)
3190 struct spi_controller *found;
3191 int id = ctlr->bus_num;
3193 /* Prevent addition of new devices, unregister existing ones */
3194 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3195 mutex_lock(&ctlr->add_lock);
3197 device_for_each_child(&ctlr->dev, NULL, __unregister);
3199 /* First make sure that this controller was ever added */
3200 mutex_lock(&board_lock);
3201 found = idr_find(&spi_master_idr, id);
3202 mutex_unlock(&board_lock);
3204 if (spi_destroy_queue(ctlr))
3205 dev_err(&ctlr->dev, "queue remove failed\n");
3207 mutex_lock(&board_lock);
3208 list_del(&ctlr->list);
3209 mutex_unlock(&board_lock);
3211 device_del(&ctlr->dev);
3214 mutex_lock(&board_lock);
3216 idr_remove(&spi_master_idr, id);
3217 mutex_unlock(&board_lock);
3219 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3220 mutex_unlock(&ctlr->add_lock);
3222 /* Release the last reference on the controller if its driver
3223 * has not yet been converted to devm_spi_alloc_master/slave().
3225 if (!ctlr->devm_allocated)
3226 put_device(&ctlr->dev);
3228 EXPORT_SYMBOL_GPL(spi_unregister_controller);
3230 int spi_controller_suspend(struct spi_controller *ctlr)
3234 /* Basically no-ops for non-queued controllers */
3238 ret = spi_stop_queue(ctlr);
3240 dev_err(&ctlr->dev, "queue stop failed\n");
3244 EXPORT_SYMBOL_GPL(spi_controller_suspend);
3246 int spi_controller_resume(struct spi_controller *ctlr)
3253 ret = spi_start_queue(ctlr);
3255 dev_err(&ctlr->dev, "queue restart failed\n");
3259 EXPORT_SYMBOL_GPL(spi_controller_resume);
3261 /*-------------------------------------------------------------------------*/
3263 /* Core methods for spi_message alterations */
3265 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3266 struct spi_message *msg,
3269 struct spi_replaced_transfers *rxfer = res;
3272 /* Call extra callback if requested */
3274 rxfer->release(ctlr, msg, res);
3276 /* Insert replaced transfers back into the message */
3277 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3279 /* Remove the formerly inserted entries */
3280 for (i = 0; i < rxfer->inserted; i++)
3281 list_del(&rxfer->inserted_transfers[i].transfer_list);
3285 * spi_replace_transfers - replace transfers with several transfers
3286 * and register change with spi_message.resources
3287 * @msg: the spi_message we work upon
3288 * @xfer_first: the first spi_transfer we want to replace
3289 * @remove: number of transfers to remove
3290 * @insert: the number of transfers we want to insert instead
3291 * @release: extra release code necessary in some circumstances
3292 * @extradatasize: extra data to allocate (with alignment guarantees
3293 * of struct @spi_transfer)
3296 * Returns: pointer to @spi_replaced_transfers,
3297 * PTR_ERR(...) in case of errors.
3299 static struct spi_replaced_transfers *spi_replace_transfers(
3300 struct spi_message *msg,
3301 struct spi_transfer *xfer_first,
3304 spi_replaced_release_t release,
3305 size_t extradatasize,
3308 struct spi_replaced_transfers *rxfer;
3309 struct spi_transfer *xfer;
3312 /* Allocate the structure using spi_res */
3313 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3314 struct_size(rxfer, inserted_transfers, insert)
3318 return ERR_PTR(-ENOMEM);
3320 /* The release code to invoke before running the generic release */
3321 rxfer->release = release;
3323 /* Assign extradata */
3326 &rxfer->inserted_transfers[insert];
3328 /* Init the replaced_transfers list */
3329 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3332 * Assign the list_entry after which we should reinsert
3333 * the @replaced_transfers - it may be spi_message.messages!
3335 rxfer->replaced_after = xfer_first->transfer_list.prev;
3337 /* Remove the requested number of transfers */
3338 for (i = 0; i < remove; i++) {
3340 * If the entry after replaced_after it is msg->transfers
3341 * then we have been requested to remove more transfers
3342 * than are in the list.
3344 if (rxfer->replaced_after->next == &msg->transfers) {
3345 dev_err(&msg->spi->dev,
3346 "requested to remove more spi_transfers than are available\n");
3347 /* Insert replaced transfers back into the message */
3348 list_splice(&rxfer->replaced_transfers,
3349 rxfer->replaced_after);
3351 /* Free the spi_replace_transfer structure... */
3352 spi_res_free(rxfer);
3354 /* ...and return with an error */
3355 return ERR_PTR(-EINVAL);
3359 * Remove the entry after replaced_after from list of
3360 * transfers and add it to list of replaced_transfers.
3362 list_move_tail(rxfer->replaced_after->next,
3363 &rxfer->replaced_transfers);
3367 * Create copy of the given xfer with identical settings
3368 * based on the first transfer to get removed.
3370 for (i = 0; i < insert; i++) {
3371 /* We need to run in reverse order */
3372 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3374 /* Copy all spi_transfer data */
3375 memcpy(xfer, xfer_first, sizeof(*xfer));
3378 list_add(&xfer->transfer_list, rxfer->replaced_after);
3380 /* Clear cs_change and delay for all but the last */
3382 xfer->cs_change = false;
3383 xfer->delay.value = 0;
3387 /* Set up inserted... */
3388 rxfer->inserted = insert;
3390 /* ...and register it with spi_res/spi_message */
3391 spi_res_add(msg, rxfer);
3396 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3397 struct spi_message *msg,
3398 struct spi_transfer **xferp,
3402 struct spi_transfer *xfer = *xferp, *xfers;
3403 struct spi_replaced_transfers *srt;
3407 /* Calculate how many we have to replace */
3408 count = DIV_ROUND_UP(xfer->len, maxsize);
3410 /* Create replacement */
3411 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3413 return PTR_ERR(srt);
3414 xfers = srt->inserted_transfers;
3417 * Now handle each of those newly inserted spi_transfers.
3418 * Note that the replacements spi_transfers all are preset
3419 * to the same values as *xferp, so tx_buf, rx_buf and len
3420 * are all identical (as well as most others)
3421 * so we just have to fix up len and the pointers.
3423 * This also includes support for the depreciated
3424 * spi_message.is_dma_mapped interface.
3428 * The first transfer just needs the length modified, so we
3429 * run it outside the loop.
3431 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3433 /* All the others need rx_buf/tx_buf also set */
3434 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3435 /* Update rx_buf, tx_buf and dma */
3436 if (xfers[i].rx_buf)
3437 xfers[i].rx_buf += offset;
3438 if (xfers[i].rx_dma)
3439 xfers[i].rx_dma += offset;
3440 if (xfers[i].tx_buf)
3441 xfers[i].tx_buf += offset;
3442 if (xfers[i].tx_dma)
3443 xfers[i].tx_dma += offset;
3446 xfers[i].len = min(maxsize, xfers[i].len - offset);
3450 * We set up xferp to the last entry we have inserted,
3451 * so that we skip those already split transfers.
3453 *xferp = &xfers[count - 1];
3455 /* Increment statistics counters */
3456 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics,
3457 transfers_split_maxsize);
3458 SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics,
3459 transfers_split_maxsize);
3465 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3466 * when an individual transfer exceeds a
3468 * @ctlr: the @spi_controller for this transfer
3469 * @msg: the @spi_message to transform
3470 * @maxsize: the maximum when to apply this
3471 * @gfp: GFP allocation flags
3473 * Return: status of transformation
3475 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3476 struct spi_message *msg,
3480 struct spi_transfer *xfer;
3484 * Iterate over the transfer_list,
3485 * but note that xfer is advanced to the last transfer inserted
3486 * to avoid checking sizes again unnecessarily (also xfer does
3487 * potentially belong to a different list by the time the
3488 * replacement has happened).
3490 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3491 if (xfer->len > maxsize) {
3492 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3501 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3503 /*-------------------------------------------------------------------------*/
3505 /* Core methods for SPI controller protocol drivers. Some of the
3506 * other core methods are currently defined as inline functions.
3509 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3512 if (ctlr->bits_per_word_mask) {
3513 /* Only 32 bits fit in the mask */
3514 if (bits_per_word > 32)
3516 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3524 * spi_setup - setup SPI mode and clock rate
3525 * @spi: the device whose settings are being modified
3526 * Context: can sleep, and no requests are queued to the device
3528 * SPI protocol drivers may need to update the transfer mode if the
3529 * device doesn't work with its default. They may likewise need
3530 * to update clock rates or word sizes from initial values. This function
3531 * changes those settings, and must be called from a context that can sleep.
3532 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3533 * effect the next time the device is selected and data is transferred to
3534 * or from it. When this function returns, the spi device is deselected.
3536 * Note that this call will fail if the protocol driver specifies an option
3537 * that the underlying controller or its driver does not support. For
3538 * example, not all hardware supports wire transfers using nine bit words,
3539 * LSB-first wire encoding, or active-high chipselects.
3541 * Return: zero on success, else a negative error code.
3543 int spi_setup(struct spi_device *spi)
3545 unsigned bad_bits, ugly_bits;
3549 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3550 * are set at the same time.
3552 if ((hweight_long(spi->mode &
3553 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3554 (hweight_long(spi->mode &
3555 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3557 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3560 /* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3561 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3562 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3563 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3566 * Help drivers fail *cleanly* when they need options
3567 * that aren't supported with their current controller.
3568 * SPI_CS_WORD has a fallback software implementation,
3569 * so it is ignored here.
3571 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3572 SPI_NO_TX | SPI_NO_RX);
3573 ugly_bits = bad_bits &
3574 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3575 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3578 "setup: ignoring unsupported mode bits %x\n",
3580 spi->mode &= ~ugly_bits;
3581 bad_bits &= ~ugly_bits;
3584 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3589 if (!spi->bits_per_word) {
3590 spi->bits_per_word = 8;
3593 * Some controllers may not support the default 8 bits-per-word
3594 * so only perform the check when this is explicitly provided.
3596 status = __spi_validate_bits_per_word(spi->controller,
3597 spi->bits_per_word);
3602 if (spi->controller->max_speed_hz &&
3603 (!spi->max_speed_hz ||
3604 spi->max_speed_hz > spi->controller->max_speed_hz))
3605 spi->max_speed_hz = spi->controller->max_speed_hz;
3607 mutex_lock(&spi->controller->io_mutex);
3609 if (spi->controller->setup) {
3610 status = spi->controller->setup(spi);
3612 mutex_unlock(&spi->controller->io_mutex);
3613 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3619 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3620 status = pm_runtime_resume_and_get(spi->controller->dev.parent);
3622 mutex_unlock(&spi->controller->io_mutex);
3623 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3629 * We do not want to return positive value from pm_runtime_get,
3630 * there are many instances of devices calling spi_setup() and
3631 * checking for a non-zero return value instead of a negative
3636 spi_set_cs(spi, false, true);
3637 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3638 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3640 spi_set_cs(spi, false, true);
3643 mutex_unlock(&spi->controller->io_mutex);
3645 if (spi->rt && !spi->controller->rt) {
3646 spi->controller->rt = true;
3647 spi_set_thread_rt(spi->controller);
3650 trace_spi_setup(spi, status);
3652 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3653 spi->mode & SPI_MODE_X_MASK,
3654 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3655 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3656 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3657 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3658 spi->bits_per_word, spi->max_speed_hz,
3663 EXPORT_SYMBOL_GPL(spi_setup);
3665 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3666 struct spi_device *spi)
3670 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3674 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3678 if (delay1 < delay2)
3679 memcpy(&xfer->word_delay, &spi->word_delay,
3680 sizeof(xfer->word_delay));
3685 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3687 struct spi_controller *ctlr = spi->controller;
3688 struct spi_transfer *xfer;
3691 if (list_empty(&message->transfers))
3695 * If an SPI controller does not support toggling the CS line on each
3696 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3697 * for the CS line, we can emulate the CS-per-word hardware function by
3698 * splitting transfers into one-word transfers and ensuring that
3699 * cs_change is set for each transfer.
3701 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3706 maxsize = (spi->bits_per_word + 7) / 8;
3708 /* spi_split_transfers_maxsize() requires message->spi */
3711 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3716 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3717 /* Don't change cs_change on the last entry in the list */
3718 if (list_is_last(&xfer->transfer_list, &message->transfers))
3720 xfer->cs_change = 1;
3725 * Half-duplex links include original MicroWire, and ones with
3726 * only one data pin like SPI_3WIRE (switches direction) or where
3727 * either MOSI or MISO is missing. They can also be caused by
3728 * software limitations.
3730 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3731 (spi->mode & SPI_3WIRE)) {
3732 unsigned flags = ctlr->flags;
3734 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3735 if (xfer->rx_buf && xfer->tx_buf)
3737 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3739 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3745 * Set transfer bits_per_word and max speed as spi device default if
3746 * it is not set for this transfer.
3747 * Set transfer tx_nbits and rx_nbits as single transfer default
3748 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3749 * Ensure transfer word_delay is at least as long as that required by
3752 message->frame_length = 0;
3753 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3754 xfer->effective_speed_hz = 0;
3755 message->frame_length += xfer->len;
3756 if (!xfer->bits_per_word)
3757 xfer->bits_per_word = spi->bits_per_word;
3759 if (!xfer->speed_hz)
3760 xfer->speed_hz = spi->max_speed_hz;
3762 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3763 xfer->speed_hz = ctlr->max_speed_hz;
3765 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3769 * SPI transfer length should be multiple of SPI word size
3770 * where SPI word size should be power-of-two multiple.
3772 if (xfer->bits_per_word <= 8)
3774 else if (xfer->bits_per_word <= 16)
3779 /* No partial transfers accepted */
3780 if (xfer->len % w_size)
3783 if (xfer->speed_hz && ctlr->min_speed_hz &&
3784 xfer->speed_hz < ctlr->min_speed_hz)
3787 if (xfer->tx_buf && !xfer->tx_nbits)
3788 xfer->tx_nbits = SPI_NBITS_SINGLE;
3789 if (xfer->rx_buf && !xfer->rx_nbits)
3790 xfer->rx_nbits = SPI_NBITS_SINGLE;
3792 * Check transfer tx/rx_nbits:
3793 * 1. check the value matches one of single, dual and quad
3794 * 2. check tx/rx_nbits match the mode in spi_device
3797 if (spi->mode & SPI_NO_TX)
3799 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3800 xfer->tx_nbits != SPI_NBITS_DUAL &&
3801 xfer->tx_nbits != SPI_NBITS_QUAD)
3803 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3804 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3806 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3807 !(spi->mode & SPI_TX_QUAD))
3810 /* Check transfer rx_nbits */
3812 if (spi->mode & SPI_NO_RX)
3814 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3815 xfer->rx_nbits != SPI_NBITS_DUAL &&
3816 xfer->rx_nbits != SPI_NBITS_QUAD)
3818 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3819 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3821 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3822 !(spi->mode & SPI_RX_QUAD))
3826 if (_spi_xfer_word_delay_update(xfer, spi))
3830 message->status = -EINPROGRESS;
3835 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3837 struct spi_controller *ctlr = spi->controller;
3838 struct spi_transfer *xfer;
3841 * Some controllers do not support doing regular SPI transfers. Return
3842 * ENOTSUPP when this is the case.
3844 if (!ctlr->transfer)
3849 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async);
3850 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async);
3852 trace_spi_message_submit(message);
3854 if (!ctlr->ptp_sts_supported) {
3855 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3856 xfer->ptp_sts_word_pre = 0;
3857 ptp_read_system_prets(xfer->ptp_sts);
3861 return ctlr->transfer(spi, message);
3865 * spi_async - asynchronous SPI transfer
3866 * @spi: device with which data will be exchanged
3867 * @message: describes the data transfers, including completion callback
3868 * Context: any (irqs may be blocked, etc)
3870 * This call may be used in_irq and other contexts which can't sleep,
3871 * as well as from task contexts which can sleep.
3873 * The completion callback is invoked in a context which can't sleep.
3874 * Before that invocation, the value of message->status is undefined.
3875 * When the callback is issued, message->status holds either zero (to
3876 * indicate complete success) or a negative error code. After that
3877 * callback returns, the driver which issued the transfer request may
3878 * deallocate the associated memory; it's no longer in use by any SPI
3879 * core or controller driver code.
3881 * Note that although all messages to a spi_device are handled in
3882 * FIFO order, messages may go to different devices in other orders.
3883 * Some device might be higher priority, or have various "hard" access
3884 * time requirements, for example.
3886 * On detection of any fault during the transfer, processing of
3887 * the entire message is aborted, and the device is deselected.
3888 * Until returning from the associated message completion callback,
3889 * no other spi_message queued to that device will be processed.
3890 * (This rule applies equally to all the synchronous transfer calls,
3891 * which are wrappers around this core asynchronous primitive.)
3893 * Return: zero on success, else a negative error code.
3895 int spi_async(struct spi_device *spi, struct spi_message *message)
3897 struct spi_controller *ctlr = spi->controller;
3899 unsigned long flags;
3901 ret = __spi_validate(spi, message);
3905 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3907 if (ctlr->bus_lock_flag)
3910 ret = __spi_async(spi, message);
3912 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3916 EXPORT_SYMBOL_GPL(spi_async);
3919 * spi_async_locked - version of spi_async with exclusive bus usage
3920 * @spi: device with which data will be exchanged
3921 * @message: describes the data transfers, including completion callback
3922 * Context: any (irqs may be blocked, etc)
3924 * This call may be used in_irq and other contexts which can't sleep,
3925 * as well as from task contexts which can sleep.
3927 * The completion callback is invoked in a context which can't sleep.
3928 * Before that invocation, the value of message->status is undefined.
3929 * When the callback is issued, message->status holds either zero (to
3930 * indicate complete success) or a negative error code. After that
3931 * callback returns, the driver which issued the transfer request may
3932 * deallocate the associated memory; it's no longer in use by any SPI
3933 * core or controller driver code.
3935 * Note that although all messages to a spi_device are handled in
3936 * FIFO order, messages may go to different devices in other orders.
3937 * Some device might be higher priority, or have various "hard" access
3938 * time requirements, for example.
3940 * On detection of any fault during the transfer, processing of
3941 * the entire message is aborted, and the device is deselected.
3942 * Until returning from the associated message completion callback,
3943 * no other spi_message queued to that device will be processed.
3944 * (This rule applies equally to all the synchronous transfer calls,
3945 * which are wrappers around this core asynchronous primitive.)
3947 * Return: zero on success, else a negative error code.
3949 static int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3951 struct spi_controller *ctlr = spi->controller;
3953 unsigned long flags;
3955 ret = __spi_validate(spi, message);
3959 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3961 ret = __spi_async(spi, message);
3963 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3969 static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg)
3974 mutex_lock(&ctlr->io_mutex);
3976 was_busy = ctlr->busy;
3978 ctlr->cur_msg = msg;
3979 ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
3983 ctlr->cur_msg = NULL;
3984 ctlr->fallback = false;
3987 kfree(ctlr->dummy_rx);
3988 ctlr->dummy_rx = NULL;
3989 kfree(ctlr->dummy_tx);
3990 ctlr->dummy_tx = NULL;
3991 if (ctlr->unprepare_transfer_hardware &&
3992 ctlr->unprepare_transfer_hardware(ctlr))
3994 "failed to unprepare transfer hardware\n");
3995 spi_idle_runtime_pm(ctlr);
3999 mutex_unlock(&ctlr->io_mutex);
4002 /*-------------------------------------------------------------------------*/
4005 * Utility methods for SPI protocol drivers, layered on
4006 * top of the core. Some other utility methods are defined as
4010 static void spi_complete(void *arg)
4015 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
4017 DECLARE_COMPLETION_ONSTACK(done);
4019 struct spi_controller *ctlr = spi->controller;
4021 status = __spi_validate(spi, message);
4027 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync);
4028 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync);
4031 * Checking queue_empty here only guarantees async/sync message
4032 * ordering when coming from the same context. It does not need to
4033 * guard against reentrancy from a different context. The io_mutex
4034 * will catch those cases.
4036 if (READ_ONCE(ctlr->queue_empty)) {
4037 message->actual_length = 0;
4038 message->status = -EINPROGRESS;
4040 trace_spi_message_submit(message);
4042 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate);
4043 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate);
4045 __spi_transfer_message_noqueue(ctlr, message);
4047 return message->status;
4051 * There are messages in the async queue that could have originated
4052 * from the same context, so we need to preserve ordering.
4053 * Therefor we send the message to the async queue and wait until they
4056 message->complete = spi_complete;
4057 message->context = &done;
4058 status = spi_async_locked(spi, message);
4060 wait_for_completion(&done);
4061 status = message->status;
4063 message->context = NULL;
4069 * spi_sync - blocking/synchronous SPI data transfers
4070 * @spi: device with which data will be exchanged
4071 * @message: describes the data transfers
4072 * Context: can sleep
4074 * This call may only be used from a context that may sleep. The sleep
4075 * is non-interruptible, and has no timeout. Low-overhead controller
4076 * drivers may DMA directly into and out of the message buffers.
4078 * Note that the SPI device's chip select is active during the message,
4079 * and then is normally disabled between messages. Drivers for some
4080 * frequently-used devices may want to minimize costs of selecting a chip,
4081 * by leaving it selected in anticipation that the next message will go
4082 * to the same chip. (That may increase power usage.)
4084 * Also, the caller is guaranteeing that the memory associated with the
4085 * message will not be freed before this call returns.
4087 * Return: zero on success, else a negative error code.
4089 int spi_sync(struct spi_device *spi, struct spi_message *message)
4093 mutex_lock(&spi->controller->bus_lock_mutex);
4094 ret = __spi_sync(spi, message);
4095 mutex_unlock(&spi->controller->bus_lock_mutex);
4099 EXPORT_SYMBOL_GPL(spi_sync);
4102 * spi_sync_locked - version of spi_sync with exclusive bus usage
4103 * @spi: device with which data will be exchanged
4104 * @message: describes the data transfers
4105 * Context: can sleep
4107 * This call may only be used from a context that may sleep. The sleep
4108 * is non-interruptible, and has no timeout. Low-overhead controller
4109 * drivers may DMA directly into and out of the message buffers.
4111 * This call should be used by drivers that require exclusive access to the
4112 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4113 * be released by a spi_bus_unlock call when the exclusive access is over.
4115 * Return: zero on success, else a negative error code.
4117 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4119 return __spi_sync(spi, message);
4121 EXPORT_SYMBOL_GPL(spi_sync_locked);
4124 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
4125 * @ctlr: SPI bus master that should be locked for exclusive bus access
4126 * Context: can sleep
4128 * This call may only be used from a context that may sleep. The sleep
4129 * is non-interruptible, and has no timeout.
4131 * This call should be used by drivers that require exclusive access to the
4132 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4133 * exclusive access is over. Data transfer must be done by spi_sync_locked
4134 * and spi_async_locked calls when the SPI bus lock is held.
4136 * Return: always zero.
4138 int spi_bus_lock(struct spi_controller *ctlr)
4140 unsigned long flags;
4142 mutex_lock(&ctlr->bus_lock_mutex);
4144 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4145 ctlr->bus_lock_flag = 1;
4146 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4148 /* Mutex remains locked until spi_bus_unlock() is called */
4152 EXPORT_SYMBOL_GPL(spi_bus_lock);
4155 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4156 * @ctlr: SPI bus master that was locked for exclusive bus access
4157 * Context: can sleep
4159 * This call may only be used from a context that may sleep. The sleep
4160 * is non-interruptible, and has no timeout.
4162 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4165 * Return: always zero.
4167 int spi_bus_unlock(struct spi_controller *ctlr)
4169 ctlr->bus_lock_flag = 0;
4171 mutex_unlock(&ctlr->bus_lock_mutex);
4175 EXPORT_SYMBOL_GPL(spi_bus_unlock);
4177 /* Portable code must never pass more than 32 bytes */
4178 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4183 * spi_write_then_read - SPI synchronous write followed by read
4184 * @spi: device with which data will be exchanged
4185 * @txbuf: data to be written (need not be dma-safe)
4186 * @n_tx: size of txbuf, in bytes
4187 * @rxbuf: buffer into which data will be read (need not be dma-safe)
4188 * @n_rx: size of rxbuf, in bytes
4189 * Context: can sleep
4191 * This performs a half duplex MicroWire style transaction with the
4192 * device, sending txbuf and then reading rxbuf. The return value
4193 * is zero for success, else a negative errno status code.
4194 * This call may only be used from a context that may sleep.
4196 * Parameters to this routine are always copied using a small buffer.
4197 * Performance-sensitive or bulk transfer code should instead use
4198 * spi_{async,sync}() calls with dma-safe buffers.
4200 * Return: zero on success, else a negative error code.
4202 int spi_write_then_read(struct spi_device *spi,
4203 const void *txbuf, unsigned n_tx,
4204 void *rxbuf, unsigned n_rx)
4206 static DEFINE_MUTEX(lock);
4209 struct spi_message message;
4210 struct spi_transfer x[2];
4214 * Use preallocated DMA-safe buffer if we can. We can't avoid
4215 * copying here, (as a pure convenience thing), but we can
4216 * keep heap costs out of the hot path unless someone else is
4217 * using the pre-allocated buffer or the transfer is too large.
4219 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4220 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4221 GFP_KERNEL | GFP_DMA);
4228 spi_message_init(&message);
4229 memset(x, 0, sizeof(x));
4232 spi_message_add_tail(&x[0], &message);
4236 spi_message_add_tail(&x[1], &message);
4239 memcpy(local_buf, txbuf, n_tx);
4240 x[0].tx_buf = local_buf;
4241 x[1].rx_buf = local_buf + n_tx;
4244 status = spi_sync(spi, &message);
4246 memcpy(rxbuf, x[1].rx_buf, n_rx);
4248 if (x[0].tx_buf == buf)
4249 mutex_unlock(&lock);
4255 EXPORT_SYMBOL_GPL(spi_write_then_read);
4257 /*-------------------------------------------------------------------------*/
4259 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4260 /* Must call put_device() when done with returned spi_device device */
4261 static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4263 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4265 return dev ? to_spi_device(dev) : NULL;
4268 /* The spi controllers are not using spi_bus, so we find it with another way */
4269 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4273 dev = class_find_device_by_of_node(&spi_master_class, node);
4274 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4275 dev = class_find_device_by_of_node(&spi_slave_class, node);
4279 /* Reference got in class_find_device */
4280 return container_of(dev, struct spi_controller, dev);
4283 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4286 struct of_reconfig_data *rd = arg;
4287 struct spi_controller *ctlr;
4288 struct spi_device *spi;
4290 switch (of_reconfig_get_state_change(action, arg)) {
4291 case OF_RECONFIG_CHANGE_ADD:
4292 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4294 return NOTIFY_OK; /* Not for us */
4296 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4297 put_device(&ctlr->dev);
4301 spi = of_register_spi_device(ctlr, rd->dn);
4302 put_device(&ctlr->dev);
4305 pr_err("%s: failed to create for '%pOF'\n",
4307 of_node_clear_flag(rd->dn, OF_POPULATED);
4308 return notifier_from_errno(PTR_ERR(spi));
4312 case OF_RECONFIG_CHANGE_REMOVE:
4313 /* Already depopulated? */
4314 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4317 /* Find our device by node */
4318 spi = of_find_spi_device_by_node(rd->dn);
4320 return NOTIFY_OK; /* No? not meant for us */
4322 /* Unregister takes one ref away */
4323 spi_unregister_device(spi);
4325 /* And put the reference of the find */
4326 put_device(&spi->dev);
4333 static struct notifier_block spi_of_notifier = {
4334 .notifier_call = of_spi_notify,
4336 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4337 extern struct notifier_block spi_of_notifier;
4338 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4340 #if IS_ENABLED(CONFIG_ACPI)
4341 static int spi_acpi_controller_match(struct device *dev, const void *data)
4343 return ACPI_COMPANION(dev->parent) == data;
4346 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4350 dev = class_find_device(&spi_master_class, NULL, adev,
4351 spi_acpi_controller_match);
4352 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4353 dev = class_find_device(&spi_slave_class, NULL, adev,
4354 spi_acpi_controller_match);
4358 return container_of(dev, struct spi_controller, dev);
4361 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4365 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4366 return to_spi_device(dev);
4369 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4372 struct acpi_device *adev = arg;
4373 struct spi_controller *ctlr;
4374 struct spi_device *spi;
4377 case ACPI_RECONFIG_DEVICE_ADD:
4378 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4382 acpi_register_spi_device(ctlr, adev);
4383 put_device(&ctlr->dev);
4385 case ACPI_RECONFIG_DEVICE_REMOVE:
4386 if (!acpi_device_enumerated(adev))
4389 spi = acpi_spi_find_device_by_adev(adev);
4393 spi_unregister_device(spi);
4394 put_device(&spi->dev);
4401 static struct notifier_block spi_acpi_notifier = {
4402 .notifier_call = acpi_spi_notify,
4405 extern struct notifier_block spi_acpi_notifier;
4408 static int __init spi_init(void)
4412 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4418 status = bus_register(&spi_bus_type);
4422 status = class_register(&spi_master_class);
4426 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4427 status = class_register(&spi_slave_class);
4432 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4433 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4434 if (IS_ENABLED(CONFIG_ACPI))
4435 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4440 class_unregister(&spi_master_class);
4442 bus_unregister(&spi_bus_type);
4451 * A board_info is normally registered in arch_initcall(),
4452 * but even essential drivers wait till later.
4454 * REVISIT only boardinfo really needs static linking. The rest (device and
4455 * driver registration) _could_ be dynamically linked (modular) ... Costs
4456 * include needing to have boardinfo data structures be much more public.
4458 postcore_initcall(spi_init);