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/acpi.h>
8 #include <linux/cache.h>
9 #include <linux/clk/clk-conf.h>
10 #include <linux/delay.h>
11 #include <linux/device.h>
12 #include <linux/dmaengine.h>
13 #include <linux/dma-mapping.h>
14 #include <linux/export.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/highmem.h>
17 #include <linux/idr.h>
18 #include <linux/init.h>
19 #include <linux/ioport.h>
20 #include <linux/kernel.h>
21 #include <linux/kthread.h>
22 #include <linux/mod_devicetable.h>
23 #include <linux/mutex.h>
24 #include <linux/of_device.h>
25 #include <linux/of_irq.h>
26 #include <linux/percpu.h>
27 #include <linux/platform_data/x86/apple.h>
28 #include <linux/pm_domain.h>
29 #include <linux/pm_runtime.h>
30 #include <linux/property.h>
31 #include <linux/ptp_clock_kernel.h>
32 #include <linux/sched/rt.h>
33 #include <linux/slab.h>
34 #include <linux/spi/spi.h>
35 #include <linux/spi/spi-mem.h>
36 #include <uapi/linux/sched/types.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 sysfs_emit(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 = sysfs_emit(buf, "%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 static ssize_t spi_emit_pcpu_stats(struct spi_statistics __percpu *stat,
121 char *buf, size_t offset)
126 for_each_possible_cpu(i) {
127 const struct spi_statistics *pcpu_stats;
132 pcpu_stats = per_cpu_ptr(stat, i);
133 field = (void *)pcpu_stats + offset;
135 start = u64_stats_fetch_begin(&pcpu_stats->syncp);
136 inc = u64_stats_read(field);
137 } while (u64_stats_fetch_retry(&pcpu_stats->syncp, start));
140 return sysfs_emit(buf, "%llu\n", val);
143 #define SPI_STATISTICS_ATTRS(field, file) \
144 static ssize_t spi_controller_##field##_show(struct device *dev, \
145 struct device_attribute *attr, \
148 struct spi_controller *ctlr = container_of(dev, \
149 struct spi_controller, dev); \
150 return spi_statistics_##field##_show(ctlr->pcpu_statistics, buf); \
152 static struct device_attribute dev_attr_spi_controller_##field = { \
153 .attr = { .name = file, .mode = 0444 }, \
154 .show = spi_controller_##field##_show, \
156 static ssize_t spi_device_##field##_show(struct device *dev, \
157 struct device_attribute *attr, \
160 struct spi_device *spi = to_spi_device(dev); \
161 return spi_statistics_##field##_show(spi->pcpu_statistics, buf); \
163 static struct device_attribute dev_attr_spi_device_##field = { \
164 .attr = { .name = file, .mode = 0444 }, \
165 .show = spi_device_##field##_show, \
168 #define SPI_STATISTICS_SHOW_NAME(name, file, field) \
169 static ssize_t spi_statistics_##name##_show(struct spi_statistics __percpu *stat, \
172 return spi_emit_pcpu_stats(stat, buf, \
173 offsetof(struct spi_statistics, field)); \
175 SPI_STATISTICS_ATTRS(name, file)
177 #define SPI_STATISTICS_SHOW(field) \
178 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
181 SPI_STATISTICS_SHOW(messages);
182 SPI_STATISTICS_SHOW(transfers);
183 SPI_STATISTICS_SHOW(errors);
184 SPI_STATISTICS_SHOW(timedout);
186 SPI_STATISTICS_SHOW(spi_sync);
187 SPI_STATISTICS_SHOW(spi_sync_immediate);
188 SPI_STATISTICS_SHOW(spi_async);
190 SPI_STATISTICS_SHOW(bytes);
191 SPI_STATISTICS_SHOW(bytes_rx);
192 SPI_STATISTICS_SHOW(bytes_tx);
194 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
195 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
196 "transfer_bytes_histo_" number, \
197 transfer_bytes_histo[index])
198 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
199 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
200 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
201 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
202 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
203 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
204 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
205 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
206 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
207 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
208 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
209 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
210 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
211 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
212 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
213 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
214 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
216 SPI_STATISTICS_SHOW(transfers_split_maxsize);
218 static struct attribute *spi_dev_attrs[] = {
219 &dev_attr_modalias.attr,
220 &dev_attr_driver_override.attr,
224 static const struct attribute_group spi_dev_group = {
225 .attrs = spi_dev_attrs,
228 static struct attribute *spi_device_statistics_attrs[] = {
229 &dev_attr_spi_device_messages.attr,
230 &dev_attr_spi_device_transfers.attr,
231 &dev_attr_spi_device_errors.attr,
232 &dev_attr_spi_device_timedout.attr,
233 &dev_attr_spi_device_spi_sync.attr,
234 &dev_attr_spi_device_spi_sync_immediate.attr,
235 &dev_attr_spi_device_spi_async.attr,
236 &dev_attr_spi_device_bytes.attr,
237 &dev_attr_spi_device_bytes_rx.attr,
238 &dev_attr_spi_device_bytes_tx.attr,
239 &dev_attr_spi_device_transfer_bytes_histo0.attr,
240 &dev_attr_spi_device_transfer_bytes_histo1.attr,
241 &dev_attr_spi_device_transfer_bytes_histo2.attr,
242 &dev_attr_spi_device_transfer_bytes_histo3.attr,
243 &dev_attr_spi_device_transfer_bytes_histo4.attr,
244 &dev_attr_spi_device_transfer_bytes_histo5.attr,
245 &dev_attr_spi_device_transfer_bytes_histo6.attr,
246 &dev_attr_spi_device_transfer_bytes_histo7.attr,
247 &dev_attr_spi_device_transfer_bytes_histo8.attr,
248 &dev_attr_spi_device_transfer_bytes_histo9.attr,
249 &dev_attr_spi_device_transfer_bytes_histo10.attr,
250 &dev_attr_spi_device_transfer_bytes_histo11.attr,
251 &dev_attr_spi_device_transfer_bytes_histo12.attr,
252 &dev_attr_spi_device_transfer_bytes_histo13.attr,
253 &dev_attr_spi_device_transfer_bytes_histo14.attr,
254 &dev_attr_spi_device_transfer_bytes_histo15.attr,
255 &dev_attr_spi_device_transfer_bytes_histo16.attr,
256 &dev_attr_spi_device_transfers_split_maxsize.attr,
260 static const struct attribute_group spi_device_statistics_group = {
261 .name = "statistics",
262 .attrs = spi_device_statistics_attrs,
265 static const struct attribute_group *spi_dev_groups[] = {
267 &spi_device_statistics_group,
271 static struct attribute *spi_controller_statistics_attrs[] = {
272 &dev_attr_spi_controller_messages.attr,
273 &dev_attr_spi_controller_transfers.attr,
274 &dev_attr_spi_controller_errors.attr,
275 &dev_attr_spi_controller_timedout.attr,
276 &dev_attr_spi_controller_spi_sync.attr,
277 &dev_attr_spi_controller_spi_sync_immediate.attr,
278 &dev_attr_spi_controller_spi_async.attr,
279 &dev_attr_spi_controller_bytes.attr,
280 &dev_attr_spi_controller_bytes_rx.attr,
281 &dev_attr_spi_controller_bytes_tx.attr,
282 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
283 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
284 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
285 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
286 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
287 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
288 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
289 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
290 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
291 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
292 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
293 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
294 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
295 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
296 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
297 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
298 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
299 &dev_attr_spi_controller_transfers_split_maxsize.attr,
303 static const struct attribute_group spi_controller_statistics_group = {
304 .name = "statistics",
305 .attrs = spi_controller_statistics_attrs,
308 static const struct attribute_group *spi_master_groups[] = {
309 &spi_controller_statistics_group,
313 static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
314 struct spi_transfer *xfer,
315 struct spi_message *msg)
317 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
318 struct spi_statistics *stats;
324 stats = this_cpu_ptr(pcpu_stats);
325 u64_stats_update_begin(&stats->syncp);
327 u64_stats_inc(&stats->transfers);
328 u64_stats_inc(&stats->transfer_bytes_histo[l2len]);
330 u64_stats_add(&stats->bytes, xfer->len);
331 if (spi_valid_txbuf(msg, xfer))
332 u64_stats_add(&stats->bytes_tx, xfer->len);
333 if (spi_valid_rxbuf(msg, xfer))
334 u64_stats_add(&stats->bytes_rx, xfer->len);
336 u64_stats_update_end(&stats->syncp);
341 * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
342 * and the sysfs version makes coldplug work too.
344 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
346 while (id->name[0]) {
347 if (!strcmp(name, id->name))
354 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
356 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
358 return spi_match_id(sdrv->id_table, sdev->modalias);
360 EXPORT_SYMBOL_GPL(spi_get_device_id);
362 const void *spi_get_device_match_data(const struct spi_device *sdev)
366 match = device_get_match_data(&sdev->dev);
370 return (const void *)spi_get_device_id(sdev)->driver_data;
372 EXPORT_SYMBOL_GPL(spi_get_device_match_data);
374 static int spi_match_device(struct device *dev, struct device_driver *drv)
376 const struct spi_device *spi = to_spi_device(dev);
377 const struct spi_driver *sdrv = to_spi_driver(drv);
379 /* Check override first, and if set, only use the named driver */
380 if (spi->driver_override)
381 return strcmp(spi->driver_override, drv->name) == 0;
383 /* Attempt an OF style match */
384 if (of_driver_match_device(dev, drv))
388 if (acpi_driver_match_device(dev, drv))
392 return !!spi_match_id(sdrv->id_table, spi->modalias);
394 return strcmp(spi->modalias, drv->name) == 0;
397 static int spi_uevent(const struct device *dev, struct kobj_uevent_env *env)
399 const struct spi_device *spi = to_spi_device(dev);
402 rc = acpi_device_uevent_modalias(dev, env);
406 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
409 static int spi_probe(struct device *dev)
411 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
412 struct spi_device *spi = to_spi_device(dev);
415 ret = of_clk_set_defaults(dev->of_node, false);
420 spi->irq = of_irq_get(dev->of_node, 0);
421 if (spi->irq == -EPROBE_DEFER)
422 return -EPROBE_DEFER;
427 ret = dev_pm_domain_attach(dev, true);
432 ret = sdrv->probe(spi);
434 dev_pm_domain_detach(dev, true);
440 static void spi_remove(struct device *dev)
442 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
445 sdrv->remove(to_spi_device(dev));
447 dev_pm_domain_detach(dev, true);
450 static void spi_shutdown(struct device *dev)
453 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
456 sdrv->shutdown(to_spi_device(dev));
460 const struct bus_type spi_bus_type = {
462 .dev_groups = spi_dev_groups,
463 .match = spi_match_device,
464 .uevent = spi_uevent,
466 .remove = spi_remove,
467 .shutdown = spi_shutdown,
469 EXPORT_SYMBOL_GPL(spi_bus_type);
472 * __spi_register_driver - register a SPI driver
473 * @owner: owner module of the driver to register
474 * @sdrv: the driver to register
477 * Return: zero on success, else a negative error code.
479 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
481 sdrv->driver.owner = owner;
482 sdrv->driver.bus = &spi_bus_type;
485 * For Really Good Reasons we use spi: modaliases not of:
486 * modaliases for DT so module autoloading won't work if we
487 * don't have a spi_device_id as well as a compatible string.
489 if (sdrv->driver.of_match_table) {
490 const struct of_device_id *of_id;
492 for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
496 /* Strip off any vendor prefix */
497 of_name = strnchr(of_id->compatible,
498 sizeof(of_id->compatible), ',');
502 of_name = of_id->compatible;
504 if (sdrv->id_table) {
505 const struct spi_device_id *spi_id;
507 spi_id = spi_match_id(sdrv->id_table, of_name);
511 if (strcmp(sdrv->driver.name, of_name) == 0)
515 pr_warn("SPI driver %s has no spi_device_id for %s\n",
516 sdrv->driver.name, of_id->compatible);
520 return driver_register(&sdrv->driver);
522 EXPORT_SYMBOL_GPL(__spi_register_driver);
524 /*-------------------------------------------------------------------------*/
527 * SPI devices should normally not be created by SPI device drivers; that
528 * would make them board-specific. Similarly with SPI controller drivers.
529 * Device registration normally goes into like arch/.../mach.../board-YYY.c
530 * with other readonly (flashable) information about mainboard devices.
534 struct list_head list;
535 struct spi_board_info board_info;
538 static LIST_HEAD(board_list);
539 static LIST_HEAD(spi_controller_list);
542 * Used to protect add/del operation for board_info list and
543 * spi_controller list, and their matching process also used
544 * to protect object of type struct idr.
546 static DEFINE_MUTEX(board_lock);
549 * spi_alloc_device - Allocate a new SPI device
550 * @ctlr: Controller to which device is connected
553 * Allows a driver to allocate and initialize a spi_device without
554 * registering it immediately. This allows a driver to directly
555 * fill the spi_device with device parameters before calling
556 * spi_add_device() on it.
558 * Caller is responsible to call spi_add_device() on the returned
559 * spi_device structure to add it to the SPI controller. If the caller
560 * needs to discard the spi_device without adding it, then it should
561 * call spi_dev_put() on it.
563 * Return: a pointer to the new device, or NULL.
565 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
567 struct spi_device *spi;
569 if (!spi_controller_get(ctlr))
572 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
574 spi_controller_put(ctlr);
578 spi->pcpu_statistics = spi_alloc_pcpu_stats(NULL);
579 if (!spi->pcpu_statistics) {
581 spi_controller_put(ctlr);
585 spi->controller = ctlr;
586 spi->dev.parent = &ctlr->dev;
587 spi->dev.bus = &spi_bus_type;
588 spi->dev.release = spidev_release;
589 spi->mode = ctlr->buswidth_override_bits;
591 device_initialize(&spi->dev);
594 EXPORT_SYMBOL_GPL(spi_alloc_device);
596 static void spi_dev_set_name(struct spi_device *spi)
598 struct device *dev = &spi->dev;
599 struct fwnode_handle *fwnode = dev_fwnode(dev);
601 if (is_acpi_device_node(fwnode)) {
602 dev_set_name(dev, "spi-%s", acpi_dev_name(to_acpi_device_node(fwnode)));
606 if (is_software_node(fwnode)) {
607 dev_set_name(dev, "spi-%pfwP", fwnode);
611 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
612 spi_get_chipselect(spi, 0));
616 * Zero(0) is a valid physical CS value and can be located at any
617 * logical CS in the spi->chip_select[]. If all the physical CS
618 * are initialized to 0 then It would be difficult to differentiate
619 * between a valid physical CS 0 & an unused logical CS whose physical
620 * CS can be 0. As a solution to this issue initialize all the CS to -1.
621 * Now all the unused logical CS will have -1 physical CS value & can be
622 * ignored while performing physical CS validity checks.
624 #define SPI_INVALID_CS ((s8)-1)
626 static inline bool is_valid_cs(s8 chip_select)
628 return chip_select != SPI_INVALID_CS;
631 static inline int spi_dev_check_cs(struct device *dev,
632 struct spi_device *spi, u8 idx,
633 struct spi_device *new_spi, u8 new_idx)
638 cs = spi_get_chipselect(spi, idx);
639 for (idx_new = new_idx; idx_new < SPI_CS_CNT_MAX; idx_new++) {
640 cs_new = spi_get_chipselect(new_spi, idx_new);
641 if (is_valid_cs(cs) && is_valid_cs(cs_new) && cs == cs_new) {
642 dev_err(dev, "chipselect %u already in use\n", cs_new);
649 static int spi_dev_check(struct device *dev, void *data)
651 struct spi_device *spi = to_spi_device(dev);
652 struct spi_device *new_spi = data;
655 if (spi->controller == new_spi->controller) {
656 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
657 status = spi_dev_check_cs(dev, spi, idx, new_spi, 0);
665 static void spi_cleanup(struct spi_device *spi)
667 if (spi->controller->cleanup)
668 spi->controller->cleanup(spi);
671 static int __spi_add_device(struct spi_device *spi)
673 struct spi_controller *ctlr = spi->controller;
674 struct device *dev = ctlr->dev.parent;
678 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
679 /* Chipselects are numbered 0..max; validate. */
680 cs = spi_get_chipselect(spi, idx);
681 if (is_valid_cs(cs) && cs >= ctlr->num_chipselect) {
682 dev_err(dev, "cs%d >= max %d\n", spi_get_chipselect(spi, idx),
683 ctlr->num_chipselect);
689 * Make sure that multiple logical CS doesn't map to the same physical CS.
690 * For example, spi->chip_select[0] != spi->chip_select[1] and so on.
692 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
693 status = spi_dev_check_cs(dev, spi, idx, spi, idx + 1);
698 /* Set the bus ID string */
699 spi_dev_set_name(spi);
702 * We need to make sure there's no other device with this
703 * chipselect **BEFORE** we call setup(), else we'll trash
706 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
710 /* Controller may unregister concurrently */
711 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
712 !device_is_registered(&ctlr->dev)) {
716 if (ctlr->cs_gpiods) {
719 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
720 cs = spi_get_chipselect(spi, idx);
722 spi_set_csgpiod(spi, idx, ctlr->cs_gpiods[cs]);
727 * Drivers may modify this initial i/o setup, but will
728 * normally rely on the device being setup. Devices
729 * using SPI_CS_HIGH can't coexist well otherwise...
731 status = spi_setup(spi);
733 dev_err(dev, "can't setup %s, status %d\n",
734 dev_name(&spi->dev), status);
738 /* Device may be bound to an active driver when this returns */
739 status = device_add(&spi->dev);
741 dev_err(dev, "can't add %s, status %d\n",
742 dev_name(&spi->dev), status);
745 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
752 * spi_add_device - Add spi_device allocated with spi_alloc_device
753 * @spi: spi_device to register
755 * Companion function to spi_alloc_device. Devices allocated with
756 * spi_alloc_device can be added onto the SPI bus with this function.
758 * Return: 0 on success; negative errno on failure
760 int spi_add_device(struct spi_device *spi)
762 struct spi_controller *ctlr = spi->controller;
765 /* Set the bus ID string */
766 spi_dev_set_name(spi);
768 mutex_lock(&ctlr->add_lock);
769 status = __spi_add_device(spi);
770 mutex_unlock(&ctlr->add_lock);
773 EXPORT_SYMBOL_GPL(spi_add_device);
775 static void spi_set_all_cs_unused(struct spi_device *spi)
779 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
780 spi_set_chipselect(spi, idx, SPI_INVALID_CS);
784 * spi_new_device - instantiate one new SPI device
785 * @ctlr: Controller to which device is connected
786 * @chip: Describes the SPI device
789 * On typical mainboards, this is purely internal; and it's not needed
790 * after board init creates the hard-wired devices. Some development
791 * platforms may not be able to use spi_register_board_info though, and
792 * this is exported so that for example a USB or parport based adapter
793 * driver could add devices (which it would learn about out-of-band).
795 * Return: the new device, or NULL.
797 struct spi_device *spi_new_device(struct spi_controller *ctlr,
798 struct spi_board_info *chip)
800 struct spi_device *proxy;
804 * NOTE: caller did any chip->bus_num checks necessary.
806 * Also, unless we change the return value convention to use
807 * error-or-pointer (not NULL-or-pointer), troubleshootability
808 * suggests syslogged diagnostics are best here (ugh).
811 proxy = spi_alloc_device(ctlr);
815 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
817 /* Use provided chip-select for proxy device */
818 spi_set_all_cs_unused(proxy);
819 spi_set_chipselect(proxy, 0, chip->chip_select);
821 proxy->max_speed_hz = chip->max_speed_hz;
822 proxy->mode = chip->mode;
823 proxy->irq = chip->irq;
824 strscpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
825 proxy->dev.platform_data = (void *) chip->platform_data;
826 proxy->controller_data = chip->controller_data;
827 proxy->controller_state = NULL;
829 * By default spi->chip_select[0] will hold the physical CS number,
830 * so set bit 0 in spi->cs_index_mask.
832 proxy->cs_index_mask = BIT(0);
835 status = device_add_software_node(&proxy->dev, chip->swnode);
837 dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
838 chip->modalias, status);
843 status = spi_add_device(proxy);
850 device_remove_software_node(&proxy->dev);
854 EXPORT_SYMBOL_GPL(spi_new_device);
857 * spi_unregister_device - unregister a single SPI device
858 * @spi: spi_device to unregister
860 * Start making the passed SPI device vanish. Normally this would be handled
861 * by spi_unregister_controller().
863 void spi_unregister_device(struct spi_device *spi)
868 if (spi->dev.of_node) {
869 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
870 of_node_put(spi->dev.of_node);
872 if (ACPI_COMPANION(&spi->dev))
873 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
874 device_remove_software_node(&spi->dev);
875 device_del(&spi->dev);
877 put_device(&spi->dev);
879 EXPORT_SYMBOL_GPL(spi_unregister_device);
881 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
882 struct spi_board_info *bi)
884 struct spi_device *dev;
886 if (ctlr->bus_num != bi->bus_num)
889 dev = spi_new_device(ctlr, bi);
891 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
896 * spi_register_board_info - register SPI devices for a given board
897 * @info: array of chip descriptors
898 * @n: how many descriptors are provided
901 * Board-specific early init code calls this (probably during arch_initcall)
902 * with segments of the SPI device table. Any device nodes are created later,
903 * after the relevant parent SPI controller (bus_num) is defined. We keep
904 * this table of devices forever, so that reloading a controller driver will
905 * not make Linux forget about these hard-wired devices.
907 * Other code can also call this, e.g. a particular add-on board might provide
908 * SPI devices through its expansion connector, so code initializing that board
909 * would naturally declare its SPI devices.
911 * The board info passed can safely be __initdata ... but be careful of
912 * any embedded pointers (platform_data, etc), they're copied as-is.
914 * Return: zero on success, else a negative error code.
916 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
918 struct boardinfo *bi;
924 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
928 for (i = 0; i < n; i++, bi++, info++) {
929 struct spi_controller *ctlr;
931 memcpy(&bi->board_info, info, sizeof(*info));
933 mutex_lock(&board_lock);
934 list_add_tail(&bi->list, &board_list);
935 list_for_each_entry(ctlr, &spi_controller_list, list)
936 spi_match_controller_to_boardinfo(ctlr,
938 mutex_unlock(&board_lock);
944 /*-------------------------------------------------------------------------*/
946 /* Core methods for SPI resource management */
949 * spi_res_alloc - allocate a spi resource that is life-cycle managed
950 * during the processing of a spi_message while using
952 * @spi: the SPI device for which we allocate memory
953 * @release: the release code to execute for this resource
954 * @size: size to alloc and return
955 * @gfp: GFP allocation flags
957 * Return: the pointer to the allocated data
959 * This may get enhanced in the future to allocate from a memory pool
960 * of the @spi_device or @spi_controller to avoid repeated allocations.
962 static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
963 size_t size, gfp_t gfp)
965 struct spi_res *sres;
967 sres = kzalloc(sizeof(*sres) + size, gfp);
971 INIT_LIST_HEAD(&sres->entry);
972 sres->release = release;
978 * spi_res_free - free an SPI resource
979 * @res: pointer to the custom data of a resource
981 static void spi_res_free(void *res)
983 struct spi_res *sres = container_of(res, struct spi_res, data);
988 WARN_ON(!list_empty(&sres->entry));
993 * spi_res_add - add a spi_res to the spi_message
994 * @message: the SPI message
995 * @res: the spi_resource
997 static void spi_res_add(struct spi_message *message, void *res)
999 struct spi_res *sres = container_of(res, struct spi_res, data);
1001 WARN_ON(!list_empty(&sres->entry));
1002 list_add_tail(&sres->entry, &message->resources);
1006 * spi_res_release - release all SPI resources for this message
1007 * @ctlr: the @spi_controller
1008 * @message: the @spi_message
1010 static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
1012 struct spi_res *res, *tmp;
1014 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
1016 res->release(ctlr, message, res->data);
1018 list_del(&res->entry);
1024 /*-------------------------------------------------------------------------*/
1025 #define spi_for_each_valid_cs(spi, idx) \
1026 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) \
1027 if (!(spi->cs_index_mask & BIT(idx))) {} else
1029 static inline bool spi_is_last_cs(struct spi_device *spi)
1034 spi_for_each_valid_cs(spi, idx) {
1035 if (spi->controller->last_cs[idx] == spi_get_chipselect(spi, idx))
1041 static void spi_toggle_csgpiod(struct spi_device *spi, u8 idx, bool enable, bool activate)
1044 * Historically ACPI has no means of the GPIO polarity and
1045 * thus the SPISerialBus() resource defines it on the per-chip
1046 * basis. In order to avoid a chain of negations, the GPIO
1047 * polarity is considered being Active High. Even for the cases
1048 * when _DSD() is involved (in the updated versions of ACPI)
1049 * the GPIO CS polarity must be defined Active High to avoid
1050 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
1053 if (has_acpi_companion(&spi->dev))
1054 gpiod_set_value_cansleep(spi_get_csgpiod(spi, idx), !enable);
1056 /* Polarity handled by GPIO library */
1057 gpiod_set_value_cansleep(spi_get_csgpiod(spi, idx), activate);
1060 spi_delay_exec(&spi->cs_setup, NULL);
1062 spi_delay_exec(&spi->cs_inactive, NULL);
1065 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
1067 bool activate = enable;
1071 * Avoid calling into the driver (or doing delays) if the chip select
1072 * isn't actually changing from the last time this was called.
1074 if (!force && ((enable && spi->controller->last_cs_index_mask == spi->cs_index_mask &&
1075 spi_is_last_cs(spi)) ||
1076 (!enable && spi->controller->last_cs_index_mask == spi->cs_index_mask &&
1077 !spi_is_last_cs(spi))) &&
1078 (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
1081 trace_spi_set_cs(spi, activate);
1083 spi->controller->last_cs_index_mask = spi->cs_index_mask;
1084 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
1085 spi->controller->last_cs[idx] = enable ? spi_get_chipselect(spi, 0) : SPI_INVALID_CS;
1086 spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
1088 if (spi->mode & SPI_CS_HIGH)
1092 * Handle chip select delays for GPIO based CS or controllers without
1093 * programmable chip select timing.
1095 if ((spi_is_csgpiod(spi) || !spi->controller->set_cs_timing) && !activate)
1096 spi_delay_exec(&spi->cs_hold, NULL);
1098 if (spi_is_csgpiod(spi)) {
1099 if (!(spi->mode & SPI_NO_CS)) {
1100 spi_for_each_valid_cs(spi, idx) {
1101 if (spi_get_csgpiod(spi, idx))
1102 spi_toggle_csgpiod(spi, idx, enable, activate);
1105 /* Some SPI masters need both GPIO CS & slave_select */
1106 if ((spi->controller->flags & SPI_CONTROLLER_GPIO_SS) &&
1107 spi->controller->set_cs)
1108 spi->controller->set_cs(spi, !enable);
1109 } else if (spi->controller->set_cs) {
1110 spi->controller->set_cs(spi, !enable);
1113 if (spi_is_csgpiod(spi) || !spi->controller->set_cs_timing) {
1115 spi_delay_exec(&spi->cs_setup, NULL);
1117 spi_delay_exec(&spi->cs_inactive, NULL);
1121 #ifdef CONFIG_HAS_DMA
1122 static int spi_map_buf_attrs(struct spi_controller *ctlr, struct device *dev,
1123 struct sg_table *sgt, void *buf, size_t len,
1124 enum dma_data_direction dir, unsigned long attrs)
1126 const bool vmalloced_buf = is_vmalloc_addr(buf);
1127 unsigned int max_seg_size = dma_get_max_seg_size(dev);
1128 #ifdef CONFIG_HIGHMEM
1129 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
1130 (unsigned long)buf < (PKMAP_BASE +
1131 (LAST_PKMAP * PAGE_SIZE)));
1133 const bool kmap_buf = false;
1137 struct page *vm_page;
1138 struct scatterlist *sg;
1143 if (vmalloced_buf || kmap_buf) {
1144 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
1145 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
1146 } else if (virt_addr_valid(buf)) {
1147 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
1148 sgs = DIV_ROUND_UP(len, desc_len);
1153 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
1158 for (i = 0; i < sgs; i++) {
1160 if (vmalloced_buf || kmap_buf) {
1162 * Next scatterlist entry size is the minimum between
1163 * the desc_len and the remaining buffer length that
1166 min = min_t(size_t, desc_len,
1168 PAGE_SIZE - offset_in_page(buf)));
1170 vm_page = vmalloc_to_page(buf);
1172 vm_page = kmap_to_page(buf);
1177 sg_set_page(sg, vm_page,
1178 min, offset_in_page(buf));
1180 min = min_t(size_t, len, desc_len);
1182 sg_set_buf(sg, sg_buf, min);
1190 ret = dma_map_sgtable(dev, sgt, dir, attrs);
1199 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
1200 struct sg_table *sgt, void *buf, size_t len,
1201 enum dma_data_direction dir)
1203 return spi_map_buf_attrs(ctlr, dev, sgt, buf, len, dir, 0);
1206 static void spi_unmap_buf_attrs(struct spi_controller *ctlr,
1207 struct device *dev, struct sg_table *sgt,
1208 enum dma_data_direction dir,
1209 unsigned long attrs)
1211 dma_unmap_sgtable(dev, sgt, dir, attrs);
1213 sgt->orig_nents = 0;
1217 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
1218 struct sg_table *sgt, enum dma_data_direction dir)
1220 spi_unmap_buf_attrs(ctlr, dev, sgt, dir, 0);
1223 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1225 struct device *tx_dev, *rx_dev;
1226 struct spi_transfer *xfer;
1233 tx_dev = ctlr->dma_tx->device->dev;
1234 else if (ctlr->dma_map_dev)
1235 tx_dev = ctlr->dma_map_dev;
1237 tx_dev = ctlr->dev.parent;
1240 rx_dev = ctlr->dma_rx->device->dev;
1241 else if (ctlr->dma_map_dev)
1242 rx_dev = ctlr->dma_map_dev;
1244 rx_dev = ctlr->dev.parent;
1246 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1247 /* The sync is done before each transfer. */
1248 unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
1250 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1253 if (xfer->tx_buf != NULL) {
1254 ret = spi_map_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
1255 (void *)xfer->tx_buf,
1256 xfer->len, DMA_TO_DEVICE,
1262 if (xfer->rx_buf != NULL) {
1263 ret = spi_map_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
1264 xfer->rx_buf, xfer->len,
1265 DMA_FROM_DEVICE, attrs);
1267 spi_unmap_buf_attrs(ctlr, tx_dev,
1268 &xfer->tx_sg, DMA_TO_DEVICE,
1276 ctlr->cur_rx_dma_dev = rx_dev;
1277 ctlr->cur_tx_dma_dev = tx_dev;
1278 ctlr->cur_msg_mapped = true;
1283 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1285 struct device *rx_dev = ctlr->cur_rx_dma_dev;
1286 struct device *tx_dev = ctlr->cur_tx_dma_dev;
1287 struct spi_transfer *xfer;
1289 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1292 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1293 /* The sync has already been done after each transfer. */
1294 unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
1296 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1299 spi_unmap_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
1300 DMA_FROM_DEVICE, attrs);
1301 spi_unmap_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
1302 DMA_TO_DEVICE, attrs);
1305 ctlr->cur_msg_mapped = false;
1310 static void spi_dma_sync_for_device(struct spi_controller *ctlr,
1311 struct spi_transfer *xfer)
1313 struct device *rx_dev = ctlr->cur_rx_dma_dev;
1314 struct device *tx_dev = ctlr->cur_tx_dma_dev;
1316 if (!ctlr->cur_msg_mapped)
1319 dma_sync_sgtable_for_device(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1320 dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1323 static void spi_dma_sync_for_cpu(struct spi_controller *ctlr,
1324 struct spi_transfer *xfer)
1326 struct device *rx_dev = ctlr->cur_rx_dma_dev;
1327 struct device *tx_dev = ctlr->cur_tx_dma_dev;
1329 if (!ctlr->cur_msg_mapped)
1332 dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1333 dma_sync_sgtable_for_cpu(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1335 #else /* !CONFIG_HAS_DMA */
1336 static inline int __spi_map_msg(struct spi_controller *ctlr,
1337 struct spi_message *msg)
1342 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1343 struct spi_message *msg)
1348 static void spi_dma_sync_for_device(struct spi_controller *ctrl,
1349 struct spi_transfer *xfer)
1353 static void spi_dma_sync_for_cpu(struct spi_controller *ctrl,
1354 struct spi_transfer *xfer)
1357 #endif /* !CONFIG_HAS_DMA */
1359 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1360 struct spi_message *msg)
1362 struct spi_transfer *xfer;
1364 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1366 * Restore the original value of tx_buf or rx_buf if they are
1369 if (xfer->tx_buf == ctlr->dummy_tx)
1370 xfer->tx_buf = NULL;
1371 if (xfer->rx_buf == ctlr->dummy_rx)
1372 xfer->rx_buf = NULL;
1375 return __spi_unmap_msg(ctlr, msg);
1378 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1380 struct spi_transfer *xfer;
1382 unsigned int max_tx, max_rx;
1384 if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1385 && !(msg->spi->mode & SPI_3WIRE)) {
1389 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1390 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1392 max_tx = max(xfer->len, max_tx);
1393 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1395 max_rx = max(xfer->len, max_rx);
1399 tmp = krealloc(ctlr->dummy_tx, max_tx,
1400 GFP_KERNEL | GFP_DMA | __GFP_ZERO);
1403 ctlr->dummy_tx = tmp;
1407 tmp = krealloc(ctlr->dummy_rx, max_rx,
1408 GFP_KERNEL | GFP_DMA);
1411 ctlr->dummy_rx = tmp;
1414 if (max_tx || max_rx) {
1415 list_for_each_entry(xfer, &msg->transfers,
1420 xfer->tx_buf = ctlr->dummy_tx;
1422 xfer->rx_buf = ctlr->dummy_rx;
1427 return __spi_map_msg(ctlr, msg);
1430 static int spi_transfer_wait(struct spi_controller *ctlr,
1431 struct spi_message *msg,
1432 struct spi_transfer *xfer)
1434 struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1435 struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1436 u32 speed_hz = xfer->speed_hz;
1437 unsigned long long ms;
1439 if (spi_controller_is_slave(ctlr)) {
1440 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1441 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1449 * For each byte we wait for 8 cycles of the SPI clock.
1450 * Since speed is defined in Hz and we want milliseconds,
1451 * use respective multiplier, but before the division,
1452 * otherwise we may get 0 for short transfers.
1454 ms = 8LL * MSEC_PER_SEC * xfer->len;
1455 do_div(ms, speed_hz);
1458 * Increase it twice and add 200 ms tolerance, use
1459 * predefined maximum in case of overflow.
1465 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1466 msecs_to_jiffies(ms));
1469 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1470 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1471 dev_err(&msg->spi->dev,
1472 "SPI transfer timed out\n");
1476 if (xfer->error & SPI_TRANS_FAIL_IO)
1483 static void _spi_transfer_delay_ns(u32 ns)
1487 if (ns <= NSEC_PER_USEC) {
1490 u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
1495 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1499 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1501 u32 delay = _delay->value;
1502 u32 unit = _delay->unit;
1509 case SPI_DELAY_UNIT_USECS:
1510 delay *= NSEC_PER_USEC;
1512 case SPI_DELAY_UNIT_NSECS:
1513 /* Nothing to do here */
1515 case SPI_DELAY_UNIT_SCK:
1516 /* Clock cycles need to be obtained from spi_transfer */
1520 * If there is unknown effective speed, approximate it
1521 * by underestimating with half of the requested Hz.
1523 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1527 /* Convert delay to nanoseconds */
1528 delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1536 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1538 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1547 delay = spi_delay_to_ns(_delay, xfer);
1551 _spi_transfer_delay_ns(delay);
1555 EXPORT_SYMBOL_GPL(spi_delay_exec);
1557 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1558 struct spi_transfer *xfer)
1560 u32 default_delay_ns = 10 * NSEC_PER_USEC;
1561 u32 delay = xfer->cs_change_delay.value;
1562 u32 unit = xfer->cs_change_delay.unit;
1565 /* Return early on "fast" mode - for everything but USECS */
1567 if (unit == SPI_DELAY_UNIT_USECS)
1568 _spi_transfer_delay_ns(default_delay_ns);
1572 ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1574 dev_err_once(&msg->spi->dev,
1575 "Use of unsupported delay unit %i, using default of %luus\n",
1576 unit, default_delay_ns / NSEC_PER_USEC);
1577 _spi_transfer_delay_ns(default_delay_ns);
1581 void spi_transfer_cs_change_delay_exec(struct spi_message *msg,
1582 struct spi_transfer *xfer)
1584 _spi_transfer_cs_change_delay(msg, xfer);
1586 EXPORT_SYMBOL_GPL(spi_transfer_cs_change_delay_exec);
1589 * spi_transfer_one_message - Default implementation of transfer_one_message()
1591 * This is a standard implementation of transfer_one_message() for
1592 * drivers which implement a transfer_one() operation. It provides
1593 * standard handling of delays and chip select management.
1595 static int spi_transfer_one_message(struct spi_controller *ctlr,
1596 struct spi_message *msg)
1598 struct spi_transfer *xfer;
1599 bool keep_cs = false;
1601 struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1602 struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1604 xfer = list_first_entry(&msg->transfers, struct spi_transfer, transfer_list);
1605 spi_set_cs(msg->spi, !xfer->cs_off, false);
1607 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1608 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1610 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1611 trace_spi_transfer_start(msg, xfer);
1613 spi_statistics_add_transfer_stats(statm, xfer, msg);
1614 spi_statistics_add_transfer_stats(stats, xfer, msg);
1616 if (!ctlr->ptp_sts_supported) {
1617 xfer->ptp_sts_word_pre = 0;
1618 ptp_read_system_prets(xfer->ptp_sts);
1621 if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1622 reinit_completion(&ctlr->xfer_completion);
1625 spi_dma_sync_for_device(ctlr, xfer);
1626 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1628 spi_dma_sync_for_cpu(ctlr, xfer);
1630 if (ctlr->cur_msg_mapped &&
1631 (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1632 __spi_unmap_msg(ctlr, msg);
1633 ctlr->fallback = true;
1634 xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1638 SPI_STATISTICS_INCREMENT_FIELD(statm,
1640 SPI_STATISTICS_INCREMENT_FIELD(stats,
1642 dev_err(&msg->spi->dev,
1643 "SPI transfer failed: %d\n", ret);
1648 ret = spi_transfer_wait(ctlr, msg, xfer);
1653 spi_dma_sync_for_cpu(ctlr, xfer);
1656 dev_err(&msg->spi->dev,
1657 "Bufferless transfer has length %u\n",
1661 if (!ctlr->ptp_sts_supported) {
1662 ptp_read_system_postts(xfer->ptp_sts);
1663 xfer->ptp_sts_word_post = xfer->len;
1666 trace_spi_transfer_stop(msg, xfer);
1668 if (msg->status != -EINPROGRESS)
1671 spi_transfer_delay_exec(xfer);
1673 if (xfer->cs_change) {
1674 if (list_is_last(&xfer->transfer_list,
1679 spi_set_cs(msg->spi, false, false);
1680 _spi_transfer_cs_change_delay(msg, xfer);
1681 if (!list_next_entry(xfer, transfer_list)->cs_off)
1682 spi_set_cs(msg->spi, true, false);
1684 } else if (!list_is_last(&xfer->transfer_list, &msg->transfers) &&
1685 xfer->cs_off != list_next_entry(xfer, transfer_list)->cs_off) {
1686 spi_set_cs(msg->spi, xfer->cs_off, false);
1689 msg->actual_length += xfer->len;
1693 if (ret != 0 || !keep_cs)
1694 spi_set_cs(msg->spi, false, false);
1696 if (msg->status == -EINPROGRESS)
1699 if (msg->status && ctlr->handle_err)
1700 ctlr->handle_err(ctlr, msg);
1702 spi_finalize_current_message(ctlr);
1708 * spi_finalize_current_transfer - report completion of a transfer
1709 * @ctlr: the controller reporting completion
1711 * Called by SPI drivers using the core transfer_one_message()
1712 * implementation to notify it that the current interrupt driven
1713 * transfer has finished and the next one may be scheduled.
1715 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1717 complete(&ctlr->xfer_completion);
1719 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1721 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1723 if (ctlr->auto_runtime_pm) {
1724 pm_runtime_mark_last_busy(ctlr->dev.parent);
1725 pm_runtime_put_autosuspend(ctlr->dev.parent);
1729 static int __spi_pump_transfer_message(struct spi_controller *ctlr,
1730 struct spi_message *msg, bool was_busy)
1732 struct spi_transfer *xfer;
1735 if (!was_busy && ctlr->auto_runtime_pm) {
1736 ret = pm_runtime_get_sync(ctlr->dev.parent);
1738 pm_runtime_put_noidle(ctlr->dev.parent);
1739 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1743 spi_finalize_current_message(ctlr);
1750 trace_spi_controller_busy(ctlr);
1752 if (!was_busy && ctlr->prepare_transfer_hardware) {
1753 ret = ctlr->prepare_transfer_hardware(ctlr);
1756 "failed to prepare transfer hardware: %d\n",
1759 if (ctlr->auto_runtime_pm)
1760 pm_runtime_put(ctlr->dev.parent);
1763 spi_finalize_current_message(ctlr);
1769 trace_spi_message_start(msg);
1771 if (ctlr->prepare_message) {
1772 ret = ctlr->prepare_message(ctlr, msg);
1774 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1777 spi_finalize_current_message(ctlr);
1780 msg->prepared = true;
1783 ret = spi_map_msg(ctlr, msg);
1786 spi_finalize_current_message(ctlr);
1790 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1791 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1792 xfer->ptp_sts_word_pre = 0;
1793 ptp_read_system_prets(xfer->ptp_sts);
1798 * Drivers implementation of transfer_one_message() must arrange for
1799 * spi_finalize_current_message() to get called. Most drivers will do
1800 * this in the calling context, but some don't. For those cases, a
1801 * completion is used to guarantee that this function does not return
1802 * until spi_finalize_current_message() is done accessing
1804 * Use of the following two flags enable to opportunistically skip the
1805 * use of the completion since its use involves expensive spin locks.
1806 * In case of a race with the context that calls
1807 * spi_finalize_current_message() the completion will always be used,
1808 * due to strict ordering of these flags using barriers.
1810 WRITE_ONCE(ctlr->cur_msg_incomplete, true);
1811 WRITE_ONCE(ctlr->cur_msg_need_completion, false);
1812 reinit_completion(&ctlr->cur_msg_completion);
1813 smp_wmb(); /* Make these available to spi_finalize_current_message() */
1815 ret = ctlr->transfer_one_message(ctlr, msg);
1818 "failed to transfer one message from queue\n");
1822 WRITE_ONCE(ctlr->cur_msg_need_completion, true);
1823 smp_mb(); /* See spi_finalize_current_message()... */
1824 if (READ_ONCE(ctlr->cur_msg_incomplete))
1825 wait_for_completion(&ctlr->cur_msg_completion);
1831 * __spi_pump_messages - function which processes SPI message queue
1832 * @ctlr: controller to process queue for
1833 * @in_kthread: true if we are in the context of the message pump thread
1835 * This function checks if there is any SPI message in the queue that
1836 * needs processing and if so call out to the driver to initialize hardware
1837 * and transfer each message.
1839 * Note that it is called both from the kthread itself and also from
1840 * inside spi_sync(); the queue extraction handling at the top of the
1841 * function should deal with this safely.
1843 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1845 struct spi_message *msg;
1846 bool was_busy = false;
1847 unsigned long flags;
1850 /* Take the I/O mutex */
1851 mutex_lock(&ctlr->io_mutex);
1854 spin_lock_irqsave(&ctlr->queue_lock, flags);
1856 /* Make sure we are not already running a message */
1860 /* Check if the queue is idle */
1861 if (list_empty(&ctlr->queue) || !ctlr->running) {
1865 /* Defer any non-atomic teardown to the thread */
1867 if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1868 !ctlr->unprepare_transfer_hardware) {
1869 spi_idle_runtime_pm(ctlr);
1871 ctlr->queue_empty = true;
1872 trace_spi_controller_idle(ctlr);
1874 kthread_queue_work(ctlr->kworker,
1875 &ctlr->pump_messages);
1881 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1883 kfree(ctlr->dummy_rx);
1884 ctlr->dummy_rx = NULL;
1885 kfree(ctlr->dummy_tx);
1886 ctlr->dummy_tx = NULL;
1887 if (ctlr->unprepare_transfer_hardware &&
1888 ctlr->unprepare_transfer_hardware(ctlr))
1890 "failed to unprepare transfer hardware\n");
1891 spi_idle_runtime_pm(ctlr);
1892 trace_spi_controller_idle(ctlr);
1894 spin_lock_irqsave(&ctlr->queue_lock, flags);
1895 ctlr->queue_empty = true;
1899 /* Extract head of queue */
1900 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1901 ctlr->cur_msg = msg;
1903 list_del_init(&msg->queue);
1908 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1910 ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
1911 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1913 ctlr->cur_msg = NULL;
1914 ctlr->fallback = false;
1916 mutex_unlock(&ctlr->io_mutex);
1918 /* Prod the scheduler in case transfer_one() was busy waiting */
1924 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1925 mutex_unlock(&ctlr->io_mutex);
1929 * spi_pump_messages - kthread work function which processes spi message queue
1930 * @work: pointer to kthread work struct contained in the controller struct
1932 static void spi_pump_messages(struct kthread_work *work)
1934 struct spi_controller *ctlr =
1935 container_of(work, struct spi_controller, pump_messages);
1937 __spi_pump_messages(ctlr, true);
1941 * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1942 * @ctlr: Pointer to the spi_controller structure of the driver
1943 * @xfer: Pointer to the transfer being timestamped
1944 * @progress: How many words (not bytes) have been transferred so far
1945 * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1946 * transfer, for less jitter in time measurement. Only compatible
1947 * with PIO drivers. If true, must follow up with
1948 * spi_take_timestamp_post or otherwise system will crash.
1949 * WARNING: for fully predictable results, the CPU frequency must
1950 * also be under control (governor).
1952 * This is a helper for drivers to collect the beginning of the TX timestamp
1953 * for the requested byte from the SPI transfer. The frequency with which this
1954 * function must be called (once per word, once for the whole transfer, once
1955 * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1956 * greater than or equal to the requested byte at the time of the call. The
1957 * timestamp is only taken once, at the first such call. It is assumed that
1958 * the driver advances its @tx buffer pointer monotonically.
1960 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1961 struct spi_transfer *xfer,
1962 size_t progress, bool irqs_off)
1967 if (xfer->timestamped)
1970 if (progress > xfer->ptp_sts_word_pre)
1973 /* Capture the resolution of the timestamp */
1974 xfer->ptp_sts_word_pre = progress;
1977 local_irq_save(ctlr->irq_flags);
1981 ptp_read_system_prets(xfer->ptp_sts);
1983 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1986 * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1987 * @ctlr: Pointer to the spi_controller structure of the driver
1988 * @xfer: Pointer to the transfer being timestamped
1989 * @progress: How many words (not bytes) have been transferred so far
1990 * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1992 * This is a helper for drivers to collect the end of the TX timestamp for
1993 * the requested byte from the SPI transfer. Can be called with an arbitrary
1994 * frequency: only the first call where @tx exceeds or is equal to the
1995 * requested word will be timestamped.
1997 void spi_take_timestamp_post(struct spi_controller *ctlr,
1998 struct spi_transfer *xfer,
1999 size_t progress, bool irqs_off)
2004 if (xfer->timestamped)
2007 if (progress < xfer->ptp_sts_word_post)
2010 ptp_read_system_postts(xfer->ptp_sts);
2013 local_irq_restore(ctlr->irq_flags);
2017 /* Capture the resolution of the timestamp */
2018 xfer->ptp_sts_word_post = progress;
2020 xfer->timestamped = 1;
2022 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
2025 * spi_set_thread_rt - set the controller to pump at realtime priority
2026 * @ctlr: controller to boost priority of
2028 * This can be called because the controller requested realtime priority
2029 * (by setting the ->rt value before calling spi_register_controller()) or
2030 * because a device on the bus said that its transfers needed realtime
2033 * NOTE: at the moment if any device on a bus says it needs realtime then
2034 * the thread will be at realtime priority for all transfers on that
2035 * controller. If this eventually becomes a problem we may see if we can
2036 * find a way to boost the priority only temporarily during relevant
2039 static void spi_set_thread_rt(struct spi_controller *ctlr)
2041 dev_info(&ctlr->dev,
2042 "will run message pump with realtime priority\n");
2043 sched_set_fifo(ctlr->kworker->task);
2046 static int spi_init_queue(struct spi_controller *ctlr)
2048 ctlr->running = false;
2050 ctlr->queue_empty = true;
2052 ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
2053 if (IS_ERR(ctlr->kworker)) {
2054 dev_err(&ctlr->dev, "failed to create message pump kworker\n");
2055 return PTR_ERR(ctlr->kworker);
2058 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
2061 * Controller config will indicate if this controller should run the
2062 * message pump with high (realtime) priority to reduce the transfer
2063 * latency on the bus by minimising the delay between a transfer
2064 * request and the scheduling of the message pump thread. Without this
2065 * setting the message pump thread will remain at default priority.
2068 spi_set_thread_rt(ctlr);
2074 * spi_get_next_queued_message() - called by driver to check for queued
2076 * @ctlr: the controller to check for queued messages
2078 * If there are more messages in the queue, the next message is returned from
2081 * Return: the next message in the queue, else NULL if the queue is empty.
2083 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
2085 struct spi_message *next;
2086 unsigned long flags;
2088 /* Get a pointer to the next message, if any */
2089 spin_lock_irqsave(&ctlr->queue_lock, flags);
2090 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
2092 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2096 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
2099 * __spi_unoptimize_message - shared implementation of spi_unoptimize_message()
2100 * and spi_maybe_unoptimize_message()
2101 * @msg: the message to unoptimize
2103 * Peripheral drivers should use spi_unoptimize_message() and callers inside
2104 * core should use spi_maybe_unoptimize_message() rather than calling this
2105 * function directly.
2107 * It is not valid to call this on a message that is not currently optimized.
2109 static void __spi_unoptimize_message(struct spi_message *msg)
2111 struct spi_controller *ctlr = msg->spi->controller;
2113 if (ctlr->unoptimize_message)
2114 ctlr->unoptimize_message(msg);
2116 spi_res_release(ctlr, msg);
2118 msg->optimized = false;
2119 msg->opt_state = NULL;
2123 * spi_maybe_unoptimize_message - unoptimize msg not managed by a peripheral
2124 * @msg: the message to unoptimize
2126 * This function is used to unoptimize a message if and only if it was
2127 * optimized by the core (via spi_maybe_optimize_message()).
2129 static void spi_maybe_unoptimize_message(struct spi_message *msg)
2131 if (!msg->pre_optimized && msg->optimized)
2132 __spi_unoptimize_message(msg);
2136 * spi_finalize_current_message() - the current message is complete
2137 * @ctlr: the controller to return the message to
2139 * Called by the driver to notify the core that the message in the front of the
2140 * queue is complete and can be removed from the queue.
2142 void spi_finalize_current_message(struct spi_controller *ctlr)
2144 struct spi_transfer *xfer;
2145 struct spi_message *mesg;
2148 mesg = ctlr->cur_msg;
2150 if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
2151 list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
2152 ptp_read_system_postts(xfer->ptp_sts);
2153 xfer->ptp_sts_word_post = xfer->len;
2157 if (unlikely(ctlr->ptp_sts_supported))
2158 list_for_each_entry(xfer, &mesg->transfers, transfer_list)
2159 WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
2161 spi_unmap_msg(ctlr, mesg);
2163 if (mesg->prepared && ctlr->unprepare_message) {
2164 ret = ctlr->unprepare_message(ctlr, mesg);
2166 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
2171 mesg->prepared = false;
2173 spi_maybe_unoptimize_message(mesg);
2175 WRITE_ONCE(ctlr->cur_msg_incomplete, false);
2176 smp_mb(); /* See __spi_pump_transfer_message()... */
2177 if (READ_ONCE(ctlr->cur_msg_need_completion))
2178 complete(&ctlr->cur_msg_completion);
2180 trace_spi_message_done(mesg);
2184 mesg->complete(mesg->context);
2186 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
2188 static int spi_start_queue(struct spi_controller *ctlr)
2190 unsigned long flags;
2192 spin_lock_irqsave(&ctlr->queue_lock, flags);
2194 if (ctlr->running || ctlr->busy) {
2195 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2199 ctlr->running = true;
2200 ctlr->cur_msg = NULL;
2201 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2203 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2208 static int spi_stop_queue(struct spi_controller *ctlr)
2210 unsigned long flags;
2211 unsigned limit = 500;
2214 spin_lock_irqsave(&ctlr->queue_lock, flags);
2217 * This is a bit lame, but is optimized for the common execution path.
2218 * A wait_queue on the ctlr->busy could be used, but then the common
2219 * execution path (pump_messages) would be required to call wake_up or
2220 * friends on every SPI message. Do this instead.
2222 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
2223 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2224 usleep_range(10000, 11000);
2225 spin_lock_irqsave(&ctlr->queue_lock, flags);
2228 if (!list_empty(&ctlr->queue) || ctlr->busy)
2231 ctlr->running = false;
2233 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2238 static int spi_destroy_queue(struct spi_controller *ctlr)
2242 ret = spi_stop_queue(ctlr);
2245 * kthread_flush_worker will block until all work is done.
2246 * If the reason that stop_queue timed out is that the work will never
2247 * finish, then it does no good to call flush/stop thread, so
2251 dev_err(&ctlr->dev, "problem destroying queue\n");
2255 kthread_destroy_worker(ctlr->kworker);
2260 static int __spi_queued_transfer(struct spi_device *spi,
2261 struct spi_message *msg,
2264 struct spi_controller *ctlr = spi->controller;
2265 unsigned long flags;
2267 spin_lock_irqsave(&ctlr->queue_lock, flags);
2269 if (!ctlr->running) {
2270 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2273 msg->actual_length = 0;
2274 msg->status = -EINPROGRESS;
2276 list_add_tail(&msg->queue, &ctlr->queue);
2277 ctlr->queue_empty = false;
2278 if (!ctlr->busy && need_pump)
2279 kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2281 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2286 * spi_queued_transfer - transfer function for queued transfers
2287 * @spi: SPI device which is requesting transfer
2288 * @msg: SPI message which is to handled is queued to driver queue
2290 * Return: zero on success, else a negative error code.
2292 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
2294 return __spi_queued_transfer(spi, msg, true);
2297 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2301 ctlr->transfer = spi_queued_transfer;
2302 if (!ctlr->transfer_one_message)
2303 ctlr->transfer_one_message = spi_transfer_one_message;
2305 /* Initialize and start queue */
2306 ret = spi_init_queue(ctlr);
2308 dev_err(&ctlr->dev, "problem initializing queue\n");
2309 goto err_init_queue;
2311 ctlr->queued = true;
2312 ret = spi_start_queue(ctlr);
2314 dev_err(&ctlr->dev, "problem starting queue\n");
2315 goto err_start_queue;
2321 spi_destroy_queue(ctlr);
2327 * spi_flush_queue - Send all pending messages in the queue from the callers'
2329 * @ctlr: controller to process queue for
2331 * This should be used when one wants to ensure all pending messages have been
2332 * sent before doing something. Is used by the spi-mem code to make sure SPI
2333 * memory operations do not preempt regular SPI transfers that have been queued
2334 * before the spi-mem operation.
2336 void spi_flush_queue(struct spi_controller *ctlr)
2338 if (ctlr->transfer == spi_queued_transfer)
2339 __spi_pump_messages(ctlr, false);
2342 /*-------------------------------------------------------------------------*/
2344 #if defined(CONFIG_OF)
2345 static void of_spi_parse_dt_cs_delay(struct device_node *nc,
2346 struct spi_delay *delay, const char *prop)
2350 if (!of_property_read_u32(nc, prop, &value)) {
2351 if (value > U16_MAX) {
2352 delay->value = DIV_ROUND_UP(value, 1000);
2353 delay->unit = SPI_DELAY_UNIT_USECS;
2355 delay->value = value;
2356 delay->unit = SPI_DELAY_UNIT_NSECS;
2361 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2362 struct device_node *nc)
2364 u32 value, cs[SPI_CS_CNT_MAX];
2367 /* Mode (clock phase/polarity/etc.) */
2368 if (of_property_read_bool(nc, "spi-cpha"))
2369 spi->mode |= SPI_CPHA;
2370 if (of_property_read_bool(nc, "spi-cpol"))
2371 spi->mode |= SPI_CPOL;
2372 if (of_property_read_bool(nc, "spi-3wire"))
2373 spi->mode |= SPI_3WIRE;
2374 if (of_property_read_bool(nc, "spi-lsb-first"))
2375 spi->mode |= SPI_LSB_FIRST;
2376 if (of_property_read_bool(nc, "spi-cs-high"))
2377 spi->mode |= SPI_CS_HIGH;
2379 /* Device DUAL/QUAD mode */
2380 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
2383 spi->mode |= SPI_NO_TX;
2388 spi->mode |= SPI_TX_DUAL;
2391 spi->mode |= SPI_TX_QUAD;
2394 spi->mode |= SPI_TX_OCTAL;
2397 dev_warn(&ctlr->dev,
2398 "spi-tx-bus-width %d not supported\n",
2404 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
2407 spi->mode |= SPI_NO_RX;
2412 spi->mode |= SPI_RX_DUAL;
2415 spi->mode |= SPI_RX_QUAD;
2418 spi->mode |= SPI_RX_OCTAL;
2421 dev_warn(&ctlr->dev,
2422 "spi-rx-bus-width %d not supported\n",
2428 if (spi_controller_is_slave(ctlr)) {
2429 if (!of_node_name_eq(nc, "slave")) {
2430 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2437 if (ctlr->num_chipselect > SPI_CS_CNT_MAX) {
2438 dev_err(&ctlr->dev, "No. of CS is more than max. no. of supported CS\n");
2442 spi_set_all_cs_unused(spi);
2444 /* Device address */
2445 rc = of_property_read_variable_u32_array(nc, "reg", &cs[0], 1,
2448 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2452 if (rc > ctlr->num_chipselect) {
2453 dev_err(&ctlr->dev, "%pOF has number of CS > ctlr->num_chipselect (%d)\n",
2457 if ((of_property_read_bool(nc, "parallel-memories")) &&
2458 (!(ctlr->flags & SPI_CONTROLLER_MULTI_CS))) {
2459 dev_err(&ctlr->dev, "SPI controller doesn't support multi CS\n");
2462 for (idx = 0; idx < rc; idx++)
2463 spi_set_chipselect(spi, idx, cs[idx]);
2466 * By default spi->chip_select[0] will hold the physical CS number,
2467 * so set bit 0 in spi->cs_index_mask.
2469 spi->cs_index_mask = BIT(0);
2472 if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2473 spi->max_speed_hz = value;
2475 /* Device CS delays */
2476 of_spi_parse_dt_cs_delay(nc, &spi->cs_setup, "spi-cs-setup-delay-ns");
2477 of_spi_parse_dt_cs_delay(nc, &spi->cs_hold, "spi-cs-hold-delay-ns");
2478 of_spi_parse_dt_cs_delay(nc, &spi->cs_inactive, "spi-cs-inactive-delay-ns");
2483 static struct spi_device *
2484 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2486 struct spi_device *spi;
2489 /* Alloc an spi_device */
2490 spi = spi_alloc_device(ctlr);
2492 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2497 /* Select device driver */
2498 rc = of_alias_from_compatible(nc, spi->modalias,
2499 sizeof(spi->modalias));
2501 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2505 rc = of_spi_parse_dt(ctlr, spi, nc);
2509 /* Store a pointer to the node in the device structure */
2512 device_set_node(&spi->dev, of_fwnode_handle(nc));
2514 /* Register the new device */
2515 rc = spi_add_device(spi);
2517 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2518 goto err_of_node_put;
2531 * of_register_spi_devices() - Register child devices onto the SPI bus
2532 * @ctlr: Pointer to spi_controller device
2534 * Registers an spi_device for each child node of controller node which
2535 * represents a valid SPI slave.
2537 static void of_register_spi_devices(struct spi_controller *ctlr)
2539 struct spi_device *spi;
2540 struct device_node *nc;
2542 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2543 if (of_node_test_and_set_flag(nc, OF_POPULATED))
2545 spi = of_register_spi_device(ctlr, nc);
2547 dev_warn(&ctlr->dev,
2548 "Failed to create SPI device for %pOF\n", nc);
2549 of_node_clear_flag(nc, OF_POPULATED);
2554 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2558 * spi_new_ancillary_device() - Register ancillary SPI device
2559 * @spi: Pointer to the main SPI device registering the ancillary device
2560 * @chip_select: Chip Select of the ancillary device
2562 * Register an ancillary SPI device; for example some chips have a chip-select
2563 * for normal device usage and another one for setup/firmware upload.
2565 * This may only be called from main SPI device's probe routine.
2567 * Return: 0 on success; negative errno on failure
2569 struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
2572 struct spi_controller *ctlr = spi->controller;
2573 struct spi_device *ancillary;
2576 /* Alloc an spi_device */
2577 ancillary = spi_alloc_device(ctlr);
2583 strscpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
2585 /* Use provided chip-select for ancillary device */
2586 spi_set_all_cs_unused(ancillary);
2587 spi_set_chipselect(ancillary, 0, chip_select);
2589 /* Take over SPI mode/speed from SPI main device */
2590 ancillary->max_speed_hz = spi->max_speed_hz;
2591 ancillary->mode = spi->mode;
2593 * By default spi->chip_select[0] will hold the physical CS number,
2594 * so set bit 0 in spi->cs_index_mask.
2596 ancillary->cs_index_mask = BIT(0);
2598 WARN_ON(!mutex_is_locked(&ctlr->add_lock));
2600 /* Register the new device */
2601 rc = __spi_add_device(ancillary);
2603 dev_err(&spi->dev, "failed to register ancillary device\n");
2610 spi_dev_put(ancillary);
2613 EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
2616 struct acpi_spi_lookup {
2617 struct spi_controller *ctlr;
2627 static int acpi_spi_count(struct acpi_resource *ares, void *data)
2629 struct acpi_resource_spi_serialbus *sb;
2632 if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2635 sb = &ares->data.spi_serial_bus;
2636 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2639 *count = *count + 1;
2645 * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2646 * @adev: ACPI device
2648 * Return: the number of SpiSerialBus resources in the ACPI-device's
2649 * resource-list; or a negative error code.
2651 int acpi_spi_count_resources(struct acpi_device *adev)
2657 ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2661 acpi_dev_free_resource_list(&r);
2665 EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2667 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2668 struct acpi_spi_lookup *lookup)
2670 const union acpi_object *obj;
2672 if (!x86_apple_machine)
2675 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2676 && obj->buffer.length >= 4)
2677 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2679 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2680 && obj->buffer.length == 8)
2681 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2683 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2684 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2685 lookup->mode |= SPI_LSB_FIRST;
2687 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2688 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2689 lookup->mode |= SPI_CPOL;
2691 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2692 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
2693 lookup->mode |= SPI_CPHA;
2696 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2698 struct acpi_spi_lookup *lookup = data;
2699 struct spi_controller *ctlr = lookup->ctlr;
2701 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2702 struct acpi_resource_spi_serialbus *sb;
2703 acpi_handle parent_handle;
2706 sb = &ares->data.spi_serial_bus;
2707 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2709 if (lookup->index != -1 && lookup->n++ != lookup->index)
2712 status = acpi_get_handle(NULL,
2713 sb->resource_source.string_ptr,
2716 if (ACPI_FAILURE(status))
2720 if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2723 struct acpi_device *adev;
2725 adev = acpi_fetch_acpi_dev(parent_handle);
2729 ctlr = acpi_spi_find_controller_by_adev(adev);
2731 return -EPROBE_DEFER;
2733 lookup->ctlr = ctlr;
2737 * ACPI DeviceSelection numbering is handled by the
2738 * host controller driver in Windows and can vary
2739 * from driver to driver. In Linux we always expect
2740 * 0 .. max - 1 so we need to ask the driver to
2741 * translate between the two schemes.
2743 if (ctlr->fw_translate_cs) {
2744 int cs = ctlr->fw_translate_cs(ctlr,
2745 sb->device_selection);
2748 lookup->chip_select = cs;
2750 lookup->chip_select = sb->device_selection;
2753 lookup->max_speed_hz = sb->connection_speed;
2754 lookup->bits_per_word = sb->data_bit_length;
2756 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2757 lookup->mode |= SPI_CPHA;
2758 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2759 lookup->mode |= SPI_CPOL;
2760 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2761 lookup->mode |= SPI_CS_HIGH;
2763 } else if (lookup->irq < 0) {
2766 if (acpi_dev_resource_interrupt(ares, 0, &r))
2767 lookup->irq = r.start;
2770 /* Always tell the ACPI core to skip this resource */
2775 * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2776 * @ctlr: controller to which the spi device belongs
2777 * @adev: ACPI Device for the spi device
2778 * @index: Index of the spi resource inside the ACPI Node
2780 * This should be used to allocate a new SPI device from and ACPI Device node.
2781 * The caller is responsible for calling spi_add_device to register the SPI device.
2783 * If ctlr is set to NULL, the Controller for the SPI device will be looked up
2784 * using the resource.
2785 * If index is set to -1, index is not used.
2786 * Note: If index is -1, ctlr must be set.
2788 * Return: a pointer to the new device, or ERR_PTR on error.
2790 struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
2791 struct acpi_device *adev,
2794 acpi_handle parent_handle = NULL;
2795 struct list_head resource_list;
2796 struct acpi_spi_lookup lookup = {};
2797 struct spi_device *spi;
2800 if (!ctlr && index == -1)
2801 return ERR_PTR(-EINVAL);
2805 lookup.index = index;
2808 INIT_LIST_HEAD(&resource_list);
2809 ret = acpi_dev_get_resources(adev, &resource_list,
2810 acpi_spi_add_resource, &lookup);
2811 acpi_dev_free_resource_list(&resource_list);
2814 /* Found SPI in _CRS but it points to another controller */
2815 return ERR_PTR(ret);
2817 if (!lookup.max_speed_hz &&
2818 ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
2819 ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
2820 /* Apple does not use _CRS but nested devices for SPI slaves */
2821 acpi_spi_parse_apple_properties(adev, &lookup);
2824 if (!lookup.max_speed_hz)
2825 return ERR_PTR(-ENODEV);
2827 spi = spi_alloc_device(lookup.ctlr);
2829 dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
2830 dev_name(&adev->dev));
2831 return ERR_PTR(-ENOMEM);
2834 spi_set_all_cs_unused(spi);
2835 spi_set_chipselect(spi, 0, lookup.chip_select);
2837 ACPI_COMPANION_SET(&spi->dev, adev);
2838 spi->max_speed_hz = lookup.max_speed_hz;
2839 spi->mode |= lookup.mode;
2840 spi->irq = lookup.irq;
2841 spi->bits_per_word = lookup.bits_per_word;
2843 * By default spi->chip_select[0] will hold the physical CS number,
2844 * so set bit 0 in spi->cs_index_mask.
2846 spi->cs_index_mask = BIT(0);
2850 EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2852 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2853 struct acpi_device *adev)
2855 struct spi_device *spi;
2857 if (acpi_bus_get_status(adev) || !adev->status.present ||
2858 acpi_device_enumerated(adev))
2861 spi = acpi_spi_device_alloc(ctlr, adev, -1);
2863 if (PTR_ERR(spi) == -ENOMEM)
2864 return AE_NO_MEMORY;
2869 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2870 sizeof(spi->modalias));
2873 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2875 acpi_device_set_enumerated(adev);
2877 adev->power.flags.ignore_parent = true;
2878 if (spi_add_device(spi)) {
2879 adev->power.flags.ignore_parent = false;
2880 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2881 dev_name(&adev->dev));
2888 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2889 void *data, void **return_value)
2891 struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
2892 struct spi_controller *ctlr = data;
2897 return acpi_register_spi_device(ctlr, adev);
2900 #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2902 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2907 handle = ACPI_HANDLE(ctlr->dev.parent);
2911 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2912 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2913 acpi_spi_add_device, NULL, ctlr, NULL);
2914 if (ACPI_FAILURE(status))
2915 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2918 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2919 #endif /* CONFIG_ACPI */
2921 static void spi_controller_release(struct device *dev)
2923 struct spi_controller *ctlr;
2925 ctlr = container_of(dev, struct spi_controller, dev);
2929 static struct class spi_master_class = {
2930 .name = "spi_master",
2931 .dev_release = spi_controller_release,
2932 .dev_groups = spi_master_groups,
2935 #ifdef CONFIG_SPI_SLAVE
2937 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2939 * @spi: device used for the current transfer
2941 int spi_slave_abort(struct spi_device *spi)
2943 struct spi_controller *ctlr = spi->controller;
2945 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2946 return ctlr->slave_abort(ctlr);
2950 EXPORT_SYMBOL_GPL(spi_slave_abort);
2952 int spi_target_abort(struct spi_device *spi)
2954 struct spi_controller *ctlr = spi->controller;
2956 if (spi_controller_is_target(ctlr) && ctlr->target_abort)
2957 return ctlr->target_abort(ctlr);
2961 EXPORT_SYMBOL_GPL(spi_target_abort);
2963 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2966 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2968 struct device *child;
2970 child = device_find_any_child(&ctlr->dev);
2971 return sysfs_emit(buf, "%s\n", child ? to_spi_device(child)->modalias : NULL);
2974 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2975 const char *buf, size_t count)
2977 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2979 struct spi_device *spi;
2980 struct device *child;
2984 rc = sscanf(buf, "%31s", name);
2985 if (rc != 1 || !name[0])
2988 child = device_find_any_child(&ctlr->dev);
2990 /* Remove registered slave */
2991 device_unregister(child);
2995 if (strcmp(name, "(null)")) {
2996 /* Register new slave */
2997 spi = spi_alloc_device(ctlr);
3001 strscpy(spi->modalias, name, sizeof(spi->modalias));
3003 rc = spi_add_device(spi);
3013 static DEVICE_ATTR_RW(slave);
3015 static struct attribute *spi_slave_attrs[] = {
3016 &dev_attr_slave.attr,
3020 static const struct attribute_group spi_slave_group = {
3021 .attrs = spi_slave_attrs,
3024 static const struct attribute_group *spi_slave_groups[] = {
3025 &spi_controller_statistics_group,
3030 static struct class spi_slave_class = {
3031 .name = "spi_slave",
3032 .dev_release = spi_controller_release,
3033 .dev_groups = spi_slave_groups,
3036 extern struct class spi_slave_class; /* dummy */
3040 * __spi_alloc_controller - allocate an SPI master or slave controller
3041 * @dev: the controller, possibly using the platform_bus
3042 * @size: how much zeroed driver-private data to allocate; the pointer to this
3043 * memory is in the driver_data field of the returned device, accessible
3044 * with spi_controller_get_devdata(); the memory is cacheline aligned;
3045 * drivers granting DMA access to portions of their private data need to
3046 * round up @size using ALIGN(size, dma_get_cache_alignment()).
3047 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
3048 * slave (true) controller
3049 * Context: can sleep
3051 * This call is used only by SPI controller drivers, which are the
3052 * only ones directly touching chip registers. It's how they allocate
3053 * an spi_controller structure, prior to calling spi_register_controller().
3055 * This must be called from context that can sleep.
3057 * The caller is responsible for assigning the bus number and initializing the
3058 * controller's methods before calling spi_register_controller(); and (after
3059 * errors adding the device) calling spi_controller_put() to prevent a memory
3062 * Return: the SPI controller structure on success, else NULL.
3064 struct spi_controller *__spi_alloc_controller(struct device *dev,
3065 unsigned int size, bool slave)
3067 struct spi_controller *ctlr;
3068 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
3073 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
3077 device_initialize(&ctlr->dev);
3078 INIT_LIST_HEAD(&ctlr->queue);
3079 spin_lock_init(&ctlr->queue_lock);
3080 spin_lock_init(&ctlr->bus_lock_spinlock);
3081 mutex_init(&ctlr->bus_lock_mutex);
3082 mutex_init(&ctlr->io_mutex);
3083 mutex_init(&ctlr->add_lock);
3085 ctlr->num_chipselect = 1;
3086 ctlr->slave = slave;
3087 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
3088 ctlr->dev.class = &spi_slave_class;
3090 ctlr->dev.class = &spi_master_class;
3091 ctlr->dev.parent = dev;
3092 pm_suspend_ignore_children(&ctlr->dev, true);
3093 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
3097 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
3099 static void devm_spi_release_controller(struct device *dev, void *ctlr)
3101 spi_controller_put(*(struct spi_controller **)ctlr);
3105 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
3106 * @dev: physical device of SPI controller
3107 * @size: how much zeroed driver-private data to allocate
3108 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
3109 * Context: can sleep
3111 * Allocate an SPI controller and automatically release a reference on it
3112 * when @dev is unbound from its driver. Drivers are thus relieved from
3113 * having to call spi_controller_put().
3115 * The arguments to this function are identical to __spi_alloc_controller().
3117 * Return: the SPI controller structure on success, else NULL.
3119 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
3123 struct spi_controller **ptr, *ctlr;
3125 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
3130 ctlr = __spi_alloc_controller(dev, size, slave);
3132 ctlr->devm_allocated = true;
3134 devres_add(dev, ptr);
3141 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
3144 * spi_get_gpio_descs() - grab chip select GPIOs for the master
3145 * @ctlr: The SPI master to grab GPIO descriptors for
3147 static int spi_get_gpio_descs(struct spi_controller *ctlr)
3150 struct gpio_desc **cs;
3151 struct device *dev = &ctlr->dev;
3152 unsigned long native_cs_mask = 0;
3153 unsigned int num_cs_gpios = 0;
3155 nb = gpiod_count(dev, "cs");
3157 /* No GPIOs at all is fine, else return the error */
3163 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
3165 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
3169 ctlr->cs_gpiods = cs;
3171 for (i = 0; i < nb; i++) {
3173 * Most chipselects are active low, the inverted
3174 * semantics are handled by special quirks in gpiolib,
3175 * so initializing them GPIOD_OUT_LOW here means
3176 * "unasserted", in most cases this will drive the physical
3179 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
3182 return PTR_ERR(cs[i]);
3186 * If we find a CS GPIO, name it after the device and
3191 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
3195 gpiod_set_consumer_name(cs[i], gpioname);
3200 if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
3201 dev_err(dev, "Invalid native chip select %d\n", i);
3204 native_cs_mask |= BIT(i);
3207 ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
3209 if ((ctlr->flags & SPI_CONTROLLER_GPIO_SS) && num_cs_gpios &&
3210 ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
3211 dev_err(dev, "No unused native chip select available\n");
3218 static int spi_controller_check_ops(struct spi_controller *ctlr)
3221 * The controller may implement only the high-level SPI-memory like
3222 * operations if it does not support regular SPI transfers, and this is
3224 * If ->mem_ops or ->mem_ops->exec_op is NULL, we request that at least
3225 * one of the ->transfer_xxx() method be implemented.
3227 if (!ctlr->mem_ops || !ctlr->mem_ops->exec_op) {
3228 if (!ctlr->transfer && !ctlr->transfer_one &&
3229 !ctlr->transfer_one_message) {
3237 /* Allocate dynamic bus number using Linux idr */
3238 static int spi_controller_id_alloc(struct spi_controller *ctlr, int start, int end)
3242 mutex_lock(&board_lock);
3243 id = idr_alloc(&spi_master_idr, ctlr, start, end, GFP_KERNEL);
3244 mutex_unlock(&board_lock);
3245 if (WARN(id < 0, "couldn't get idr"))
3246 return id == -ENOSPC ? -EBUSY : id;
3252 * spi_register_controller - register SPI master or slave controller
3253 * @ctlr: initialized master, originally from spi_alloc_master() or
3255 * Context: can sleep
3257 * SPI controllers connect to their drivers using some non-SPI bus,
3258 * such as the platform bus. The final stage of probe() in that code
3259 * includes calling spi_register_controller() to hook up to this SPI bus glue.
3261 * SPI controllers use board specific (often SOC specific) bus numbers,
3262 * and board-specific addressing for SPI devices combines those numbers
3263 * with chip select numbers. Since SPI does not directly support dynamic
3264 * device identification, boards need configuration tables telling which
3265 * chip is at which address.
3267 * This must be called from context that can sleep. It returns zero on
3268 * success, else a negative error code (dropping the controller's refcount).
3269 * After a successful return, the caller is responsible for calling
3270 * spi_unregister_controller().
3272 * Return: zero on success, else a negative error code.
3274 int spi_register_controller(struct spi_controller *ctlr)
3276 struct device *dev = ctlr->dev.parent;
3277 struct boardinfo *bi;
3286 * Make sure all necessary hooks are implemented before registering
3287 * the SPI controller.
3289 status = spi_controller_check_ops(ctlr);
3293 if (ctlr->bus_num < 0)
3294 ctlr->bus_num = of_alias_get_id(ctlr->dev.of_node, "spi");
3295 if (ctlr->bus_num >= 0) {
3296 /* Devices with a fixed bus num must check-in with the num */
3297 status = spi_controller_id_alloc(ctlr, ctlr->bus_num, ctlr->bus_num + 1);
3301 if (ctlr->bus_num < 0) {
3302 first_dynamic = of_alias_get_highest_id("spi");
3303 if (first_dynamic < 0)
3308 status = spi_controller_id_alloc(ctlr, first_dynamic, 0);
3312 ctlr->bus_lock_flag = 0;
3313 init_completion(&ctlr->xfer_completion);
3314 init_completion(&ctlr->cur_msg_completion);
3315 if (!ctlr->max_dma_len)
3316 ctlr->max_dma_len = INT_MAX;
3319 * Register the device, then userspace will see it.
3320 * Registration fails if the bus ID is in use.
3322 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
3324 if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
3325 status = spi_get_gpio_descs(ctlr);
3329 * A controller using GPIO descriptors always
3330 * supports SPI_CS_HIGH if need be.
3332 ctlr->mode_bits |= SPI_CS_HIGH;
3336 * Even if it's just one always-selected device, there must
3337 * be at least one chipselect.
3339 if (!ctlr->num_chipselect) {
3344 /* Setting last_cs to SPI_INVALID_CS means no chip selected */
3345 for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
3346 ctlr->last_cs[idx] = SPI_INVALID_CS;
3348 status = device_add(&ctlr->dev);
3351 dev_dbg(dev, "registered %s %s\n",
3352 spi_controller_is_slave(ctlr) ? "slave" : "master",
3353 dev_name(&ctlr->dev));
3356 * If we're using a queued driver, start the queue. Note that we don't
3357 * need the queueing logic if the driver is only supporting high-level
3358 * memory operations.
3360 if (ctlr->transfer) {
3361 dev_info(dev, "controller is unqueued, this is deprecated\n");
3362 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
3363 status = spi_controller_initialize_queue(ctlr);
3365 device_del(&ctlr->dev);
3369 /* Add statistics */
3370 ctlr->pcpu_statistics = spi_alloc_pcpu_stats(dev);
3371 if (!ctlr->pcpu_statistics) {
3372 dev_err(dev, "Error allocating per-cpu statistics\n");
3377 mutex_lock(&board_lock);
3378 list_add_tail(&ctlr->list, &spi_controller_list);
3379 list_for_each_entry(bi, &board_list, list)
3380 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
3381 mutex_unlock(&board_lock);
3383 /* Register devices from the device tree and ACPI */
3384 of_register_spi_devices(ctlr);
3385 acpi_register_spi_devices(ctlr);
3389 spi_destroy_queue(ctlr);
3391 mutex_lock(&board_lock);
3392 idr_remove(&spi_master_idr, ctlr->bus_num);
3393 mutex_unlock(&board_lock);
3396 EXPORT_SYMBOL_GPL(spi_register_controller);
3398 static void devm_spi_unregister(struct device *dev, void *res)
3400 spi_unregister_controller(*(struct spi_controller **)res);
3404 * devm_spi_register_controller - register managed SPI master or slave
3406 * @dev: device managing SPI controller
3407 * @ctlr: initialized controller, originally from spi_alloc_master() or
3409 * Context: can sleep
3411 * Register a SPI device as with spi_register_controller() which will
3412 * automatically be unregistered and freed.
3414 * Return: zero on success, else a negative error code.
3416 int devm_spi_register_controller(struct device *dev,
3417 struct spi_controller *ctlr)
3419 struct spi_controller **ptr;
3422 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
3426 ret = spi_register_controller(ctlr);
3429 devres_add(dev, ptr);
3436 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3438 static int __unregister(struct device *dev, void *null)
3440 spi_unregister_device(to_spi_device(dev));
3445 * spi_unregister_controller - unregister SPI master or slave controller
3446 * @ctlr: the controller being unregistered
3447 * Context: can sleep
3449 * This call is used only by SPI controller drivers, which are the
3450 * only ones directly touching chip registers.
3452 * This must be called from context that can sleep.
3454 * Note that this function also drops a reference to the controller.
3456 void spi_unregister_controller(struct spi_controller *ctlr)
3458 struct spi_controller *found;
3459 int id = ctlr->bus_num;
3461 /* Prevent addition of new devices, unregister existing ones */
3462 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3463 mutex_lock(&ctlr->add_lock);
3465 device_for_each_child(&ctlr->dev, NULL, __unregister);
3467 /* First make sure that this controller was ever added */
3468 mutex_lock(&board_lock);
3469 found = idr_find(&spi_master_idr, id);
3470 mutex_unlock(&board_lock);
3472 if (spi_destroy_queue(ctlr))
3473 dev_err(&ctlr->dev, "queue remove failed\n");
3475 mutex_lock(&board_lock);
3476 list_del(&ctlr->list);
3477 mutex_unlock(&board_lock);
3479 device_del(&ctlr->dev);
3482 mutex_lock(&board_lock);
3484 idr_remove(&spi_master_idr, id);
3485 mutex_unlock(&board_lock);
3487 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
3488 mutex_unlock(&ctlr->add_lock);
3491 * Release the last reference on the controller if its driver
3492 * has not yet been converted to devm_spi_alloc_master/slave().
3494 if (!ctlr->devm_allocated)
3495 put_device(&ctlr->dev);
3497 EXPORT_SYMBOL_GPL(spi_unregister_controller);
3499 static inline int __spi_check_suspended(const struct spi_controller *ctlr)
3501 return ctlr->flags & SPI_CONTROLLER_SUSPENDED ? -ESHUTDOWN : 0;
3504 static inline void __spi_mark_suspended(struct spi_controller *ctlr)
3506 mutex_lock(&ctlr->bus_lock_mutex);
3507 ctlr->flags |= SPI_CONTROLLER_SUSPENDED;
3508 mutex_unlock(&ctlr->bus_lock_mutex);
3511 static inline void __spi_mark_resumed(struct spi_controller *ctlr)
3513 mutex_lock(&ctlr->bus_lock_mutex);
3514 ctlr->flags &= ~SPI_CONTROLLER_SUSPENDED;
3515 mutex_unlock(&ctlr->bus_lock_mutex);
3518 int spi_controller_suspend(struct spi_controller *ctlr)
3522 /* Basically no-ops for non-queued controllers */
3524 ret = spi_stop_queue(ctlr);
3526 dev_err(&ctlr->dev, "queue stop failed\n");
3529 __spi_mark_suspended(ctlr);
3532 EXPORT_SYMBOL_GPL(spi_controller_suspend);
3534 int spi_controller_resume(struct spi_controller *ctlr)
3538 __spi_mark_resumed(ctlr);
3541 ret = spi_start_queue(ctlr);
3543 dev_err(&ctlr->dev, "queue restart failed\n");
3547 EXPORT_SYMBOL_GPL(spi_controller_resume);
3549 /*-------------------------------------------------------------------------*/
3551 /* Core methods for spi_message alterations */
3553 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3554 struct spi_message *msg,
3557 struct spi_replaced_transfers *rxfer = res;
3560 /* Call extra callback if requested */
3562 rxfer->release(ctlr, msg, res);
3564 /* Insert replaced transfers back into the message */
3565 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3567 /* Remove the formerly inserted entries */
3568 for (i = 0; i < rxfer->inserted; i++)
3569 list_del(&rxfer->inserted_transfers[i].transfer_list);
3573 * spi_replace_transfers - replace transfers with several transfers
3574 * and register change with spi_message.resources
3575 * @msg: the spi_message we work upon
3576 * @xfer_first: the first spi_transfer we want to replace
3577 * @remove: number of transfers to remove
3578 * @insert: the number of transfers we want to insert instead
3579 * @release: extra release code necessary in some circumstances
3580 * @extradatasize: extra data to allocate (with alignment guarantees
3581 * of struct @spi_transfer)
3584 * Returns: pointer to @spi_replaced_transfers,
3585 * PTR_ERR(...) in case of errors.
3587 static struct spi_replaced_transfers *spi_replace_transfers(
3588 struct spi_message *msg,
3589 struct spi_transfer *xfer_first,
3592 spi_replaced_release_t release,
3593 size_t extradatasize,
3596 struct spi_replaced_transfers *rxfer;
3597 struct spi_transfer *xfer;
3600 /* Allocate the structure using spi_res */
3601 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3602 struct_size(rxfer, inserted_transfers, insert)
3606 return ERR_PTR(-ENOMEM);
3608 /* The release code to invoke before running the generic release */
3609 rxfer->release = release;
3611 /* Assign extradata */
3614 &rxfer->inserted_transfers[insert];
3616 /* Init the replaced_transfers list */
3617 INIT_LIST_HEAD(&rxfer->replaced_transfers);
3620 * Assign the list_entry after which we should reinsert
3621 * the @replaced_transfers - it may be spi_message.messages!
3623 rxfer->replaced_after = xfer_first->transfer_list.prev;
3625 /* Remove the requested number of transfers */
3626 for (i = 0; i < remove; i++) {
3628 * If the entry after replaced_after it is msg->transfers
3629 * then we have been requested to remove more transfers
3630 * than are in the list.
3632 if (rxfer->replaced_after->next == &msg->transfers) {
3633 dev_err(&msg->spi->dev,
3634 "requested to remove more spi_transfers than are available\n");
3635 /* Insert replaced transfers back into the message */
3636 list_splice(&rxfer->replaced_transfers,
3637 rxfer->replaced_after);
3639 /* Free the spi_replace_transfer structure... */
3640 spi_res_free(rxfer);
3642 /* ...and return with an error */
3643 return ERR_PTR(-EINVAL);
3647 * Remove the entry after replaced_after from list of
3648 * transfers and add it to list of replaced_transfers.
3650 list_move_tail(rxfer->replaced_after->next,
3651 &rxfer->replaced_transfers);
3655 * Create copy of the given xfer with identical settings
3656 * based on the first transfer to get removed.
3658 for (i = 0; i < insert; i++) {
3659 /* We need to run in reverse order */
3660 xfer = &rxfer->inserted_transfers[insert - 1 - i];
3662 /* Copy all spi_transfer data */
3663 memcpy(xfer, xfer_first, sizeof(*xfer));
3666 list_add(&xfer->transfer_list, rxfer->replaced_after);
3668 /* Clear cs_change and delay for all but the last */
3670 xfer->cs_change = false;
3671 xfer->delay.value = 0;
3675 /* Set up inserted... */
3676 rxfer->inserted = insert;
3678 /* ...and register it with spi_res/spi_message */
3679 spi_res_add(msg, rxfer);
3684 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3685 struct spi_message *msg,
3686 struct spi_transfer **xferp,
3689 struct spi_transfer *xfer = *xferp, *xfers;
3690 struct spi_replaced_transfers *srt;
3694 /* Calculate how many we have to replace */
3695 count = DIV_ROUND_UP(xfer->len, maxsize);
3697 /* Create replacement */
3698 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, GFP_KERNEL);
3700 return PTR_ERR(srt);
3701 xfers = srt->inserted_transfers;
3704 * Now handle each of those newly inserted spi_transfers.
3705 * Note that the replacements spi_transfers all are preset
3706 * to the same values as *xferp, so tx_buf, rx_buf and len
3707 * are all identical (as well as most others)
3708 * so we just have to fix up len and the pointers.
3712 * The first transfer just needs the length modified, so we
3713 * run it outside the loop.
3715 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3717 /* All the others need rx_buf/tx_buf also set */
3718 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3719 /* Update rx_buf, tx_buf and DMA */
3720 if (xfers[i].rx_buf)
3721 xfers[i].rx_buf += offset;
3722 if (xfers[i].tx_buf)
3723 xfers[i].tx_buf += offset;
3726 xfers[i].len = min(maxsize, xfers[i].len - offset);
3730 * We set up xferp to the last entry we have inserted,
3731 * so that we skip those already split transfers.
3733 *xferp = &xfers[count - 1];
3735 /* Increment statistics counters */
3736 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics,
3737 transfers_split_maxsize);
3738 SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics,
3739 transfers_split_maxsize);
3745 * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3746 * when an individual transfer exceeds a
3748 * @ctlr: the @spi_controller for this transfer
3749 * @msg: the @spi_message to transform
3750 * @maxsize: the maximum when to apply this
3752 * This function allocates resources that are automatically freed during the
3753 * spi message unoptimize phase so this function should only be called from
3754 * optimize_message callbacks.
3756 * Return: status of transformation
3758 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3759 struct spi_message *msg,
3762 struct spi_transfer *xfer;
3766 * Iterate over the transfer_list,
3767 * but note that xfer is advanced to the last transfer inserted
3768 * to avoid checking sizes again unnecessarily (also xfer does
3769 * potentially belong to a different list by the time the
3770 * replacement has happened).
3772 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3773 if (xfer->len > maxsize) {
3774 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3783 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3787 * spi_split_transfers_maxwords - split SPI transfers into multiple transfers
3788 * when an individual transfer exceeds a
3789 * certain number of SPI words
3790 * @ctlr: the @spi_controller for this transfer
3791 * @msg: the @spi_message to transform
3792 * @maxwords: the number of words to limit each transfer to
3794 * This function allocates resources that are automatically freed during the
3795 * spi message unoptimize phase so this function should only be called from
3796 * optimize_message callbacks.
3798 * Return: status of transformation
3800 int spi_split_transfers_maxwords(struct spi_controller *ctlr,
3801 struct spi_message *msg,
3804 struct spi_transfer *xfer;
3807 * Iterate over the transfer_list,
3808 * but note that xfer is advanced to the last transfer inserted
3809 * to avoid checking sizes again unnecessarily (also xfer does
3810 * potentially belong to a different list by the time the
3811 * replacement has happened).
3813 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3817 maxsize = maxwords * roundup_pow_of_two(BITS_TO_BYTES(xfer->bits_per_word));
3818 if (xfer->len > maxsize) {
3819 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3828 EXPORT_SYMBOL_GPL(spi_split_transfers_maxwords);
3830 /*-------------------------------------------------------------------------*/
3833 * Core methods for SPI controller protocol drivers. Some of the
3834 * other core methods are currently defined as inline functions.
3837 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3840 if (ctlr->bits_per_word_mask) {
3841 /* Only 32 bits fit in the mask */
3842 if (bits_per_word > 32)
3844 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3852 * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3853 * @spi: the device that requires specific CS timing configuration
3855 * Return: zero on success, else a negative error code.
3857 static int spi_set_cs_timing(struct spi_device *spi)
3859 struct device *parent = spi->controller->dev.parent;
3862 if (spi->controller->set_cs_timing && !spi_get_csgpiod(spi, 0)) {
3863 if (spi->controller->auto_runtime_pm) {
3864 status = pm_runtime_get_sync(parent);
3866 pm_runtime_put_noidle(parent);
3867 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3872 status = spi->controller->set_cs_timing(spi);
3873 pm_runtime_mark_last_busy(parent);
3874 pm_runtime_put_autosuspend(parent);
3876 status = spi->controller->set_cs_timing(spi);
3883 * spi_setup - setup SPI mode and clock rate
3884 * @spi: the device whose settings are being modified
3885 * Context: can sleep, and no requests are queued to the device
3887 * SPI protocol drivers may need to update the transfer mode if the
3888 * device doesn't work with its default. They may likewise need
3889 * to update clock rates or word sizes from initial values. This function
3890 * changes those settings, and must be called from a context that can sleep.
3891 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3892 * effect the next time the device is selected and data is transferred to
3893 * or from it. When this function returns, the SPI device is deselected.
3895 * Note that this call will fail if the protocol driver specifies an option
3896 * that the underlying controller or its driver does not support. For
3897 * example, not all hardware supports wire transfers using nine bit words,
3898 * LSB-first wire encoding, or active-high chipselects.
3900 * Return: zero on success, else a negative error code.
3902 int spi_setup(struct spi_device *spi)
3904 unsigned bad_bits, ugly_bits;
3908 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3909 * are set at the same time.
3911 if ((hweight_long(spi->mode &
3912 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3913 (hweight_long(spi->mode &
3914 (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3916 "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3919 /* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3920 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3921 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3922 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3925 * Help drivers fail *cleanly* when they need options
3926 * that aren't supported with their current controller.
3927 * SPI_CS_WORD has a fallback software implementation,
3928 * so it is ignored here.
3930 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3931 SPI_NO_TX | SPI_NO_RX);
3932 ugly_bits = bad_bits &
3933 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3934 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3937 "setup: ignoring unsupported mode bits %x\n",
3939 spi->mode &= ~ugly_bits;
3940 bad_bits &= ~ugly_bits;
3943 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3948 if (!spi->bits_per_word) {
3949 spi->bits_per_word = 8;
3952 * Some controllers may not support the default 8 bits-per-word
3953 * so only perform the check when this is explicitly provided.
3955 status = __spi_validate_bits_per_word(spi->controller,
3956 spi->bits_per_word);
3961 if (spi->controller->max_speed_hz &&
3962 (!spi->max_speed_hz ||
3963 spi->max_speed_hz > spi->controller->max_speed_hz))
3964 spi->max_speed_hz = spi->controller->max_speed_hz;
3966 mutex_lock(&spi->controller->io_mutex);
3968 if (spi->controller->setup) {
3969 status = spi->controller->setup(spi);
3971 mutex_unlock(&spi->controller->io_mutex);
3972 dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3978 status = spi_set_cs_timing(spi);
3980 mutex_unlock(&spi->controller->io_mutex);
3984 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3985 status = pm_runtime_resume_and_get(spi->controller->dev.parent);
3987 mutex_unlock(&spi->controller->io_mutex);
3988 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3994 * We do not want to return positive value from pm_runtime_get,
3995 * there are many instances of devices calling spi_setup() and
3996 * checking for a non-zero return value instead of a negative
4001 spi_set_cs(spi, false, true);
4002 pm_runtime_mark_last_busy(spi->controller->dev.parent);
4003 pm_runtime_put_autosuspend(spi->controller->dev.parent);
4005 spi_set_cs(spi, false, true);
4008 mutex_unlock(&spi->controller->io_mutex);
4010 if (spi->rt && !spi->controller->rt) {
4011 spi->controller->rt = true;
4012 spi_set_thread_rt(spi->controller);
4015 trace_spi_setup(spi, status);
4017 dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
4018 spi->mode & SPI_MODE_X_MASK,
4019 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
4020 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
4021 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
4022 (spi->mode & SPI_LOOP) ? "loopback, " : "",
4023 spi->bits_per_word, spi->max_speed_hz,
4028 EXPORT_SYMBOL_GPL(spi_setup);
4030 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
4031 struct spi_device *spi)
4035 delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
4039 delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
4043 if (delay1 < delay2)
4044 memcpy(&xfer->word_delay, &spi->word_delay,
4045 sizeof(xfer->word_delay));
4050 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
4052 struct spi_controller *ctlr = spi->controller;
4053 struct spi_transfer *xfer;
4056 if (list_empty(&message->transfers))
4062 * Half-duplex links include original MicroWire, and ones with
4063 * only one data pin like SPI_3WIRE (switches direction) or where
4064 * either MOSI or MISO is missing. They can also be caused by
4065 * software limitations.
4067 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
4068 (spi->mode & SPI_3WIRE)) {
4069 unsigned flags = ctlr->flags;
4071 list_for_each_entry(xfer, &message->transfers, transfer_list) {
4072 if (xfer->rx_buf && xfer->tx_buf)
4074 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
4076 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
4082 * Set transfer bits_per_word and max speed as spi device default if
4083 * it is not set for this transfer.
4084 * Set transfer tx_nbits and rx_nbits as single transfer default
4085 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
4086 * Ensure transfer word_delay is at least as long as that required by
4089 message->frame_length = 0;
4090 list_for_each_entry(xfer, &message->transfers, transfer_list) {
4091 xfer->effective_speed_hz = 0;
4092 message->frame_length += xfer->len;
4093 if (!xfer->bits_per_word)
4094 xfer->bits_per_word = spi->bits_per_word;
4096 if (!xfer->speed_hz)
4097 xfer->speed_hz = spi->max_speed_hz;
4099 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
4100 xfer->speed_hz = ctlr->max_speed_hz;
4102 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
4106 * SPI transfer length should be multiple of SPI word size
4107 * where SPI word size should be power-of-two multiple.
4109 if (xfer->bits_per_word <= 8)
4111 else if (xfer->bits_per_word <= 16)
4116 /* No partial transfers accepted */
4117 if (xfer->len % w_size)
4120 if (xfer->speed_hz && ctlr->min_speed_hz &&
4121 xfer->speed_hz < ctlr->min_speed_hz)
4124 if (xfer->tx_buf && !xfer->tx_nbits)
4125 xfer->tx_nbits = SPI_NBITS_SINGLE;
4126 if (xfer->rx_buf && !xfer->rx_nbits)
4127 xfer->rx_nbits = SPI_NBITS_SINGLE;
4129 * Check transfer tx/rx_nbits:
4130 * 1. check the value matches one of single, dual and quad
4131 * 2. check tx/rx_nbits match the mode in spi_device
4134 if (spi->mode & SPI_NO_TX)
4136 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
4137 xfer->tx_nbits != SPI_NBITS_DUAL &&
4138 xfer->tx_nbits != SPI_NBITS_QUAD)
4140 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
4141 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
4143 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
4144 !(spi->mode & SPI_TX_QUAD))
4147 /* Check transfer rx_nbits */
4149 if (spi->mode & SPI_NO_RX)
4151 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
4152 xfer->rx_nbits != SPI_NBITS_DUAL &&
4153 xfer->rx_nbits != SPI_NBITS_QUAD)
4155 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
4156 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
4158 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
4159 !(spi->mode & SPI_RX_QUAD))
4163 if (_spi_xfer_word_delay_update(xfer, spi))
4167 message->status = -EINPROGRESS;
4173 * spi_split_transfers - generic handling of transfer splitting
4174 * @msg: the message to split
4176 * Under certain conditions, a SPI controller may not support arbitrary
4177 * transfer sizes or other features required by a peripheral. This function
4178 * will split the transfers in the message into smaller transfers that are
4179 * supported by the controller.
4181 * Controllers with special requirements not covered here can also split
4182 * transfers in the optimize_message() callback.
4184 * Context: can sleep
4185 * Return: zero on success, else a negative error code
4187 static int spi_split_transfers(struct spi_message *msg)
4189 struct spi_controller *ctlr = msg->spi->controller;
4190 struct spi_transfer *xfer;
4194 * If an SPI controller does not support toggling the CS line on each
4195 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
4196 * for the CS line, we can emulate the CS-per-word hardware function by
4197 * splitting transfers into one-word transfers and ensuring that
4198 * cs_change is set for each transfer.
4200 if ((msg->spi->mode & SPI_CS_WORD) &&
4201 (!(ctlr->mode_bits & SPI_CS_WORD) || spi_is_csgpiod(msg->spi))) {
4202 ret = spi_split_transfers_maxwords(ctlr, msg, 1);
4206 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
4207 /* Don't change cs_change on the last entry in the list */
4208 if (list_is_last(&xfer->transfer_list, &msg->transfers))
4211 xfer->cs_change = 1;
4214 ret = spi_split_transfers_maxsize(ctlr, msg,
4215 spi_max_transfer_size(msg->spi));
4224 * __spi_optimize_message - shared implementation for spi_optimize_message()
4225 * and spi_maybe_optimize_message()
4226 * @spi: the device that will be used for the message
4227 * @msg: the message to optimize
4229 * Peripheral drivers will call spi_optimize_message() and the spi core will
4230 * call spi_maybe_optimize_message() instead of calling this directly.
4232 * It is not valid to call this on a message that has already been optimized.
4234 * Return: zero on success, else a negative error code
4236 static int __spi_optimize_message(struct spi_device *spi,
4237 struct spi_message *msg)
4239 struct spi_controller *ctlr = spi->controller;
4242 ret = __spi_validate(spi, msg);
4246 ret = spi_split_transfers(msg);
4250 if (ctlr->optimize_message) {
4251 ret = ctlr->optimize_message(msg);
4253 spi_res_release(ctlr, msg);
4258 msg->optimized = true;
4264 * spi_maybe_optimize_message - optimize message if it isn't already pre-optimized
4265 * @spi: the device that will be used for the message
4266 * @msg: the message to optimize
4267 * Return: zero on success, else a negative error code
4269 static int spi_maybe_optimize_message(struct spi_device *spi,
4270 struct spi_message *msg)
4272 if (msg->pre_optimized)
4275 return __spi_optimize_message(spi, msg);
4279 * spi_optimize_message - do any one-time validation and setup for a SPI message
4280 * @spi: the device that will be used for the message
4281 * @msg: the message to optimize
4283 * Peripheral drivers that reuse the same message repeatedly may call this to
4284 * perform as much message prep as possible once, rather than repeating it each
4285 * time a message transfer is performed to improve throughput and reduce CPU
4288 * Once a message has been optimized, it cannot be modified with the exception
4289 * of updating the contents of any xfer->tx_buf (the pointer can't be changed,
4290 * only the data in the memory it points to).
4292 * Calls to this function must be balanced with calls to spi_unoptimize_message()
4293 * to avoid leaking resources.
4295 * Context: can sleep
4296 * Return: zero on success, else a negative error code
4298 int spi_optimize_message(struct spi_device *spi, struct spi_message *msg)
4302 ret = __spi_optimize_message(spi, msg);
4307 * This flag indicates that the peripheral driver called spi_optimize_message()
4308 * and therefore we shouldn't unoptimize message automatically when finalizing
4309 * the message but rather wait until spi_unoptimize_message() is called
4310 * by the peripheral driver.
4312 msg->pre_optimized = true;
4316 EXPORT_SYMBOL_GPL(spi_optimize_message);
4319 * spi_unoptimize_message - releases any resources allocated by spi_optimize_message()
4320 * @msg: the message to unoptimize
4322 * Calls to this function must be balanced with calls to spi_optimize_message().
4324 * Context: can sleep
4326 void spi_unoptimize_message(struct spi_message *msg)
4328 __spi_unoptimize_message(msg);
4329 msg->pre_optimized = false;
4331 EXPORT_SYMBOL_GPL(spi_unoptimize_message);
4333 static int __spi_async(struct spi_device *spi, struct spi_message *message)
4335 struct spi_controller *ctlr = spi->controller;
4336 struct spi_transfer *xfer;
4339 * Some controllers do not support doing regular SPI transfers. Return
4340 * ENOTSUPP when this is the case.
4342 if (!ctlr->transfer)
4345 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async);
4346 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async);
4348 trace_spi_message_submit(message);
4350 if (!ctlr->ptp_sts_supported) {
4351 list_for_each_entry(xfer, &message->transfers, transfer_list) {
4352 xfer->ptp_sts_word_pre = 0;
4353 ptp_read_system_prets(xfer->ptp_sts);
4357 return ctlr->transfer(spi, message);
4361 * spi_async - asynchronous SPI transfer
4362 * @spi: device with which data will be exchanged
4363 * @message: describes the data transfers, including completion callback
4364 * Context: any (IRQs may be blocked, etc)
4366 * This call may be used in_irq and other contexts which can't sleep,
4367 * as well as from task contexts which can sleep.
4369 * The completion callback is invoked in a context which can't sleep.
4370 * Before that invocation, the value of message->status is undefined.
4371 * When the callback is issued, message->status holds either zero (to
4372 * indicate complete success) or a negative error code. After that
4373 * callback returns, the driver which issued the transfer request may
4374 * deallocate the associated memory; it's no longer in use by any SPI
4375 * core or controller driver code.
4377 * Note that although all messages to a spi_device are handled in
4378 * FIFO order, messages may go to different devices in other orders.
4379 * Some device might be higher priority, or have various "hard" access
4380 * time requirements, for example.
4382 * On detection of any fault during the transfer, processing of
4383 * the entire message is aborted, and the device is deselected.
4384 * Until returning from the associated message completion callback,
4385 * no other spi_message queued to that device will be processed.
4386 * (This rule applies equally to all the synchronous transfer calls,
4387 * which are wrappers around this core asynchronous primitive.)
4389 * Return: zero on success, else a negative error code.
4391 int spi_async(struct spi_device *spi, struct spi_message *message)
4393 struct spi_controller *ctlr = spi->controller;
4395 unsigned long flags;
4397 ret = spi_maybe_optimize_message(spi, message);
4401 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4403 if (ctlr->bus_lock_flag)
4406 ret = __spi_async(spi, message);
4408 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4410 spi_maybe_unoptimize_message(message);
4414 EXPORT_SYMBOL_GPL(spi_async);
4416 static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg)
4421 mutex_lock(&ctlr->io_mutex);
4423 was_busy = ctlr->busy;
4425 ctlr->cur_msg = msg;
4426 ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
4428 dev_err(&ctlr->dev, "noqueue transfer failed\n");
4429 ctlr->cur_msg = NULL;
4430 ctlr->fallback = false;
4433 kfree(ctlr->dummy_rx);
4434 ctlr->dummy_rx = NULL;
4435 kfree(ctlr->dummy_tx);
4436 ctlr->dummy_tx = NULL;
4437 if (ctlr->unprepare_transfer_hardware &&
4438 ctlr->unprepare_transfer_hardware(ctlr))
4440 "failed to unprepare transfer hardware\n");
4441 spi_idle_runtime_pm(ctlr);
4444 mutex_unlock(&ctlr->io_mutex);
4447 /*-------------------------------------------------------------------------*/
4450 * Utility methods for SPI protocol drivers, layered on
4451 * top of the core. Some other utility methods are defined as
4455 static void spi_complete(void *arg)
4460 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
4462 DECLARE_COMPLETION_ONSTACK(done);
4463 unsigned long flags;
4465 struct spi_controller *ctlr = spi->controller;
4467 if (__spi_check_suspended(ctlr)) {
4468 dev_warn_once(&spi->dev, "Attempted to sync while suspend\n");
4472 status = spi_maybe_optimize_message(spi, message);
4476 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync);
4477 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync);
4480 * Checking queue_empty here only guarantees async/sync message
4481 * ordering when coming from the same context. It does not need to
4482 * guard against reentrancy from a different context. The io_mutex
4483 * will catch those cases.
4485 if (READ_ONCE(ctlr->queue_empty) && !ctlr->must_async) {
4486 message->actual_length = 0;
4487 message->status = -EINPROGRESS;
4489 trace_spi_message_submit(message);
4491 SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate);
4492 SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate);
4494 __spi_transfer_message_noqueue(ctlr, message);
4496 return message->status;
4500 * There are messages in the async queue that could have originated
4501 * from the same context, so we need to preserve ordering.
4502 * Therefor we send the message to the async queue and wait until they
4505 message->complete = spi_complete;
4506 message->context = &done;
4508 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4509 status = __spi_async(spi, message);
4510 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4513 wait_for_completion(&done);
4514 status = message->status;
4516 message->complete = NULL;
4517 message->context = NULL;
4523 * spi_sync - blocking/synchronous SPI data transfers
4524 * @spi: device with which data will be exchanged
4525 * @message: describes the data transfers
4526 * Context: can sleep
4528 * This call may only be used from a context that may sleep. The sleep
4529 * is non-interruptible, and has no timeout. Low-overhead controller
4530 * drivers may DMA directly into and out of the message buffers.
4532 * Note that the SPI device's chip select is active during the message,
4533 * and then is normally disabled between messages. Drivers for some
4534 * frequently-used devices may want to minimize costs of selecting a chip,
4535 * by leaving it selected in anticipation that the next message will go
4536 * to the same chip. (That may increase power usage.)
4538 * Also, the caller is guaranteeing that the memory associated with the
4539 * message will not be freed before this call returns.
4541 * Return: zero on success, else a negative error code.
4543 int spi_sync(struct spi_device *spi, struct spi_message *message)
4547 mutex_lock(&spi->controller->bus_lock_mutex);
4548 ret = __spi_sync(spi, message);
4549 mutex_unlock(&spi->controller->bus_lock_mutex);
4553 EXPORT_SYMBOL_GPL(spi_sync);
4556 * spi_sync_locked - version of spi_sync with exclusive bus usage
4557 * @spi: device with which data will be exchanged
4558 * @message: describes the data transfers
4559 * Context: can sleep
4561 * This call may only be used from a context that may sleep. The sleep
4562 * is non-interruptible, and has no timeout. Low-overhead controller
4563 * drivers may DMA directly into and out of the message buffers.
4565 * This call should be used by drivers that require exclusive access to the
4566 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4567 * be released by a spi_bus_unlock call when the exclusive access is over.
4569 * Return: zero on success, else a negative error code.
4571 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4573 return __spi_sync(spi, message);
4575 EXPORT_SYMBOL_GPL(spi_sync_locked);
4578 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
4579 * @ctlr: SPI bus master that should be locked for exclusive bus access
4580 * Context: can sleep
4582 * This call may only be used from a context that may sleep. The sleep
4583 * is non-interruptible, and has no timeout.
4585 * This call should be used by drivers that require exclusive access to the
4586 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4587 * exclusive access is over. Data transfer must be done by spi_sync_locked
4588 * and spi_async_locked calls when the SPI bus lock is held.
4590 * Return: always zero.
4592 int spi_bus_lock(struct spi_controller *ctlr)
4594 unsigned long flags;
4596 mutex_lock(&ctlr->bus_lock_mutex);
4598 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4599 ctlr->bus_lock_flag = 1;
4600 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4602 /* Mutex remains locked until spi_bus_unlock() is called */
4606 EXPORT_SYMBOL_GPL(spi_bus_lock);
4609 * spi_bus_unlock - release the lock for exclusive SPI bus usage
4610 * @ctlr: SPI bus master that was locked for exclusive bus access
4611 * Context: can sleep
4613 * This call may only be used from a context that may sleep. The sleep
4614 * is non-interruptible, and has no timeout.
4616 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4619 * Return: always zero.
4621 int spi_bus_unlock(struct spi_controller *ctlr)
4623 ctlr->bus_lock_flag = 0;
4625 mutex_unlock(&ctlr->bus_lock_mutex);
4629 EXPORT_SYMBOL_GPL(spi_bus_unlock);
4631 /* Portable code must never pass more than 32 bytes */
4632 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
4637 * spi_write_then_read - SPI synchronous write followed by read
4638 * @spi: device with which data will be exchanged
4639 * @txbuf: data to be written (need not be DMA-safe)
4640 * @n_tx: size of txbuf, in bytes
4641 * @rxbuf: buffer into which data will be read (need not be DMA-safe)
4642 * @n_rx: size of rxbuf, in bytes
4643 * Context: can sleep
4645 * This performs a half duplex MicroWire style transaction with the
4646 * device, sending txbuf and then reading rxbuf. The return value
4647 * is zero for success, else a negative errno status code.
4648 * This call may only be used from a context that may sleep.
4650 * Parameters to this routine are always copied using a small buffer.
4651 * Performance-sensitive or bulk transfer code should instead use
4652 * spi_{async,sync}() calls with DMA-safe buffers.
4654 * Return: zero on success, else a negative error code.
4656 int spi_write_then_read(struct spi_device *spi,
4657 const void *txbuf, unsigned n_tx,
4658 void *rxbuf, unsigned n_rx)
4660 static DEFINE_MUTEX(lock);
4663 struct spi_message message;
4664 struct spi_transfer x[2];
4668 * Use preallocated DMA-safe buffer if we can. We can't avoid
4669 * copying here, (as a pure convenience thing), but we can
4670 * keep heap costs out of the hot path unless someone else is
4671 * using the pre-allocated buffer or the transfer is too large.
4673 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4674 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4675 GFP_KERNEL | GFP_DMA);
4682 spi_message_init(&message);
4683 memset(x, 0, sizeof(x));
4686 spi_message_add_tail(&x[0], &message);
4690 spi_message_add_tail(&x[1], &message);
4693 memcpy(local_buf, txbuf, n_tx);
4694 x[0].tx_buf = local_buf;
4695 x[1].rx_buf = local_buf + n_tx;
4698 status = spi_sync(spi, &message);
4700 memcpy(rxbuf, x[1].rx_buf, n_rx);
4702 if (x[0].tx_buf == buf)
4703 mutex_unlock(&lock);
4709 EXPORT_SYMBOL_GPL(spi_write_then_read);
4711 /*-------------------------------------------------------------------------*/
4713 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4714 /* Must call put_device() when done with returned spi_device device */
4715 static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4717 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4719 return dev ? to_spi_device(dev) : NULL;
4722 /* The spi controllers are not using spi_bus, so we find it with another way */
4723 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4727 dev = class_find_device_by_of_node(&spi_master_class, node);
4728 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4729 dev = class_find_device_by_of_node(&spi_slave_class, node);
4733 /* Reference got in class_find_device */
4734 return container_of(dev, struct spi_controller, dev);
4737 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4740 struct of_reconfig_data *rd = arg;
4741 struct spi_controller *ctlr;
4742 struct spi_device *spi;
4744 switch (of_reconfig_get_state_change(action, arg)) {
4745 case OF_RECONFIG_CHANGE_ADD:
4746 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4748 return NOTIFY_OK; /* Not for us */
4750 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4751 put_device(&ctlr->dev);
4756 * Clear the flag before adding the device so that fw_devlink
4757 * doesn't skip adding consumers to this device.
4759 rd->dn->fwnode.flags &= ~FWNODE_FLAG_NOT_DEVICE;
4760 spi = of_register_spi_device(ctlr, rd->dn);
4761 put_device(&ctlr->dev);
4764 pr_err("%s: failed to create for '%pOF'\n",
4766 of_node_clear_flag(rd->dn, OF_POPULATED);
4767 return notifier_from_errno(PTR_ERR(spi));
4771 case OF_RECONFIG_CHANGE_REMOVE:
4772 /* Already depopulated? */
4773 if (!of_node_check_flag(rd->dn, OF_POPULATED))
4776 /* Find our device by node */
4777 spi = of_find_spi_device_by_node(rd->dn);
4779 return NOTIFY_OK; /* No? not meant for us */
4781 /* Unregister takes one ref away */
4782 spi_unregister_device(spi);
4784 /* And put the reference of the find */
4785 put_device(&spi->dev);
4792 static struct notifier_block spi_of_notifier = {
4793 .notifier_call = of_spi_notify,
4795 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4796 extern struct notifier_block spi_of_notifier;
4797 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4799 #if IS_ENABLED(CONFIG_ACPI)
4800 static int spi_acpi_controller_match(struct device *dev, const void *data)
4802 return ACPI_COMPANION(dev->parent) == data;
4805 struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4809 dev = class_find_device(&spi_master_class, NULL, adev,
4810 spi_acpi_controller_match);
4811 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4812 dev = class_find_device(&spi_slave_class, NULL, adev,
4813 spi_acpi_controller_match);
4817 return container_of(dev, struct spi_controller, dev);
4819 EXPORT_SYMBOL_GPL(acpi_spi_find_controller_by_adev);
4821 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4825 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4826 return to_spi_device(dev);
4829 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4832 struct acpi_device *adev = arg;
4833 struct spi_controller *ctlr;
4834 struct spi_device *spi;
4837 case ACPI_RECONFIG_DEVICE_ADD:
4838 ctlr = acpi_spi_find_controller_by_adev(acpi_dev_parent(adev));
4842 acpi_register_spi_device(ctlr, adev);
4843 put_device(&ctlr->dev);
4845 case ACPI_RECONFIG_DEVICE_REMOVE:
4846 if (!acpi_device_enumerated(adev))
4849 spi = acpi_spi_find_device_by_adev(adev);
4853 spi_unregister_device(spi);
4854 put_device(&spi->dev);
4861 static struct notifier_block spi_acpi_notifier = {
4862 .notifier_call = acpi_spi_notify,
4865 extern struct notifier_block spi_acpi_notifier;
4868 static int __init spi_init(void)
4872 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4878 status = bus_register(&spi_bus_type);
4882 status = class_register(&spi_master_class);
4886 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4887 status = class_register(&spi_slave_class);
4892 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4893 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4894 if (IS_ENABLED(CONFIG_ACPI))
4895 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4900 class_unregister(&spi_master_class);
4902 bus_unregister(&spi_bus_type);
4911 * A board_info is normally registered in arch_initcall(),
4912 * but even essential drivers wait till later.
4914 * REVISIT only boardinfo really needs static linking. The rest (device and
4915 * driver registration) _could_ be dynamically linked (modular) ... Costs
4916 * include needing to have boardinfo data structures be much more public.
4918 postcore_initcall(spi_init);