perf tools: Don't clone maps from parent when synthesizing forks
[linux/fpc-iii.git] / drivers / spi / spi.c
blob6ca59406b0b7a5bbe965833cb7e5fa8d86b388dd
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * SPI init/core code
5 * Copyright (C) 2005 David Brownell
6 * Copyright (C) 2008 Secret Lab Technologies Ltd.
7 */
9 #include <linux/kernel.h>
10 #include <linux/device.h>
11 #include <linux/init.h>
12 #include <linux/cache.h>
13 #include <linux/dma-mapping.h>
14 #include <linux/dmaengine.h>
15 #include <linux/mutex.h>
16 #include <linux/of_device.h>
17 #include <linux/of_irq.h>
18 #include <linux/clk/clk-conf.h>
19 #include <linux/slab.h>
20 #include <linux/mod_devicetable.h>
21 #include <linux/spi/spi.h>
22 #include <linux/spi/spi-mem.h>
23 #include <linux/of_gpio.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/pm_domain.h>
26 #include <linux/property.h>
27 #include <linux/export.h>
28 #include <linux/sched/rt.h>
29 #include <uapi/linux/sched/types.h>
30 #include <linux/delay.h>
31 #include <linux/kthread.h>
32 #include <linux/ioport.h>
33 #include <linux/acpi.h>
34 #include <linux/highmem.h>
35 #include <linux/idr.h>
36 #include <linux/platform_data/x86/apple.h>
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/spi.h>
41 #include "internals.h"
43 static DEFINE_IDR(spi_master_idr);
45 static void spidev_release(struct device *dev)
47 struct spi_device *spi = to_spi_device(dev);
49 /* spi controllers may cleanup for released devices */
50 if (spi->controller->cleanup)
51 spi->controller->cleanup(spi);
53 spi_controller_put(spi->controller);
54 kfree(spi->driver_override);
55 kfree(spi);
58 static ssize_t
59 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
61 const struct spi_device *spi = to_spi_device(dev);
62 int len;
64 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
65 if (len != -ENODEV)
66 return len;
68 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
70 static DEVICE_ATTR_RO(modalias);
72 static ssize_t driver_override_store(struct device *dev,
73 struct device_attribute *a,
74 const char *buf, size_t count)
76 struct spi_device *spi = to_spi_device(dev);
77 const char *end = memchr(buf, '\n', count);
78 const size_t len = end ? end - buf : count;
79 const char *driver_override, *old;
81 /* We need to keep extra room for a newline when displaying value */
82 if (len >= (PAGE_SIZE - 1))
83 return -EINVAL;
85 driver_override = kstrndup(buf, len, GFP_KERNEL);
86 if (!driver_override)
87 return -ENOMEM;
89 device_lock(dev);
90 old = spi->driver_override;
91 if (len) {
92 spi->driver_override = driver_override;
93 } else {
94 /* Emptry string, disable driver override */
95 spi->driver_override = NULL;
96 kfree(driver_override);
98 device_unlock(dev);
99 kfree(old);
101 return count;
104 static ssize_t driver_override_show(struct device *dev,
105 struct device_attribute *a, char *buf)
107 const struct spi_device *spi = to_spi_device(dev);
108 ssize_t len;
110 device_lock(dev);
111 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
112 device_unlock(dev);
113 return len;
115 static DEVICE_ATTR_RW(driver_override);
117 #define SPI_STATISTICS_ATTRS(field, file) \
118 static ssize_t spi_controller_##field##_show(struct device *dev, \
119 struct device_attribute *attr, \
120 char *buf) \
122 struct spi_controller *ctlr = container_of(dev, \
123 struct spi_controller, dev); \
124 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
126 static struct device_attribute dev_attr_spi_controller_##field = { \
127 .attr = { .name = file, .mode = 0444 }, \
128 .show = spi_controller_##field##_show, \
129 }; \
130 static ssize_t spi_device_##field##_show(struct device *dev, \
131 struct device_attribute *attr, \
132 char *buf) \
134 struct spi_device *spi = to_spi_device(dev); \
135 return spi_statistics_##field##_show(&spi->statistics, buf); \
137 static struct device_attribute dev_attr_spi_device_##field = { \
138 .attr = { .name = file, .mode = 0444 }, \
139 .show = spi_device_##field##_show, \
142 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
143 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
144 char *buf) \
146 unsigned long flags; \
147 ssize_t len; \
148 spin_lock_irqsave(&stat->lock, flags); \
149 len = sprintf(buf, format_string, stat->field); \
150 spin_unlock_irqrestore(&stat->lock, flags); \
151 return len; \
153 SPI_STATISTICS_ATTRS(name, file)
155 #define SPI_STATISTICS_SHOW(field, format_string) \
156 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
157 field, format_string)
159 SPI_STATISTICS_SHOW(messages, "%lu");
160 SPI_STATISTICS_SHOW(transfers, "%lu");
161 SPI_STATISTICS_SHOW(errors, "%lu");
162 SPI_STATISTICS_SHOW(timedout, "%lu");
164 SPI_STATISTICS_SHOW(spi_sync, "%lu");
165 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
166 SPI_STATISTICS_SHOW(spi_async, "%lu");
168 SPI_STATISTICS_SHOW(bytes, "%llu");
169 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
170 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
172 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
173 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
174 "transfer_bytes_histo_" number, \
175 transfer_bytes_histo[index], "%lu")
176 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
190 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
191 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
192 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
194 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
196 static struct attribute *spi_dev_attrs[] = {
197 &dev_attr_modalias.attr,
198 &dev_attr_driver_override.attr,
199 NULL,
202 static const struct attribute_group spi_dev_group = {
203 .attrs = spi_dev_attrs,
206 static struct attribute *spi_device_statistics_attrs[] = {
207 &dev_attr_spi_device_messages.attr,
208 &dev_attr_spi_device_transfers.attr,
209 &dev_attr_spi_device_errors.attr,
210 &dev_attr_spi_device_timedout.attr,
211 &dev_attr_spi_device_spi_sync.attr,
212 &dev_attr_spi_device_spi_sync_immediate.attr,
213 &dev_attr_spi_device_spi_async.attr,
214 &dev_attr_spi_device_bytes.attr,
215 &dev_attr_spi_device_bytes_rx.attr,
216 &dev_attr_spi_device_bytes_tx.attr,
217 &dev_attr_spi_device_transfer_bytes_histo0.attr,
218 &dev_attr_spi_device_transfer_bytes_histo1.attr,
219 &dev_attr_spi_device_transfer_bytes_histo2.attr,
220 &dev_attr_spi_device_transfer_bytes_histo3.attr,
221 &dev_attr_spi_device_transfer_bytes_histo4.attr,
222 &dev_attr_spi_device_transfer_bytes_histo5.attr,
223 &dev_attr_spi_device_transfer_bytes_histo6.attr,
224 &dev_attr_spi_device_transfer_bytes_histo7.attr,
225 &dev_attr_spi_device_transfer_bytes_histo8.attr,
226 &dev_attr_spi_device_transfer_bytes_histo9.attr,
227 &dev_attr_spi_device_transfer_bytes_histo10.attr,
228 &dev_attr_spi_device_transfer_bytes_histo11.attr,
229 &dev_attr_spi_device_transfer_bytes_histo12.attr,
230 &dev_attr_spi_device_transfer_bytes_histo13.attr,
231 &dev_attr_spi_device_transfer_bytes_histo14.attr,
232 &dev_attr_spi_device_transfer_bytes_histo15.attr,
233 &dev_attr_spi_device_transfer_bytes_histo16.attr,
234 &dev_attr_spi_device_transfers_split_maxsize.attr,
235 NULL,
238 static const struct attribute_group spi_device_statistics_group = {
239 .name = "statistics",
240 .attrs = spi_device_statistics_attrs,
243 static const struct attribute_group *spi_dev_groups[] = {
244 &spi_dev_group,
245 &spi_device_statistics_group,
246 NULL,
249 static struct attribute *spi_controller_statistics_attrs[] = {
250 &dev_attr_spi_controller_messages.attr,
251 &dev_attr_spi_controller_transfers.attr,
252 &dev_attr_spi_controller_errors.attr,
253 &dev_attr_spi_controller_timedout.attr,
254 &dev_attr_spi_controller_spi_sync.attr,
255 &dev_attr_spi_controller_spi_sync_immediate.attr,
256 &dev_attr_spi_controller_spi_async.attr,
257 &dev_attr_spi_controller_bytes.attr,
258 &dev_attr_spi_controller_bytes_rx.attr,
259 &dev_attr_spi_controller_bytes_tx.attr,
260 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
274 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
275 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
276 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
277 &dev_attr_spi_controller_transfers_split_maxsize.attr,
278 NULL,
281 static const struct attribute_group spi_controller_statistics_group = {
282 .name = "statistics",
283 .attrs = spi_controller_statistics_attrs,
286 static const struct attribute_group *spi_master_groups[] = {
287 &spi_controller_statistics_group,
288 NULL,
291 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
292 struct spi_transfer *xfer,
293 struct spi_controller *ctlr)
295 unsigned long flags;
296 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
298 if (l2len < 0)
299 l2len = 0;
301 spin_lock_irqsave(&stats->lock, flags);
303 stats->transfers++;
304 stats->transfer_bytes_histo[l2len]++;
306 stats->bytes += xfer->len;
307 if ((xfer->tx_buf) &&
308 (xfer->tx_buf != ctlr->dummy_tx))
309 stats->bytes_tx += xfer->len;
310 if ((xfer->rx_buf) &&
311 (xfer->rx_buf != ctlr->dummy_rx))
312 stats->bytes_rx += xfer->len;
314 spin_unlock_irqrestore(&stats->lock, flags);
316 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
318 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
319 * and the sysfs version makes coldplug work too.
322 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
323 const struct spi_device *sdev)
325 while (id->name[0]) {
326 if (!strcmp(sdev->modalias, id->name))
327 return id;
328 id++;
330 return NULL;
333 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
335 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
337 return spi_match_id(sdrv->id_table, sdev);
339 EXPORT_SYMBOL_GPL(spi_get_device_id);
341 static int spi_match_device(struct device *dev, struct device_driver *drv)
343 const struct spi_device *spi = to_spi_device(dev);
344 const struct spi_driver *sdrv = to_spi_driver(drv);
346 /* Check override first, and if set, only use the named driver */
347 if (spi->driver_override)
348 return strcmp(spi->driver_override, drv->name) == 0;
350 /* Attempt an OF style match */
351 if (of_driver_match_device(dev, drv))
352 return 1;
354 /* Then try ACPI */
355 if (acpi_driver_match_device(dev, drv))
356 return 1;
358 if (sdrv->id_table)
359 return !!spi_match_id(sdrv->id_table, spi);
361 return strcmp(spi->modalias, drv->name) == 0;
364 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
366 const struct spi_device *spi = to_spi_device(dev);
367 int rc;
369 rc = acpi_device_uevent_modalias(dev, env);
370 if (rc != -ENODEV)
371 return rc;
373 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
376 struct bus_type spi_bus_type = {
377 .name = "spi",
378 .dev_groups = spi_dev_groups,
379 .match = spi_match_device,
380 .uevent = spi_uevent,
382 EXPORT_SYMBOL_GPL(spi_bus_type);
385 static int spi_drv_probe(struct device *dev)
387 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
388 struct spi_device *spi = to_spi_device(dev);
389 int ret;
391 ret = of_clk_set_defaults(dev->of_node, false);
392 if (ret)
393 return ret;
395 if (dev->of_node) {
396 spi->irq = of_irq_get(dev->of_node, 0);
397 if (spi->irq == -EPROBE_DEFER)
398 return -EPROBE_DEFER;
399 if (spi->irq < 0)
400 spi->irq = 0;
403 ret = dev_pm_domain_attach(dev, true);
404 if (ret)
405 return ret;
407 ret = sdrv->probe(spi);
408 if (ret)
409 dev_pm_domain_detach(dev, true);
411 return ret;
414 static int spi_drv_remove(struct device *dev)
416 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
417 int ret;
419 ret = sdrv->remove(to_spi_device(dev));
420 dev_pm_domain_detach(dev, true);
422 return ret;
425 static void spi_drv_shutdown(struct device *dev)
427 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
429 sdrv->shutdown(to_spi_device(dev));
433 * __spi_register_driver - register a SPI driver
434 * @owner: owner module of the driver to register
435 * @sdrv: the driver to register
436 * Context: can sleep
438 * Return: zero on success, else a negative error code.
440 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
442 sdrv->driver.owner = owner;
443 sdrv->driver.bus = &spi_bus_type;
444 if (sdrv->probe)
445 sdrv->driver.probe = spi_drv_probe;
446 if (sdrv->remove)
447 sdrv->driver.remove = spi_drv_remove;
448 if (sdrv->shutdown)
449 sdrv->driver.shutdown = spi_drv_shutdown;
450 return driver_register(&sdrv->driver);
452 EXPORT_SYMBOL_GPL(__spi_register_driver);
454 /*-------------------------------------------------------------------------*/
456 /* SPI devices should normally not be created by SPI device drivers; that
457 * would make them board-specific. Similarly with SPI controller drivers.
458 * Device registration normally goes into like arch/.../mach.../board-YYY.c
459 * with other readonly (flashable) information about mainboard devices.
462 struct boardinfo {
463 struct list_head list;
464 struct spi_board_info board_info;
467 static LIST_HEAD(board_list);
468 static LIST_HEAD(spi_controller_list);
471 * Used to protect add/del opertion for board_info list and
472 * spi_controller list, and their matching process
473 * also used to protect object of type struct idr
475 static DEFINE_MUTEX(board_lock);
478 * spi_alloc_device - Allocate a new SPI device
479 * @ctlr: Controller to which device is connected
480 * Context: can sleep
482 * Allows a driver to allocate and initialize a spi_device without
483 * registering it immediately. This allows a driver to directly
484 * fill the spi_device with device parameters before calling
485 * spi_add_device() on it.
487 * Caller is responsible to call spi_add_device() on the returned
488 * spi_device structure to add it to the SPI controller. If the caller
489 * needs to discard the spi_device without adding it, then it should
490 * call spi_dev_put() on it.
492 * Return: a pointer to the new device, or NULL.
494 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
496 struct spi_device *spi;
498 if (!spi_controller_get(ctlr))
499 return NULL;
501 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
502 if (!spi) {
503 spi_controller_put(ctlr);
504 return NULL;
507 spi->master = spi->controller = ctlr;
508 spi->dev.parent = &ctlr->dev;
509 spi->dev.bus = &spi_bus_type;
510 spi->dev.release = spidev_release;
511 spi->cs_gpio = -ENOENT;
513 spin_lock_init(&spi->statistics.lock);
515 device_initialize(&spi->dev);
516 return spi;
518 EXPORT_SYMBOL_GPL(spi_alloc_device);
520 static void spi_dev_set_name(struct spi_device *spi)
522 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
524 if (adev) {
525 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
526 return;
529 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
530 spi->chip_select);
533 static int spi_dev_check(struct device *dev, void *data)
535 struct spi_device *spi = to_spi_device(dev);
536 struct spi_device *new_spi = data;
538 if (spi->controller == new_spi->controller &&
539 spi->chip_select == new_spi->chip_select)
540 return -EBUSY;
541 return 0;
545 * spi_add_device - Add spi_device allocated with spi_alloc_device
546 * @spi: spi_device to register
548 * Companion function to spi_alloc_device. Devices allocated with
549 * spi_alloc_device can be added onto the spi bus with this function.
551 * Return: 0 on success; negative errno on failure
553 int spi_add_device(struct spi_device *spi)
555 static DEFINE_MUTEX(spi_add_lock);
556 struct spi_controller *ctlr = spi->controller;
557 struct device *dev = ctlr->dev.parent;
558 int status;
560 /* Chipselects are numbered 0..max; validate. */
561 if (spi->chip_select >= ctlr->num_chipselect) {
562 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
563 ctlr->num_chipselect);
564 return -EINVAL;
567 /* Set the bus ID string */
568 spi_dev_set_name(spi);
570 /* We need to make sure there's no other device with this
571 * chipselect **BEFORE** we call setup(), else we'll trash
572 * its configuration. Lock against concurrent add() calls.
574 mutex_lock(&spi_add_lock);
576 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
577 if (status) {
578 dev_err(dev, "chipselect %d already in use\n",
579 spi->chip_select);
580 goto done;
583 if (ctlr->cs_gpios)
584 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
586 /* Drivers may modify this initial i/o setup, but will
587 * normally rely on the device being setup. Devices
588 * using SPI_CS_HIGH can't coexist well otherwise...
590 status = spi_setup(spi);
591 if (status < 0) {
592 dev_err(dev, "can't setup %s, status %d\n",
593 dev_name(&spi->dev), status);
594 goto done;
597 /* Device may be bound to an active driver when this returns */
598 status = device_add(&spi->dev);
599 if (status < 0)
600 dev_err(dev, "can't add %s, status %d\n",
601 dev_name(&spi->dev), status);
602 else
603 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
605 done:
606 mutex_unlock(&spi_add_lock);
607 return status;
609 EXPORT_SYMBOL_GPL(spi_add_device);
612 * spi_new_device - instantiate one new SPI device
613 * @ctlr: Controller to which device is connected
614 * @chip: Describes the SPI device
615 * Context: can sleep
617 * On typical mainboards, this is purely internal; and it's not needed
618 * after board init creates the hard-wired devices. Some development
619 * platforms may not be able to use spi_register_board_info though, and
620 * this is exported so that for example a USB or parport based adapter
621 * driver could add devices (which it would learn about out-of-band).
623 * Return: the new device, or NULL.
625 struct spi_device *spi_new_device(struct spi_controller *ctlr,
626 struct spi_board_info *chip)
628 struct spi_device *proxy;
629 int status;
631 /* NOTE: caller did any chip->bus_num checks necessary.
633 * Also, unless we change the return value convention to use
634 * error-or-pointer (not NULL-or-pointer), troubleshootability
635 * suggests syslogged diagnostics are best here (ugh).
638 proxy = spi_alloc_device(ctlr);
639 if (!proxy)
640 return NULL;
642 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
644 proxy->chip_select = chip->chip_select;
645 proxy->max_speed_hz = chip->max_speed_hz;
646 proxy->mode = chip->mode;
647 proxy->irq = chip->irq;
648 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
649 proxy->dev.platform_data = (void *) chip->platform_data;
650 proxy->controller_data = chip->controller_data;
651 proxy->controller_state = NULL;
653 if (chip->properties) {
654 status = device_add_properties(&proxy->dev, chip->properties);
655 if (status) {
656 dev_err(&ctlr->dev,
657 "failed to add properties to '%s': %d\n",
658 chip->modalias, status);
659 goto err_dev_put;
663 status = spi_add_device(proxy);
664 if (status < 0)
665 goto err_remove_props;
667 return proxy;
669 err_remove_props:
670 if (chip->properties)
671 device_remove_properties(&proxy->dev);
672 err_dev_put:
673 spi_dev_put(proxy);
674 return NULL;
676 EXPORT_SYMBOL_GPL(spi_new_device);
679 * spi_unregister_device - unregister a single SPI device
680 * @spi: spi_device to unregister
682 * Start making the passed SPI device vanish. Normally this would be handled
683 * by spi_unregister_controller().
685 void spi_unregister_device(struct spi_device *spi)
687 if (!spi)
688 return;
690 if (spi->dev.of_node) {
691 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
692 of_node_put(spi->dev.of_node);
694 if (ACPI_COMPANION(&spi->dev))
695 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
696 device_unregister(&spi->dev);
698 EXPORT_SYMBOL_GPL(spi_unregister_device);
700 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
701 struct spi_board_info *bi)
703 struct spi_device *dev;
705 if (ctlr->bus_num != bi->bus_num)
706 return;
708 dev = spi_new_device(ctlr, bi);
709 if (!dev)
710 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
711 bi->modalias);
715 * spi_register_board_info - register SPI devices for a given board
716 * @info: array of chip descriptors
717 * @n: how many descriptors are provided
718 * Context: can sleep
720 * Board-specific early init code calls this (probably during arch_initcall)
721 * with segments of the SPI device table. Any device nodes are created later,
722 * after the relevant parent SPI controller (bus_num) is defined. We keep
723 * this table of devices forever, so that reloading a controller driver will
724 * not make Linux forget about these hard-wired devices.
726 * Other code can also call this, e.g. a particular add-on board might provide
727 * SPI devices through its expansion connector, so code initializing that board
728 * would naturally declare its SPI devices.
730 * The board info passed can safely be __initdata ... but be careful of
731 * any embedded pointers (platform_data, etc), they're copied as-is.
732 * Device properties are deep-copied though.
734 * Return: zero on success, else a negative error code.
736 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
738 struct boardinfo *bi;
739 int i;
741 if (!n)
742 return 0;
744 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
745 if (!bi)
746 return -ENOMEM;
748 for (i = 0; i < n; i++, bi++, info++) {
749 struct spi_controller *ctlr;
751 memcpy(&bi->board_info, info, sizeof(*info));
752 if (info->properties) {
753 bi->board_info.properties =
754 property_entries_dup(info->properties);
755 if (IS_ERR(bi->board_info.properties))
756 return PTR_ERR(bi->board_info.properties);
759 mutex_lock(&board_lock);
760 list_add_tail(&bi->list, &board_list);
761 list_for_each_entry(ctlr, &spi_controller_list, list)
762 spi_match_controller_to_boardinfo(ctlr,
763 &bi->board_info);
764 mutex_unlock(&board_lock);
767 return 0;
770 /*-------------------------------------------------------------------------*/
772 static void spi_set_cs(struct spi_device *spi, bool enable)
774 if (spi->mode & SPI_CS_HIGH)
775 enable = !enable;
777 if (gpio_is_valid(spi->cs_gpio)) {
778 /* Honour the SPI_NO_CS flag */
779 if (!(spi->mode & SPI_NO_CS))
780 gpio_set_value(spi->cs_gpio, !enable);
781 /* Some SPI masters need both GPIO CS & slave_select */
782 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
783 spi->controller->set_cs)
784 spi->controller->set_cs(spi, !enable);
785 } else if (spi->controller->set_cs) {
786 spi->controller->set_cs(spi, !enable);
790 #ifdef CONFIG_HAS_DMA
791 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
792 struct sg_table *sgt, void *buf, size_t len,
793 enum dma_data_direction dir)
795 const bool vmalloced_buf = is_vmalloc_addr(buf);
796 unsigned int max_seg_size = dma_get_max_seg_size(dev);
797 #ifdef CONFIG_HIGHMEM
798 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
799 (unsigned long)buf < (PKMAP_BASE +
800 (LAST_PKMAP * PAGE_SIZE)));
801 #else
802 const bool kmap_buf = false;
803 #endif
804 int desc_len;
805 int sgs;
806 struct page *vm_page;
807 struct scatterlist *sg;
808 void *sg_buf;
809 size_t min;
810 int i, ret;
812 if (vmalloced_buf || kmap_buf) {
813 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
814 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
815 } else if (virt_addr_valid(buf)) {
816 desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
817 sgs = DIV_ROUND_UP(len, desc_len);
818 } else {
819 return -EINVAL;
822 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
823 if (ret != 0)
824 return ret;
826 sg = &sgt->sgl[0];
827 for (i = 0; i < sgs; i++) {
829 if (vmalloced_buf || kmap_buf) {
831 * Next scatterlist entry size is the minimum between
832 * the desc_len and the remaining buffer length that
833 * fits in a page.
835 min = min_t(size_t, desc_len,
836 min_t(size_t, len,
837 PAGE_SIZE - offset_in_page(buf)));
838 if (vmalloced_buf)
839 vm_page = vmalloc_to_page(buf);
840 else
841 vm_page = kmap_to_page(buf);
842 if (!vm_page) {
843 sg_free_table(sgt);
844 return -ENOMEM;
846 sg_set_page(sg, vm_page,
847 min, offset_in_page(buf));
848 } else {
849 min = min_t(size_t, len, desc_len);
850 sg_buf = buf;
851 sg_set_buf(sg, sg_buf, min);
854 buf += min;
855 len -= min;
856 sg = sg_next(sg);
859 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
860 if (!ret)
861 ret = -ENOMEM;
862 if (ret < 0) {
863 sg_free_table(sgt);
864 return ret;
867 sgt->nents = ret;
869 return 0;
872 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
873 struct sg_table *sgt, enum dma_data_direction dir)
875 if (sgt->orig_nents) {
876 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
877 sg_free_table(sgt);
881 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
883 struct device *tx_dev, *rx_dev;
884 struct spi_transfer *xfer;
885 int ret;
887 if (!ctlr->can_dma)
888 return 0;
890 if (ctlr->dma_tx)
891 tx_dev = ctlr->dma_tx->device->dev;
892 else
893 tx_dev = ctlr->dev.parent;
895 if (ctlr->dma_rx)
896 rx_dev = ctlr->dma_rx->device->dev;
897 else
898 rx_dev = ctlr->dev.parent;
900 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
901 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
902 continue;
904 if (xfer->tx_buf != NULL) {
905 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
906 (void *)xfer->tx_buf, xfer->len,
907 DMA_TO_DEVICE);
908 if (ret != 0)
909 return ret;
912 if (xfer->rx_buf != NULL) {
913 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
914 xfer->rx_buf, xfer->len,
915 DMA_FROM_DEVICE);
916 if (ret != 0) {
917 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
918 DMA_TO_DEVICE);
919 return ret;
924 ctlr->cur_msg_mapped = true;
926 return 0;
929 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
931 struct spi_transfer *xfer;
932 struct device *tx_dev, *rx_dev;
934 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
935 return 0;
937 if (ctlr->dma_tx)
938 tx_dev = ctlr->dma_tx->device->dev;
939 else
940 tx_dev = ctlr->dev.parent;
942 if (ctlr->dma_rx)
943 rx_dev = ctlr->dma_rx->device->dev;
944 else
945 rx_dev = ctlr->dev.parent;
947 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
948 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
949 continue;
951 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
952 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
955 return 0;
957 #else /* !CONFIG_HAS_DMA */
958 static inline int __spi_map_msg(struct spi_controller *ctlr,
959 struct spi_message *msg)
961 return 0;
964 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
965 struct spi_message *msg)
967 return 0;
969 #endif /* !CONFIG_HAS_DMA */
971 static inline int spi_unmap_msg(struct spi_controller *ctlr,
972 struct spi_message *msg)
974 struct spi_transfer *xfer;
976 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
978 * Restore the original value of tx_buf or rx_buf if they are
979 * NULL.
981 if (xfer->tx_buf == ctlr->dummy_tx)
982 xfer->tx_buf = NULL;
983 if (xfer->rx_buf == ctlr->dummy_rx)
984 xfer->rx_buf = NULL;
987 return __spi_unmap_msg(ctlr, msg);
990 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
992 struct spi_transfer *xfer;
993 void *tmp;
994 unsigned int max_tx, max_rx;
996 if (ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX)) {
997 max_tx = 0;
998 max_rx = 0;
1000 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1001 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1002 !xfer->tx_buf)
1003 max_tx = max(xfer->len, max_tx);
1004 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1005 !xfer->rx_buf)
1006 max_rx = max(xfer->len, max_rx);
1009 if (max_tx) {
1010 tmp = krealloc(ctlr->dummy_tx, max_tx,
1011 GFP_KERNEL | GFP_DMA);
1012 if (!tmp)
1013 return -ENOMEM;
1014 ctlr->dummy_tx = tmp;
1015 memset(tmp, 0, max_tx);
1018 if (max_rx) {
1019 tmp = krealloc(ctlr->dummy_rx, max_rx,
1020 GFP_KERNEL | GFP_DMA);
1021 if (!tmp)
1022 return -ENOMEM;
1023 ctlr->dummy_rx = tmp;
1026 if (max_tx || max_rx) {
1027 list_for_each_entry(xfer, &msg->transfers,
1028 transfer_list) {
1029 if (!xfer->tx_buf)
1030 xfer->tx_buf = ctlr->dummy_tx;
1031 if (!xfer->rx_buf)
1032 xfer->rx_buf = ctlr->dummy_rx;
1037 return __spi_map_msg(ctlr, msg);
1041 * spi_transfer_one_message - Default implementation of transfer_one_message()
1043 * This is a standard implementation of transfer_one_message() for
1044 * drivers which implement a transfer_one() operation. It provides
1045 * standard handling of delays and chip select management.
1047 static int spi_transfer_one_message(struct spi_controller *ctlr,
1048 struct spi_message *msg)
1050 struct spi_transfer *xfer;
1051 bool keep_cs = false;
1052 int ret = 0;
1053 unsigned long long ms = 1;
1054 struct spi_statistics *statm = &ctlr->statistics;
1055 struct spi_statistics *stats = &msg->spi->statistics;
1057 spi_set_cs(msg->spi, true);
1059 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1060 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1062 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1063 trace_spi_transfer_start(msg, xfer);
1065 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1066 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1068 if (xfer->tx_buf || xfer->rx_buf) {
1069 reinit_completion(&ctlr->xfer_completion);
1071 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1072 if (ret < 0) {
1073 SPI_STATISTICS_INCREMENT_FIELD(statm,
1074 errors);
1075 SPI_STATISTICS_INCREMENT_FIELD(stats,
1076 errors);
1077 dev_err(&msg->spi->dev,
1078 "SPI transfer failed: %d\n", ret);
1079 goto out;
1082 if (ret > 0) {
1083 ret = 0;
1084 ms = 8LL * 1000LL * xfer->len;
1085 do_div(ms, xfer->speed_hz);
1086 ms += ms + 200; /* some tolerance */
1088 if (ms > UINT_MAX)
1089 ms = UINT_MAX;
1091 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1092 msecs_to_jiffies(ms));
1095 if (ms == 0) {
1096 SPI_STATISTICS_INCREMENT_FIELD(statm,
1097 timedout);
1098 SPI_STATISTICS_INCREMENT_FIELD(stats,
1099 timedout);
1100 dev_err(&msg->spi->dev,
1101 "SPI transfer timed out\n");
1102 msg->status = -ETIMEDOUT;
1104 } else {
1105 if (xfer->len)
1106 dev_err(&msg->spi->dev,
1107 "Bufferless transfer has length %u\n",
1108 xfer->len);
1111 trace_spi_transfer_stop(msg, xfer);
1113 if (msg->status != -EINPROGRESS)
1114 goto out;
1116 if (xfer->delay_usecs) {
1117 u16 us = xfer->delay_usecs;
1119 if (us <= 10)
1120 udelay(us);
1121 else
1122 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1125 if (xfer->cs_change) {
1126 if (list_is_last(&xfer->transfer_list,
1127 &msg->transfers)) {
1128 keep_cs = true;
1129 } else {
1130 spi_set_cs(msg->spi, false);
1131 udelay(10);
1132 spi_set_cs(msg->spi, true);
1136 msg->actual_length += xfer->len;
1139 out:
1140 if (ret != 0 || !keep_cs)
1141 spi_set_cs(msg->spi, false);
1143 if (msg->status == -EINPROGRESS)
1144 msg->status = ret;
1146 if (msg->status && ctlr->handle_err)
1147 ctlr->handle_err(ctlr, msg);
1149 spi_res_release(ctlr, msg);
1151 spi_finalize_current_message(ctlr);
1153 return ret;
1157 * spi_finalize_current_transfer - report completion of a transfer
1158 * @ctlr: the controller reporting completion
1160 * Called by SPI drivers using the core transfer_one_message()
1161 * implementation to notify it that the current interrupt driven
1162 * transfer has finished and the next one may be scheduled.
1164 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1166 complete(&ctlr->xfer_completion);
1168 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1171 * __spi_pump_messages - function which processes spi message queue
1172 * @ctlr: controller to process queue for
1173 * @in_kthread: true if we are in the context of the message pump thread
1175 * This function checks if there is any spi message in the queue that
1176 * needs processing and if so call out to the driver to initialize hardware
1177 * and transfer each message.
1179 * Note that it is called both from the kthread itself and also from
1180 * inside spi_sync(); the queue extraction handling at the top of the
1181 * function should deal with this safely.
1183 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1185 unsigned long flags;
1186 bool was_busy = false;
1187 int ret;
1189 /* Lock queue */
1190 spin_lock_irqsave(&ctlr->queue_lock, flags);
1192 /* Make sure we are not already running a message */
1193 if (ctlr->cur_msg) {
1194 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1195 return;
1198 /* If another context is idling the device then defer */
1199 if (ctlr->idling) {
1200 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1201 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1202 return;
1205 /* Check if the queue is idle */
1206 if (list_empty(&ctlr->queue) || !ctlr->running) {
1207 if (!ctlr->busy) {
1208 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1209 return;
1212 /* Only do teardown in the thread */
1213 if (!in_kthread) {
1214 kthread_queue_work(&ctlr->kworker,
1215 &ctlr->pump_messages);
1216 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1217 return;
1220 ctlr->busy = false;
1221 ctlr->idling = true;
1222 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1224 kfree(ctlr->dummy_rx);
1225 ctlr->dummy_rx = NULL;
1226 kfree(ctlr->dummy_tx);
1227 ctlr->dummy_tx = NULL;
1228 if (ctlr->unprepare_transfer_hardware &&
1229 ctlr->unprepare_transfer_hardware(ctlr))
1230 dev_err(&ctlr->dev,
1231 "failed to unprepare transfer hardware\n");
1232 if (ctlr->auto_runtime_pm) {
1233 pm_runtime_mark_last_busy(ctlr->dev.parent);
1234 pm_runtime_put_autosuspend(ctlr->dev.parent);
1236 trace_spi_controller_idle(ctlr);
1238 spin_lock_irqsave(&ctlr->queue_lock, flags);
1239 ctlr->idling = false;
1240 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1241 return;
1244 /* Extract head of queue */
1245 ctlr->cur_msg =
1246 list_first_entry(&ctlr->queue, struct spi_message, queue);
1248 list_del_init(&ctlr->cur_msg->queue);
1249 if (ctlr->busy)
1250 was_busy = true;
1251 else
1252 ctlr->busy = true;
1253 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1255 mutex_lock(&ctlr->io_mutex);
1257 if (!was_busy && ctlr->auto_runtime_pm) {
1258 ret = pm_runtime_get_sync(ctlr->dev.parent);
1259 if (ret < 0) {
1260 pm_runtime_put_noidle(ctlr->dev.parent);
1261 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1262 ret);
1263 mutex_unlock(&ctlr->io_mutex);
1264 return;
1268 if (!was_busy)
1269 trace_spi_controller_busy(ctlr);
1271 if (!was_busy && ctlr->prepare_transfer_hardware) {
1272 ret = ctlr->prepare_transfer_hardware(ctlr);
1273 if (ret) {
1274 dev_err(&ctlr->dev,
1275 "failed to prepare transfer hardware\n");
1277 if (ctlr->auto_runtime_pm)
1278 pm_runtime_put(ctlr->dev.parent);
1279 mutex_unlock(&ctlr->io_mutex);
1280 return;
1284 trace_spi_message_start(ctlr->cur_msg);
1286 if (ctlr->prepare_message) {
1287 ret = ctlr->prepare_message(ctlr, ctlr->cur_msg);
1288 if (ret) {
1289 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1290 ret);
1291 ctlr->cur_msg->status = ret;
1292 spi_finalize_current_message(ctlr);
1293 goto out;
1295 ctlr->cur_msg_prepared = true;
1298 ret = spi_map_msg(ctlr, ctlr->cur_msg);
1299 if (ret) {
1300 ctlr->cur_msg->status = ret;
1301 spi_finalize_current_message(ctlr);
1302 goto out;
1305 ret = ctlr->transfer_one_message(ctlr, ctlr->cur_msg);
1306 if (ret) {
1307 dev_err(&ctlr->dev,
1308 "failed to transfer one message from queue\n");
1309 goto out;
1312 out:
1313 mutex_unlock(&ctlr->io_mutex);
1315 /* Prod the scheduler in case transfer_one() was busy waiting */
1316 if (!ret)
1317 cond_resched();
1321 * spi_pump_messages - kthread work function which processes spi message queue
1322 * @work: pointer to kthread work struct contained in the controller struct
1324 static void spi_pump_messages(struct kthread_work *work)
1326 struct spi_controller *ctlr =
1327 container_of(work, struct spi_controller, pump_messages);
1329 __spi_pump_messages(ctlr, true);
1332 static int spi_init_queue(struct spi_controller *ctlr)
1334 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1336 ctlr->running = false;
1337 ctlr->busy = false;
1339 kthread_init_worker(&ctlr->kworker);
1340 ctlr->kworker_task = kthread_run(kthread_worker_fn, &ctlr->kworker,
1341 "%s", dev_name(&ctlr->dev));
1342 if (IS_ERR(ctlr->kworker_task)) {
1343 dev_err(&ctlr->dev, "failed to create message pump task\n");
1344 return PTR_ERR(ctlr->kworker_task);
1346 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1349 * Controller config will indicate if this controller should run the
1350 * message pump with high (realtime) priority to reduce the transfer
1351 * latency on the bus by minimising the delay between a transfer
1352 * request and the scheduling of the message pump thread. Without this
1353 * setting the message pump thread will remain at default priority.
1355 if (ctlr->rt) {
1356 dev_info(&ctlr->dev,
1357 "will run message pump with realtime priority\n");
1358 sched_setscheduler(ctlr->kworker_task, SCHED_FIFO, &param);
1361 return 0;
1365 * spi_get_next_queued_message() - called by driver to check for queued
1366 * messages
1367 * @ctlr: the controller to check for queued messages
1369 * If there are more messages in the queue, the next message is returned from
1370 * this call.
1372 * Return: the next message in the queue, else NULL if the queue is empty.
1374 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1376 struct spi_message *next;
1377 unsigned long flags;
1379 /* get a pointer to the next message, if any */
1380 spin_lock_irqsave(&ctlr->queue_lock, flags);
1381 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1382 queue);
1383 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1385 return next;
1387 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1390 * spi_finalize_current_message() - the current message is complete
1391 * @ctlr: the controller to return the message to
1393 * Called by the driver to notify the core that the message in the front of the
1394 * queue is complete and can be removed from the queue.
1396 void spi_finalize_current_message(struct spi_controller *ctlr)
1398 struct spi_message *mesg;
1399 unsigned long flags;
1400 int ret;
1402 spin_lock_irqsave(&ctlr->queue_lock, flags);
1403 mesg = ctlr->cur_msg;
1404 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1406 spi_unmap_msg(ctlr, mesg);
1408 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1409 ret = ctlr->unprepare_message(ctlr, mesg);
1410 if (ret) {
1411 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1412 ret);
1416 spin_lock_irqsave(&ctlr->queue_lock, flags);
1417 ctlr->cur_msg = NULL;
1418 ctlr->cur_msg_prepared = false;
1419 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1420 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1422 trace_spi_message_done(mesg);
1424 mesg->state = NULL;
1425 if (mesg->complete)
1426 mesg->complete(mesg->context);
1428 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1430 static int spi_start_queue(struct spi_controller *ctlr)
1432 unsigned long flags;
1434 spin_lock_irqsave(&ctlr->queue_lock, flags);
1436 if (ctlr->running || ctlr->busy) {
1437 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1438 return -EBUSY;
1441 ctlr->running = true;
1442 ctlr->cur_msg = NULL;
1443 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1445 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1447 return 0;
1450 static int spi_stop_queue(struct spi_controller *ctlr)
1452 unsigned long flags;
1453 unsigned limit = 500;
1454 int ret = 0;
1456 spin_lock_irqsave(&ctlr->queue_lock, flags);
1459 * This is a bit lame, but is optimized for the common execution path.
1460 * A wait_queue on the ctlr->busy could be used, but then the common
1461 * execution path (pump_messages) would be required to call wake_up or
1462 * friends on every SPI message. Do this instead.
1464 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1465 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1466 usleep_range(10000, 11000);
1467 spin_lock_irqsave(&ctlr->queue_lock, flags);
1470 if (!list_empty(&ctlr->queue) || ctlr->busy)
1471 ret = -EBUSY;
1472 else
1473 ctlr->running = false;
1475 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1477 if (ret) {
1478 dev_warn(&ctlr->dev, "could not stop message queue\n");
1479 return ret;
1481 return ret;
1484 static int spi_destroy_queue(struct spi_controller *ctlr)
1486 int ret;
1488 ret = spi_stop_queue(ctlr);
1491 * kthread_flush_worker will block until all work is done.
1492 * If the reason that stop_queue timed out is that the work will never
1493 * finish, then it does no good to call flush/stop thread, so
1494 * return anyway.
1496 if (ret) {
1497 dev_err(&ctlr->dev, "problem destroying queue\n");
1498 return ret;
1501 kthread_flush_worker(&ctlr->kworker);
1502 kthread_stop(ctlr->kworker_task);
1504 return 0;
1507 static int __spi_queued_transfer(struct spi_device *spi,
1508 struct spi_message *msg,
1509 bool need_pump)
1511 struct spi_controller *ctlr = spi->controller;
1512 unsigned long flags;
1514 spin_lock_irqsave(&ctlr->queue_lock, flags);
1516 if (!ctlr->running) {
1517 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1518 return -ESHUTDOWN;
1520 msg->actual_length = 0;
1521 msg->status = -EINPROGRESS;
1523 list_add_tail(&msg->queue, &ctlr->queue);
1524 if (!ctlr->busy && need_pump)
1525 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1527 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1528 return 0;
1532 * spi_queued_transfer - transfer function for queued transfers
1533 * @spi: spi device which is requesting transfer
1534 * @msg: spi message which is to handled is queued to driver queue
1536 * Return: zero on success, else a negative error code.
1538 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1540 return __spi_queued_transfer(spi, msg, true);
1543 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1545 int ret;
1547 ctlr->transfer = spi_queued_transfer;
1548 if (!ctlr->transfer_one_message)
1549 ctlr->transfer_one_message = spi_transfer_one_message;
1551 /* Initialize and start queue */
1552 ret = spi_init_queue(ctlr);
1553 if (ret) {
1554 dev_err(&ctlr->dev, "problem initializing queue\n");
1555 goto err_init_queue;
1557 ctlr->queued = true;
1558 ret = spi_start_queue(ctlr);
1559 if (ret) {
1560 dev_err(&ctlr->dev, "problem starting queue\n");
1561 goto err_start_queue;
1564 return 0;
1566 err_start_queue:
1567 spi_destroy_queue(ctlr);
1568 err_init_queue:
1569 return ret;
1573 * spi_flush_queue - Send all pending messages in the queue from the callers'
1574 * context
1575 * @ctlr: controller to process queue for
1577 * This should be used when one wants to ensure all pending messages have been
1578 * sent before doing something. Is used by the spi-mem code to make sure SPI
1579 * memory operations do not preempt regular SPI transfers that have been queued
1580 * before the spi-mem operation.
1582 void spi_flush_queue(struct spi_controller *ctlr)
1584 if (ctlr->transfer == spi_queued_transfer)
1585 __spi_pump_messages(ctlr, false);
1588 /*-------------------------------------------------------------------------*/
1590 #if defined(CONFIG_OF)
1591 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1592 struct device_node *nc)
1594 u32 value;
1595 int rc;
1597 /* Mode (clock phase/polarity/etc.) */
1598 if (of_property_read_bool(nc, "spi-cpha"))
1599 spi->mode |= SPI_CPHA;
1600 if (of_property_read_bool(nc, "spi-cpol"))
1601 spi->mode |= SPI_CPOL;
1602 if (of_property_read_bool(nc, "spi-cs-high"))
1603 spi->mode |= SPI_CS_HIGH;
1604 if (of_property_read_bool(nc, "spi-3wire"))
1605 spi->mode |= SPI_3WIRE;
1606 if (of_property_read_bool(nc, "spi-lsb-first"))
1607 spi->mode |= SPI_LSB_FIRST;
1609 /* Device DUAL/QUAD mode */
1610 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1611 switch (value) {
1612 case 1:
1613 break;
1614 case 2:
1615 spi->mode |= SPI_TX_DUAL;
1616 break;
1617 case 4:
1618 spi->mode |= SPI_TX_QUAD;
1619 break;
1620 default:
1621 dev_warn(&ctlr->dev,
1622 "spi-tx-bus-width %d not supported\n",
1623 value);
1624 break;
1628 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1629 switch (value) {
1630 case 1:
1631 break;
1632 case 2:
1633 spi->mode |= SPI_RX_DUAL;
1634 break;
1635 case 4:
1636 spi->mode |= SPI_RX_QUAD;
1637 break;
1638 default:
1639 dev_warn(&ctlr->dev,
1640 "spi-rx-bus-width %d not supported\n",
1641 value);
1642 break;
1646 if (spi_controller_is_slave(ctlr)) {
1647 if (strcmp(nc->name, "slave")) {
1648 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
1649 nc);
1650 return -EINVAL;
1652 return 0;
1655 /* Device address */
1656 rc = of_property_read_u32(nc, "reg", &value);
1657 if (rc) {
1658 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
1659 nc, rc);
1660 return rc;
1662 spi->chip_select = value;
1664 /* Device speed */
1665 rc = of_property_read_u32(nc, "spi-max-frequency", &value);
1666 if (rc) {
1667 dev_err(&ctlr->dev,
1668 "%pOF has no valid 'spi-max-frequency' property (%d)\n", nc, rc);
1669 return rc;
1671 spi->max_speed_hz = value;
1673 return 0;
1676 static struct spi_device *
1677 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
1679 struct spi_device *spi;
1680 int rc;
1682 /* Alloc an spi_device */
1683 spi = spi_alloc_device(ctlr);
1684 if (!spi) {
1685 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
1686 rc = -ENOMEM;
1687 goto err_out;
1690 /* Select device driver */
1691 rc = of_modalias_node(nc, spi->modalias,
1692 sizeof(spi->modalias));
1693 if (rc < 0) {
1694 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
1695 goto err_out;
1698 rc = of_spi_parse_dt(ctlr, spi, nc);
1699 if (rc)
1700 goto err_out;
1702 /* Store a pointer to the node in the device structure */
1703 of_node_get(nc);
1704 spi->dev.of_node = nc;
1706 /* Register the new device */
1707 rc = spi_add_device(spi);
1708 if (rc) {
1709 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
1710 goto err_of_node_put;
1713 return spi;
1715 err_of_node_put:
1716 of_node_put(nc);
1717 err_out:
1718 spi_dev_put(spi);
1719 return ERR_PTR(rc);
1723 * of_register_spi_devices() - Register child devices onto the SPI bus
1724 * @ctlr: Pointer to spi_controller device
1726 * Registers an spi_device for each child node of controller node which
1727 * represents a valid SPI slave.
1729 static void of_register_spi_devices(struct spi_controller *ctlr)
1731 struct spi_device *spi;
1732 struct device_node *nc;
1734 if (!ctlr->dev.of_node)
1735 return;
1737 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
1738 if (of_node_test_and_set_flag(nc, OF_POPULATED))
1739 continue;
1740 spi = of_register_spi_device(ctlr, nc);
1741 if (IS_ERR(spi)) {
1742 dev_warn(&ctlr->dev,
1743 "Failed to create SPI device for %pOF\n", nc);
1744 of_node_clear_flag(nc, OF_POPULATED);
1748 #else
1749 static void of_register_spi_devices(struct spi_controller *ctlr) { }
1750 #endif
1752 #ifdef CONFIG_ACPI
1753 static void acpi_spi_parse_apple_properties(struct spi_device *spi)
1755 struct acpi_device *dev = ACPI_COMPANION(&spi->dev);
1756 const union acpi_object *obj;
1758 if (!x86_apple_machine)
1759 return;
1761 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
1762 && obj->buffer.length >= 4)
1763 spi->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
1765 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
1766 && obj->buffer.length == 8)
1767 spi->bits_per_word = *(u64 *)obj->buffer.pointer;
1769 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
1770 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
1771 spi->mode |= SPI_LSB_FIRST;
1773 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
1774 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
1775 spi->mode |= SPI_CPOL;
1777 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
1778 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
1779 spi->mode |= SPI_CPHA;
1782 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
1784 struct spi_device *spi = data;
1785 struct spi_controller *ctlr = spi->controller;
1787 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
1788 struct acpi_resource_spi_serialbus *sb;
1790 sb = &ares->data.spi_serial_bus;
1791 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
1793 * ACPI DeviceSelection numbering is handled by the
1794 * host controller driver in Windows and can vary
1795 * from driver to driver. In Linux we always expect
1796 * 0 .. max - 1 so we need to ask the driver to
1797 * translate between the two schemes.
1799 if (ctlr->fw_translate_cs) {
1800 int cs = ctlr->fw_translate_cs(ctlr,
1801 sb->device_selection);
1802 if (cs < 0)
1803 return cs;
1804 spi->chip_select = cs;
1805 } else {
1806 spi->chip_select = sb->device_selection;
1809 spi->max_speed_hz = sb->connection_speed;
1811 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
1812 spi->mode |= SPI_CPHA;
1813 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
1814 spi->mode |= SPI_CPOL;
1815 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
1816 spi->mode |= SPI_CS_HIGH;
1818 } else if (spi->irq < 0) {
1819 struct resource r;
1821 if (acpi_dev_resource_interrupt(ares, 0, &r))
1822 spi->irq = r.start;
1825 /* Always tell the ACPI core to skip this resource */
1826 return 1;
1829 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
1830 struct acpi_device *adev)
1832 struct list_head resource_list;
1833 struct spi_device *spi;
1834 int ret;
1836 if (acpi_bus_get_status(adev) || !adev->status.present ||
1837 acpi_device_enumerated(adev))
1838 return AE_OK;
1840 spi = spi_alloc_device(ctlr);
1841 if (!spi) {
1842 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
1843 dev_name(&adev->dev));
1844 return AE_NO_MEMORY;
1847 ACPI_COMPANION_SET(&spi->dev, adev);
1848 spi->irq = -1;
1850 INIT_LIST_HEAD(&resource_list);
1851 ret = acpi_dev_get_resources(adev, &resource_list,
1852 acpi_spi_add_resource, spi);
1853 acpi_dev_free_resource_list(&resource_list);
1855 acpi_spi_parse_apple_properties(spi);
1857 if (ret < 0 || !spi->max_speed_hz) {
1858 spi_dev_put(spi);
1859 return AE_OK;
1862 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
1863 sizeof(spi->modalias));
1865 if (spi->irq < 0)
1866 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
1868 acpi_device_set_enumerated(adev);
1870 adev->power.flags.ignore_parent = true;
1871 if (spi_add_device(spi)) {
1872 adev->power.flags.ignore_parent = false;
1873 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
1874 dev_name(&adev->dev));
1875 spi_dev_put(spi);
1878 return AE_OK;
1881 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
1882 void *data, void **return_value)
1884 struct spi_controller *ctlr = data;
1885 struct acpi_device *adev;
1887 if (acpi_bus_get_device(handle, &adev))
1888 return AE_OK;
1890 return acpi_register_spi_device(ctlr, adev);
1893 static void acpi_register_spi_devices(struct spi_controller *ctlr)
1895 acpi_status status;
1896 acpi_handle handle;
1898 handle = ACPI_HANDLE(ctlr->dev.parent);
1899 if (!handle)
1900 return;
1902 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
1903 acpi_spi_add_device, NULL, ctlr, NULL);
1904 if (ACPI_FAILURE(status))
1905 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
1907 #else
1908 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
1909 #endif /* CONFIG_ACPI */
1911 static void spi_controller_release(struct device *dev)
1913 struct spi_controller *ctlr;
1915 ctlr = container_of(dev, struct spi_controller, dev);
1916 kfree(ctlr);
1919 static struct class spi_master_class = {
1920 .name = "spi_master",
1921 .owner = THIS_MODULE,
1922 .dev_release = spi_controller_release,
1923 .dev_groups = spi_master_groups,
1926 #ifdef CONFIG_SPI_SLAVE
1928 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
1929 * controller
1930 * @spi: device used for the current transfer
1932 int spi_slave_abort(struct spi_device *spi)
1934 struct spi_controller *ctlr = spi->controller;
1936 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
1937 return ctlr->slave_abort(ctlr);
1939 return -ENOTSUPP;
1941 EXPORT_SYMBOL_GPL(spi_slave_abort);
1943 static int match_true(struct device *dev, void *data)
1945 return 1;
1948 static ssize_t spi_slave_show(struct device *dev,
1949 struct device_attribute *attr, char *buf)
1951 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
1952 dev);
1953 struct device *child;
1955 child = device_find_child(&ctlr->dev, NULL, match_true);
1956 return sprintf(buf, "%s\n",
1957 child ? to_spi_device(child)->modalias : NULL);
1960 static ssize_t spi_slave_store(struct device *dev,
1961 struct device_attribute *attr, const char *buf,
1962 size_t count)
1964 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
1965 dev);
1966 struct spi_device *spi;
1967 struct device *child;
1968 char name[32];
1969 int rc;
1971 rc = sscanf(buf, "%31s", name);
1972 if (rc != 1 || !name[0])
1973 return -EINVAL;
1975 child = device_find_child(&ctlr->dev, NULL, match_true);
1976 if (child) {
1977 /* Remove registered slave */
1978 device_unregister(child);
1979 put_device(child);
1982 if (strcmp(name, "(null)")) {
1983 /* Register new slave */
1984 spi = spi_alloc_device(ctlr);
1985 if (!spi)
1986 return -ENOMEM;
1988 strlcpy(spi->modalias, name, sizeof(spi->modalias));
1990 rc = spi_add_device(spi);
1991 if (rc) {
1992 spi_dev_put(spi);
1993 return rc;
1997 return count;
2000 static DEVICE_ATTR(slave, 0644, spi_slave_show, spi_slave_store);
2002 static struct attribute *spi_slave_attrs[] = {
2003 &dev_attr_slave.attr,
2004 NULL,
2007 static const struct attribute_group spi_slave_group = {
2008 .attrs = spi_slave_attrs,
2011 static const struct attribute_group *spi_slave_groups[] = {
2012 &spi_controller_statistics_group,
2013 &spi_slave_group,
2014 NULL,
2017 static struct class spi_slave_class = {
2018 .name = "spi_slave",
2019 .owner = THIS_MODULE,
2020 .dev_release = spi_controller_release,
2021 .dev_groups = spi_slave_groups,
2023 #else
2024 extern struct class spi_slave_class; /* dummy */
2025 #endif
2028 * __spi_alloc_controller - allocate an SPI master or slave controller
2029 * @dev: the controller, possibly using the platform_bus
2030 * @size: how much zeroed driver-private data to allocate; the pointer to this
2031 * memory is in the driver_data field of the returned device,
2032 * accessible with spi_controller_get_devdata().
2033 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2034 * slave (true) controller
2035 * Context: can sleep
2037 * This call is used only by SPI controller drivers, which are the
2038 * only ones directly touching chip registers. It's how they allocate
2039 * an spi_controller structure, prior to calling spi_register_controller().
2041 * This must be called from context that can sleep.
2043 * The caller is responsible for assigning the bus number and initializing the
2044 * controller's methods before calling spi_register_controller(); and (after
2045 * errors adding the device) calling spi_controller_put() to prevent a memory
2046 * leak.
2048 * Return: the SPI controller structure on success, else NULL.
2050 struct spi_controller *__spi_alloc_controller(struct device *dev,
2051 unsigned int size, bool slave)
2053 struct spi_controller *ctlr;
2055 if (!dev)
2056 return NULL;
2058 ctlr = kzalloc(size + sizeof(*ctlr), GFP_KERNEL);
2059 if (!ctlr)
2060 return NULL;
2062 device_initialize(&ctlr->dev);
2063 ctlr->bus_num = -1;
2064 ctlr->num_chipselect = 1;
2065 ctlr->slave = slave;
2066 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2067 ctlr->dev.class = &spi_slave_class;
2068 else
2069 ctlr->dev.class = &spi_master_class;
2070 ctlr->dev.parent = dev;
2071 pm_suspend_ignore_children(&ctlr->dev, true);
2072 spi_controller_set_devdata(ctlr, &ctlr[1]);
2074 return ctlr;
2076 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2078 #ifdef CONFIG_OF
2079 static int of_spi_register_master(struct spi_controller *ctlr)
2081 int nb, i, *cs;
2082 struct device_node *np = ctlr->dev.of_node;
2084 if (!np)
2085 return 0;
2087 nb = of_gpio_named_count(np, "cs-gpios");
2088 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2090 /* Return error only for an incorrectly formed cs-gpios property */
2091 if (nb == 0 || nb == -ENOENT)
2092 return 0;
2093 else if (nb < 0)
2094 return nb;
2096 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2097 GFP_KERNEL);
2098 ctlr->cs_gpios = cs;
2100 if (!ctlr->cs_gpios)
2101 return -ENOMEM;
2103 for (i = 0; i < ctlr->num_chipselect; i++)
2104 cs[i] = -ENOENT;
2106 for (i = 0; i < nb; i++)
2107 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2109 return 0;
2111 #else
2112 static int of_spi_register_master(struct spi_controller *ctlr)
2114 return 0;
2116 #endif
2118 static int spi_controller_check_ops(struct spi_controller *ctlr)
2121 * The controller may implement only the high-level SPI-memory like
2122 * operations if it does not support regular SPI transfers, and this is
2123 * valid use case.
2124 * If ->mem_ops is NULL, we request that at least one of the
2125 * ->transfer_xxx() method be implemented.
2127 if (ctlr->mem_ops) {
2128 if (!ctlr->mem_ops->exec_op)
2129 return -EINVAL;
2130 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2131 !ctlr->transfer_one_message) {
2132 return -EINVAL;
2135 return 0;
2139 * spi_register_controller - register SPI master or slave controller
2140 * @ctlr: initialized master, originally from spi_alloc_master() or
2141 * spi_alloc_slave()
2142 * Context: can sleep
2144 * SPI controllers connect to their drivers using some non-SPI bus,
2145 * such as the platform bus. The final stage of probe() in that code
2146 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2148 * SPI controllers use board specific (often SOC specific) bus numbers,
2149 * and board-specific addressing for SPI devices combines those numbers
2150 * with chip select numbers. Since SPI does not directly support dynamic
2151 * device identification, boards need configuration tables telling which
2152 * chip is at which address.
2154 * This must be called from context that can sleep. It returns zero on
2155 * success, else a negative error code (dropping the controller's refcount).
2156 * After a successful return, the caller is responsible for calling
2157 * spi_unregister_controller().
2159 * Return: zero on success, else a negative error code.
2161 int spi_register_controller(struct spi_controller *ctlr)
2163 struct device *dev = ctlr->dev.parent;
2164 struct boardinfo *bi;
2165 int status = -ENODEV;
2166 int id, first_dynamic;
2168 if (!dev)
2169 return -ENODEV;
2172 * Make sure all necessary hooks are implemented before registering
2173 * the SPI controller.
2175 status = spi_controller_check_ops(ctlr);
2176 if (status)
2177 return status;
2179 if (!spi_controller_is_slave(ctlr)) {
2180 status = of_spi_register_master(ctlr);
2181 if (status)
2182 return status;
2185 /* even if it's just one always-selected device, there must
2186 * be at least one chipselect
2188 if (ctlr->num_chipselect == 0)
2189 return -EINVAL;
2190 if (ctlr->bus_num >= 0) {
2191 /* devices with a fixed bus num must check-in with the num */
2192 mutex_lock(&board_lock);
2193 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2194 ctlr->bus_num + 1, GFP_KERNEL);
2195 mutex_unlock(&board_lock);
2196 if (WARN(id < 0, "couldn't get idr"))
2197 return id == -ENOSPC ? -EBUSY : id;
2198 ctlr->bus_num = id;
2199 } else if (ctlr->dev.of_node) {
2200 /* allocate dynamic bus number using Linux idr */
2201 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2202 if (id >= 0) {
2203 ctlr->bus_num = id;
2204 mutex_lock(&board_lock);
2205 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2206 ctlr->bus_num + 1, GFP_KERNEL);
2207 mutex_unlock(&board_lock);
2208 if (WARN(id < 0, "couldn't get idr"))
2209 return id == -ENOSPC ? -EBUSY : id;
2212 if (ctlr->bus_num < 0) {
2213 first_dynamic = of_alias_get_highest_id("spi");
2214 if (first_dynamic < 0)
2215 first_dynamic = 0;
2216 else
2217 first_dynamic++;
2219 mutex_lock(&board_lock);
2220 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2221 0, GFP_KERNEL);
2222 mutex_unlock(&board_lock);
2223 if (WARN(id < 0, "couldn't get idr"))
2224 return id;
2225 ctlr->bus_num = id;
2227 INIT_LIST_HEAD(&ctlr->queue);
2228 spin_lock_init(&ctlr->queue_lock);
2229 spin_lock_init(&ctlr->bus_lock_spinlock);
2230 mutex_init(&ctlr->bus_lock_mutex);
2231 mutex_init(&ctlr->io_mutex);
2232 ctlr->bus_lock_flag = 0;
2233 init_completion(&ctlr->xfer_completion);
2234 if (!ctlr->max_dma_len)
2235 ctlr->max_dma_len = INT_MAX;
2237 /* register the device, then userspace will see it.
2238 * registration fails if the bus ID is in use.
2240 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2241 status = device_add(&ctlr->dev);
2242 if (status < 0) {
2243 /* free bus id */
2244 mutex_lock(&board_lock);
2245 idr_remove(&spi_master_idr, ctlr->bus_num);
2246 mutex_unlock(&board_lock);
2247 goto done;
2249 dev_dbg(dev, "registered %s %s\n",
2250 spi_controller_is_slave(ctlr) ? "slave" : "master",
2251 dev_name(&ctlr->dev));
2254 * If we're using a queued driver, start the queue. Note that we don't
2255 * need the queueing logic if the driver is only supporting high-level
2256 * memory operations.
2258 if (ctlr->transfer) {
2259 dev_info(dev, "controller is unqueued, this is deprecated\n");
2260 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2261 status = spi_controller_initialize_queue(ctlr);
2262 if (status) {
2263 device_del(&ctlr->dev);
2264 /* free bus id */
2265 mutex_lock(&board_lock);
2266 idr_remove(&spi_master_idr, ctlr->bus_num);
2267 mutex_unlock(&board_lock);
2268 goto done;
2271 /* add statistics */
2272 spin_lock_init(&ctlr->statistics.lock);
2274 mutex_lock(&board_lock);
2275 list_add_tail(&ctlr->list, &spi_controller_list);
2276 list_for_each_entry(bi, &board_list, list)
2277 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2278 mutex_unlock(&board_lock);
2280 /* Register devices from the device tree and ACPI */
2281 of_register_spi_devices(ctlr);
2282 acpi_register_spi_devices(ctlr);
2283 done:
2284 return status;
2286 EXPORT_SYMBOL_GPL(spi_register_controller);
2288 static void devm_spi_unregister(struct device *dev, void *res)
2290 spi_unregister_controller(*(struct spi_controller **)res);
2294 * devm_spi_register_controller - register managed SPI master or slave
2295 * controller
2296 * @dev: device managing SPI controller
2297 * @ctlr: initialized controller, originally from spi_alloc_master() or
2298 * spi_alloc_slave()
2299 * Context: can sleep
2301 * Register a SPI device as with spi_register_controller() which will
2302 * automatically be unregistered and freed.
2304 * Return: zero on success, else a negative error code.
2306 int devm_spi_register_controller(struct device *dev,
2307 struct spi_controller *ctlr)
2309 struct spi_controller **ptr;
2310 int ret;
2312 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2313 if (!ptr)
2314 return -ENOMEM;
2316 ret = spi_register_controller(ctlr);
2317 if (!ret) {
2318 *ptr = ctlr;
2319 devres_add(dev, ptr);
2320 } else {
2321 devres_free(ptr);
2324 return ret;
2326 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2328 static int __unregister(struct device *dev, void *null)
2330 spi_unregister_device(to_spi_device(dev));
2331 return 0;
2335 * spi_unregister_controller - unregister SPI master or slave controller
2336 * @ctlr: the controller being unregistered
2337 * Context: can sleep
2339 * This call is used only by SPI controller drivers, which are the
2340 * only ones directly touching chip registers.
2342 * This must be called from context that can sleep.
2344 * Note that this function also drops a reference to the controller.
2346 void spi_unregister_controller(struct spi_controller *ctlr)
2348 struct spi_controller *found;
2349 int id = ctlr->bus_num;
2350 int dummy;
2352 /* First make sure that this controller was ever added */
2353 mutex_lock(&board_lock);
2354 found = idr_find(&spi_master_idr, id);
2355 mutex_unlock(&board_lock);
2356 if (ctlr->queued) {
2357 if (spi_destroy_queue(ctlr))
2358 dev_err(&ctlr->dev, "queue remove failed\n");
2360 mutex_lock(&board_lock);
2361 list_del(&ctlr->list);
2362 mutex_unlock(&board_lock);
2364 dummy = device_for_each_child(&ctlr->dev, NULL, __unregister);
2365 device_unregister(&ctlr->dev);
2366 /* free bus id */
2367 mutex_lock(&board_lock);
2368 if (found == ctlr)
2369 idr_remove(&spi_master_idr, id);
2370 mutex_unlock(&board_lock);
2372 EXPORT_SYMBOL_GPL(spi_unregister_controller);
2374 int spi_controller_suspend(struct spi_controller *ctlr)
2376 int ret;
2378 /* Basically no-ops for non-queued controllers */
2379 if (!ctlr->queued)
2380 return 0;
2382 ret = spi_stop_queue(ctlr);
2383 if (ret)
2384 dev_err(&ctlr->dev, "queue stop failed\n");
2386 return ret;
2388 EXPORT_SYMBOL_GPL(spi_controller_suspend);
2390 int spi_controller_resume(struct spi_controller *ctlr)
2392 int ret;
2394 if (!ctlr->queued)
2395 return 0;
2397 ret = spi_start_queue(ctlr);
2398 if (ret)
2399 dev_err(&ctlr->dev, "queue restart failed\n");
2401 return ret;
2403 EXPORT_SYMBOL_GPL(spi_controller_resume);
2405 static int __spi_controller_match(struct device *dev, const void *data)
2407 struct spi_controller *ctlr;
2408 const u16 *bus_num = data;
2410 ctlr = container_of(dev, struct spi_controller, dev);
2411 return ctlr->bus_num == *bus_num;
2415 * spi_busnum_to_master - look up master associated with bus_num
2416 * @bus_num: the master's bus number
2417 * Context: can sleep
2419 * This call may be used with devices that are registered after
2420 * arch init time. It returns a refcounted pointer to the relevant
2421 * spi_controller (which the caller must release), or NULL if there is
2422 * no such master registered.
2424 * Return: the SPI master structure on success, else NULL.
2426 struct spi_controller *spi_busnum_to_master(u16 bus_num)
2428 struct device *dev;
2429 struct spi_controller *ctlr = NULL;
2431 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2432 __spi_controller_match);
2433 if (dev)
2434 ctlr = container_of(dev, struct spi_controller, dev);
2435 /* reference got in class_find_device */
2436 return ctlr;
2438 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2440 /*-------------------------------------------------------------------------*/
2442 /* Core methods for SPI resource management */
2445 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2446 * during the processing of a spi_message while using
2447 * spi_transfer_one
2448 * @spi: the spi device for which we allocate memory
2449 * @release: the release code to execute for this resource
2450 * @size: size to alloc and return
2451 * @gfp: GFP allocation flags
2453 * Return: the pointer to the allocated data
2455 * This may get enhanced in the future to allocate from a memory pool
2456 * of the @spi_device or @spi_controller to avoid repeated allocations.
2458 void *spi_res_alloc(struct spi_device *spi,
2459 spi_res_release_t release,
2460 size_t size, gfp_t gfp)
2462 struct spi_res *sres;
2464 sres = kzalloc(sizeof(*sres) + size, gfp);
2465 if (!sres)
2466 return NULL;
2468 INIT_LIST_HEAD(&sres->entry);
2469 sres->release = release;
2471 return sres->data;
2473 EXPORT_SYMBOL_GPL(spi_res_alloc);
2476 * spi_res_free - free an spi resource
2477 * @res: pointer to the custom data of a resource
2480 void spi_res_free(void *res)
2482 struct spi_res *sres = container_of(res, struct spi_res, data);
2484 if (!res)
2485 return;
2487 WARN_ON(!list_empty(&sres->entry));
2488 kfree(sres);
2490 EXPORT_SYMBOL_GPL(spi_res_free);
2493 * spi_res_add - add a spi_res to the spi_message
2494 * @message: the spi message
2495 * @res: the spi_resource
2497 void spi_res_add(struct spi_message *message, void *res)
2499 struct spi_res *sres = container_of(res, struct spi_res, data);
2501 WARN_ON(!list_empty(&sres->entry));
2502 list_add_tail(&sres->entry, &message->resources);
2504 EXPORT_SYMBOL_GPL(spi_res_add);
2507 * spi_res_release - release all spi resources for this message
2508 * @ctlr: the @spi_controller
2509 * @message: the @spi_message
2511 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
2513 struct spi_res *res;
2515 while (!list_empty(&message->resources)) {
2516 res = list_last_entry(&message->resources,
2517 struct spi_res, entry);
2519 if (res->release)
2520 res->release(ctlr, message, res->data);
2522 list_del(&res->entry);
2524 kfree(res);
2527 EXPORT_SYMBOL_GPL(spi_res_release);
2529 /*-------------------------------------------------------------------------*/
2531 /* Core methods for spi_message alterations */
2533 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
2534 struct spi_message *msg,
2535 void *res)
2537 struct spi_replaced_transfers *rxfer = res;
2538 size_t i;
2540 /* call extra callback if requested */
2541 if (rxfer->release)
2542 rxfer->release(ctlr, msg, res);
2544 /* insert replaced transfers back into the message */
2545 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
2547 /* remove the formerly inserted entries */
2548 for (i = 0; i < rxfer->inserted; i++)
2549 list_del(&rxfer->inserted_transfers[i].transfer_list);
2553 * spi_replace_transfers - replace transfers with several transfers
2554 * and register change with spi_message.resources
2555 * @msg: the spi_message we work upon
2556 * @xfer_first: the first spi_transfer we want to replace
2557 * @remove: number of transfers to remove
2558 * @insert: the number of transfers we want to insert instead
2559 * @release: extra release code necessary in some circumstances
2560 * @extradatasize: extra data to allocate (with alignment guarantees
2561 * of struct @spi_transfer)
2562 * @gfp: gfp flags
2564 * Returns: pointer to @spi_replaced_transfers,
2565 * PTR_ERR(...) in case of errors.
2567 struct spi_replaced_transfers *spi_replace_transfers(
2568 struct spi_message *msg,
2569 struct spi_transfer *xfer_first,
2570 size_t remove,
2571 size_t insert,
2572 spi_replaced_release_t release,
2573 size_t extradatasize,
2574 gfp_t gfp)
2576 struct spi_replaced_transfers *rxfer;
2577 struct spi_transfer *xfer;
2578 size_t i;
2580 /* allocate the structure using spi_res */
2581 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
2582 insert * sizeof(struct spi_transfer)
2583 + sizeof(struct spi_replaced_transfers)
2584 + extradatasize,
2585 gfp);
2586 if (!rxfer)
2587 return ERR_PTR(-ENOMEM);
2589 /* the release code to invoke before running the generic release */
2590 rxfer->release = release;
2592 /* assign extradata */
2593 if (extradatasize)
2594 rxfer->extradata =
2595 &rxfer->inserted_transfers[insert];
2597 /* init the replaced_transfers list */
2598 INIT_LIST_HEAD(&rxfer->replaced_transfers);
2600 /* assign the list_entry after which we should reinsert
2601 * the @replaced_transfers - it may be spi_message.messages!
2603 rxfer->replaced_after = xfer_first->transfer_list.prev;
2605 /* remove the requested number of transfers */
2606 for (i = 0; i < remove; i++) {
2607 /* if the entry after replaced_after it is msg->transfers
2608 * then we have been requested to remove more transfers
2609 * than are in the list
2611 if (rxfer->replaced_after->next == &msg->transfers) {
2612 dev_err(&msg->spi->dev,
2613 "requested to remove more spi_transfers than are available\n");
2614 /* insert replaced transfers back into the message */
2615 list_splice(&rxfer->replaced_transfers,
2616 rxfer->replaced_after);
2618 /* free the spi_replace_transfer structure */
2619 spi_res_free(rxfer);
2621 /* and return with an error */
2622 return ERR_PTR(-EINVAL);
2625 /* remove the entry after replaced_after from list of
2626 * transfers and add it to list of replaced_transfers
2628 list_move_tail(rxfer->replaced_after->next,
2629 &rxfer->replaced_transfers);
2632 /* create copy of the given xfer with identical settings
2633 * based on the first transfer to get removed
2635 for (i = 0; i < insert; i++) {
2636 /* we need to run in reverse order */
2637 xfer = &rxfer->inserted_transfers[insert - 1 - i];
2639 /* copy all spi_transfer data */
2640 memcpy(xfer, xfer_first, sizeof(*xfer));
2642 /* add to list */
2643 list_add(&xfer->transfer_list, rxfer->replaced_after);
2645 /* clear cs_change and delay_usecs for all but the last */
2646 if (i) {
2647 xfer->cs_change = false;
2648 xfer->delay_usecs = 0;
2652 /* set up inserted */
2653 rxfer->inserted = insert;
2655 /* and register it with spi_res/spi_message */
2656 spi_res_add(msg, rxfer);
2658 return rxfer;
2660 EXPORT_SYMBOL_GPL(spi_replace_transfers);
2662 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
2663 struct spi_message *msg,
2664 struct spi_transfer **xferp,
2665 size_t maxsize,
2666 gfp_t gfp)
2668 struct spi_transfer *xfer = *xferp, *xfers;
2669 struct spi_replaced_transfers *srt;
2670 size_t offset;
2671 size_t count, i;
2673 /* warn once about this fact that we are splitting a transfer */
2674 dev_warn_once(&msg->spi->dev,
2675 "spi_transfer of length %i exceed max length of %zu - needed to split transfers\n",
2676 xfer->len, maxsize);
2678 /* calculate how many we have to replace */
2679 count = DIV_ROUND_UP(xfer->len, maxsize);
2681 /* create replacement */
2682 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
2683 if (IS_ERR(srt))
2684 return PTR_ERR(srt);
2685 xfers = srt->inserted_transfers;
2687 /* now handle each of those newly inserted spi_transfers
2688 * note that the replacements spi_transfers all are preset
2689 * to the same values as *xferp, so tx_buf, rx_buf and len
2690 * are all identical (as well as most others)
2691 * so we just have to fix up len and the pointers.
2693 * this also includes support for the depreciated
2694 * spi_message.is_dma_mapped interface
2697 /* the first transfer just needs the length modified, so we
2698 * run it outside the loop
2700 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
2702 /* all the others need rx_buf/tx_buf also set */
2703 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
2704 /* update rx_buf, tx_buf and dma */
2705 if (xfers[i].rx_buf)
2706 xfers[i].rx_buf += offset;
2707 if (xfers[i].rx_dma)
2708 xfers[i].rx_dma += offset;
2709 if (xfers[i].tx_buf)
2710 xfers[i].tx_buf += offset;
2711 if (xfers[i].tx_dma)
2712 xfers[i].tx_dma += offset;
2714 /* update length */
2715 xfers[i].len = min(maxsize, xfers[i].len - offset);
2718 /* we set up xferp to the last entry we have inserted,
2719 * so that we skip those already split transfers
2721 *xferp = &xfers[count - 1];
2723 /* increment statistics counters */
2724 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
2725 transfers_split_maxsize);
2726 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
2727 transfers_split_maxsize);
2729 return 0;
2733 * spi_split_tranfers_maxsize - split spi transfers into multiple transfers
2734 * when an individual transfer exceeds a
2735 * certain size
2736 * @ctlr: the @spi_controller for this transfer
2737 * @msg: the @spi_message to transform
2738 * @maxsize: the maximum when to apply this
2739 * @gfp: GFP allocation flags
2741 * Return: status of transformation
2743 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
2744 struct spi_message *msg,
2745 size_t maxsize,
2746 gfp_t gfp)
2748 struct spi_transfer *xfer;
2749 int ret;
2751 /* iterate over the transfer_list,
2752 * but note that xfer is advanced to the last transfer inserted
2753 * to avoid checking sizes again unnecessarily (also xfer does
2754 * potentiall belong to a different list by the time the
2755 * replacement has happened
2757 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
2758 if (xfer->len > maxsize) {
2759 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
2760 maxsize, gfp);
2761 if (ret)
2762 return ret;
2766 return 0;
2768 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
2770 /*-------------------------------------------------------------------------*/
2772 /* Core methods for SPI controller protocol drivers. Some of the
2773 * other core methods are currently defined as inline functions.
2776 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
2777 u8 bits_per_word)
2779 if (ctlr->bits_per_word_mask) {
2780 /* Only 32 bits fit in the mask */
2781 if (bits_per_word > 32)
2782 return -EINVAL;
2783 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
2784 return -EINVAL;
2787 return 0;
2791 * spi_setup - setup SPI mode and clock rate
2792 * @spi: the device whose settings are being modified
2793 * Context: can sleep, and no requests are queued to the device
2795 * SPI protocol drivers may need to update the transfer mode if the
2796 * device doesn't work with its default. They may likewise need
2797 * to update clock rates or word sizes from initial values. This function
2798 * changes those settings, and must be called from a context that can sleep.
2799 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
2800 * effect the next time the device is selected and data is transferred to
2801 * or from it. When this function returns, the spi device is deselected.
2803 * Note that this call will fail if the protocol driver specifies an option
2804 * that the underlying controller or its driver does not support. For
2805 * example, not all hardware supports wire transfers using nine bit words,
2806 * LSB-first wire encoding, or active-high chipselects.
2808 * Return: zero on success, else a negative error code.
2810 int spi_setup(struct spi_device *spi)
2812 unsigned bad_bits, ugly_bits;
2813 int status;
2815 /* check mode to prevent that DUAL and QUAD set at the same time
2817 if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
2818 ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
2819 dev_err(&spi->dev,
2820 "setup: can not select dual and quad at the same time\n");
2821 return -EINVAL;
2823 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
2825 if ((spi->mode & SPI_3WIRE) && (spi->mode &
2826 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
2827 return -EINVAL;
2828 /* help drivers fail *cleanly* when they need options
2829 * that aren't supported with their current controller
2830 * SPI_CS_WORD has a fallback software implementation,
2831 * so it is ignored here.
2833 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD);
2834 ugly_bits = bad_bits &
2835 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD);
2836 if (ugly_bits) {
2837 dev_warn(&spi->dev,
2838 "setup: ignoring unsupported mode bits %x\n",
2839 ugly_bits);
2840 spi->mode &= ~ugly_bits;
2841 bad_bits &= ~ugly_bits;
2843 if (bad_bits) {
2844 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
2845 bad_bits);
2846 return -EINVAL;
2849 if (!spi->bits_per_word)
2850 spi->bits_per_word = 8;
2852 status = __spi_validate_bits_per_word(spi->controller,
2853 spi->bits_per_word);
2854 if (status)
2855 return status;
2857 if (!spi->max_speed_hz)
2858 spi->max_speed_hz = spi->controller->max_speed_hz;
2860 if (spi->controller->setup)
2861 status = spi->controller->setup(spi);
2863 spi_set_cs(spi, false);
2865 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
2866 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
2867 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
2868 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
2869 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
2870 (spi->mode & SPI_LOOP) ? "loopback, " : "",
2871 spi->bits_per_word, spi->max_speed_hz,
2872 status);
2874 return status;
2876 EXPORT_SYMBOL_GPL(spi_setup);
2878 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
2880 struct spi_controller *ctlr = spi->controller;
2881 struct spi_transfer *xfer;
2882 int w_size;
2884 if (list_empty(&message->transfers))
2885 return -EINVAL;
2887 /* If an SPI controller does not support toggling the CS line on each
2888 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
2889 * for the CS line, we can emulate the CS-per-word hardware function by
2890 * splitting transfers into one-word transfers and ensuring that
2891 * cs_change is set for each transfer.
2893 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
2894 gpio_is_valid(spi->cs_gpio))) {
2895 size_t maxsize;
2896 int ret;
2898 maxsize = (spi->bits_per_word + 7) / 8;
2900 /* spi_split_transfers_maxsize() requires message->spi */
2901 message->spi = spi;
2903 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
2904 GFP_KERNEL);
2905 if (ret)
2906 return ret;
2908 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2909 /* don't change cs_change on the last entry in the list */
2910 if (list_is_last(&xfer->transfer_list, &message->transfers))
2911 break;
2912 xfer->cs_change = 1;
2916 /* Half-duplex links include original MicroWire, and ones with
2917 * only one data pin like SPI_3WIRE (switches direction) or where
2918 * either MOSI or MISO is missing. They can also be caused by
2919 * software limitations.
2921 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
2922 (spi->mode & SPI_3WIRE)) {
2923 unsigned flags = ctlr->flags;
2925 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2926 if (xfer->rx_buf && xfer->tx_buf)
2927 return -EINVAL;
2928 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
2929 return -EINVAL;
2930 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
2931 return -EINVAL;
2936 * Set transfer bits_per_word and max speed as spi device default if
2937 * it is not set for this transfer.
2938 * Set transfer tx_nbits and rx_nbits as single transfer default
2939 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
2941 message->frame_length = 0;
2942 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2943 message->frame_length += xfer->len;
2944 if (!xfer->bits_per_word)
2945 xfer->bits_per_word = spi->bits_per_word;
2947 if (!xfer->speed_hz)
2948 xfer->speed_hz = spi->max_speed_hz;
2949 if (!xfer->speed_hz)
2950 xfer->speed_hz = ctlr->max_speed_hz;
2952 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
2953 xfer->speed_hz = ctlr->max_speed_hz;
2955 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
2956 return -EINVAL;
2959 * SPI transfer length should be multiple of SPI word size
2960 * where SPI word size should be power-of-two multiple
2962 if (xfer->bits_per_word <= 8)
2963 w_size = 1;
2964 else if (xfer->bits_per_word <= 16)
2965 w_size = 2;
2966 else
2967 w_size = 4;
2969 /* No partial transfers accepted */
2970 if (xfer->len % w_size)
2971 return -EINVAL;
2973 if (xfer->speed_hz && ctlr->min_speed_hz &&
2974 xfer->speed_hz < ctlr->min_speed_hz)
2975 return -EINVAL;
2977 if (xfer->tx_buf && !xfer->tx_nbits)
2978 xfer->tx_nbits = SPI_NBITS_SINGLE;
2979 if (xfer->rx_buf && !xfer->rx_nbits)
2980 xfer->rx_nbits = SPI_NBITS_SINGLE;
2981 /* check transfer tx/rx_nbits:
2982 * 1. check the value matches one of single, dual and quad
2983 * 2. check tx/rx_nbits match the mode in spi_device
2985 if (xfer->tx_buf) {
2986 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
2987 xfer->tx_nbits != SPI_NBITS_DUAL &&
2988 xfer->tx_nbits != SPI_NBITS_QUAD)
2989 return -EINVAL;
2990 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
2991 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
2992 return -EINVAL;
2993 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
2994 !(spi->mode & SPI_TX_QUAD))
2995 return -EINVAL;
2997 /* check transfer rx_nbits */
2998 if (xfer->rx_buf) {
2999 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3000 xfer->rx_nbits != SPI_NBITS_DUAL &&
3001 xfer->rx_nbits != SPI_NBITS_QUAD)
3002 return -EINVAL;
3003 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3004 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3005 return -EINVAL;
3006 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3007 !(spi->mode & SPI_RX_QUAD))
3008 return -EINVAL;
3012 message->status = -EINPROGRESS;
3014 return 0;
3017 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3019 struct spi_controller *ctlr = spi->controller;
3022 * Some controllers do not support doing regular SPI transfers. Return
3023 * ENOTSUPP when this is the case.
3025 if (!ctlr->transfer)
3026 return -ENOTSUPP;
3028 message->spi = spi;
3030 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3031 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3033 trace_spi_message_submit(message);
3035 return ctlr->transfer(spi, message);
3039 * spi_async - asynchronous SPI transfer
3040 * @spi: device with which data will be exchanged
3041 * @message: describes the data transfers, including completion callback
3042 * Context: any (irqs may be blocked, etc)
3044 * This call may be used in_irq and other contexts which can't sleep,
3045 * as well as from task contexts which can sleep.
3047 * The completion callback is invoked in a context which can't sleep.
3048 * Before that invocation, the value of message->status is undefined.
3049 * When the callback is issued, message->status holds either zero (to
3050 * indicate complete success) or a negative error code. After that
3051 * callback returns, the driver which issued the transfer request may
3052 * deallocate the associated memory; it's no longer in use by any SPI
3053 * core or controller driver code.
3055 * Note that although all messages to a spi_device are handled in
3056 * FIFO order, messages may go to different devices in other orders.
3057 * Some device might be higher priority, or have various "hard" access
3058 * time requirements, for example.
3060 * On detection of any fault during the transfer, processing of
3061 * the entire message is aborted, and the device is deselected.
3062 * Until returning from the associated message completion callback,
3063 * no other spi_message queued to that device will be processed.
3064 * (This rule applies equally to all the synchronous transfer calls,
3065 * which are wrappers around this core asynchronous primitive.)
3067 * Return: zero on success, else a negative error code.
3069 int spi_async(struct spi_device *spi, struct spi_message *message)
3071 struct spi_controller *ctlr = spi->controller;
3072 int ret;
3073 unsigned long flags;
3075 ret = __spi_validate(spi, message);
3076 if (ret != 0)
3077 return ret;
3079 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3081 if (ctlr->bus_lock_flag)
3082 ret = -EBUSY;
3083 else
3084 ret = __spi_async(spi, message);
3086 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3088 return ret;
3090 EXPORT_SYMBOL_GPL(spi_async);
3093 * spi_async_locked - version of spi_async with exclusive bus usage
3094 * @spi: device with which data will be exchanged
3095 * @message: describes the data transfers, including completion callback
3096 * Context: any (irqs may be blocked, etc)
3098 * This call may be used in_irq and other contexts which can't sleep,
3099 * as well as from task contexts which can sleep.
3101 * The completion callback is invoked in a context which can't sleep.
3102 * Before that invocation, the value of message->status is undefined.
3103 * When the callback is issued, message->status holds either zero (to
3104 * indicate complete success) or a negative error code. After that
3105 * callback returns, the driver which issued the transfer request may
3106 * deallocate the associated memory; it's no longer in use by any SPI
3107 * core or controller driver code.
3109 * Note that although all messages to a spi_device are handled in
3110 * FIFO order, messages may go to different devices in other orders.
3111 * Some device might be higher priority, or have various "hard" access
3112 * time requirements, for example.
3114 * On detection of any fault during the transfer, processing of
3115 * the entire message is aborted, and the device is deselected.
3116 * Until returning from the associated message completion callback,
3117 * no other spi_message queued to that device will be processed.
3118 * (This rule applies equally to all the synchronous transfer calls,
3119 * which are wrappers around this core asynchronous primitive.)
3121 * Return: zero on success, else a negative error code.
3123 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3125 struct spi_controller *ctlr = spi->controller;
3126 int ret;
3127 unsigned long flags;
3129 ret = __spi_validate(spi, message);
3130 if (ret != 0)
3131 return ret;
3133 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3135 ret = __spi_async(spi, message);
3137 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3139 return ret;
3142 EXPORT_SYMBOL_GPL(spi_async_locked);
3144 /*-------------------------------------------------------------------------*/
3146 /* Utility methods for SPI protocol drivers, layered on
3147 * top of the core. Some other utility methods are defined as
3148 * inline functions.
3151 static void spi_complete(void *arg)
3153 complete(arg);
3156 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3158 DECLARE_COMPLETION_ONSTACK(done);
3159 int status;
3160 struct spi_controller *ctlr = spi->controller;
3161 unsigned long flags;
3163 status = __spi_validate(spi, message);
3164 if (status != 0)
3165 return status;
3167 message->complete = spi_complete;
3168 message->context = &done;
3169 message->spi = spi;
3171 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3172 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3174 /* If we're not using the legacy transfer method then we will
3175 * try to transfer in the calling context so special case.
3176 * This code would be less tricky if we could remove the
3177 * support for driver implemented message queues.
3179 if (ctlr->transfer == spi_queued_transfer) {
3180 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3182 trace_spi_message_submit(message);
3184 status = __spi_queued_transfer(spi, message, false);
3186 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3187 } else {
3188 status = spi_async_locked(spi, message);
3191 if (status == 0) {
3192 /* Push out the messages in the calling context if we
3193 * can.
3195 if (ctlr->transfer == spi_queued_transfer) {
3196 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3197 spi_sync_immediate);
3198 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3199 spi_sync_immediate);
3200 __spi_pump_messages(ctlr, false);
3203 wait_for_completion(&done);
3204 status = message->status;
3206 message->context = NULL;
3207 return status;
3211 * spi_sync - blocking/synchronous SPI data transfers
3212 * @spi: device with which data will be exchanged
3213 * @message: describes the data transfers
3214 * Context: can sleep
3216 * This call may only be used from a context that may sleep. The sleep
3217 * is non-interruptible, and has no timeout. Low-overhead controller
3218 * drivers may DMA directly into and out of the message buffers.
3220 * Note that the SPI device's chip select is active during the message,
3221 * and then is normally disabled between messages. Drivers for some
3222 * frequently-used devices may want to minimize costs of selecting a chip,
3223 * by leaving it selected in anticipation that the next message will go
3224 * to the same chip. (That may increase power usage.)
3226 * Also, the caller is guaranteeing that the memory associated with the
3227 * message will not be freed before this call returns.
3229 * Return: zero on success, else a negative error code.
3231 int spi_sync(struct spi_device *spi, struct spi_message *message)
3233 int ret;
3235 mutex_lock(&spi->controller->bus_lock_mutex);
3236 ret = __spi_sync(spi, message);
3237 mutex_unlock(&spi->controller->bus_lock_mutex);
3239 return ret;
3241 EXPORT_SYMBOL_GPL(spi_sync);
3244 * spi_sync_locked - version of spi_sync with exclusive bus usage
3245 * @spi: device with which data will be exchanged
3246 * @message: describes the data transfers
3247 * Context: can sleep
3249 * This call may only be used from a context that may sleep. The sleep
3250 * is non-interruptible, and has no timeout. Low-overhead controller
3251 * drivers may DMA directly into and out of the message buffers.
3253 * This call should be used by drivers that require exclusive access to the
3254 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3255 * be released by a spi_bus_unlock call when the exclusive access is over.
3257 * Return: zero on success, else a negative error code.
3259 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3261 return __spi_sync(spi, message);
3263 EXPORT_SYMBOL_GPL(spi_sync_locked);
3266 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3267 * @ctlr: SPI bus master that should be locked for exclusive bus access
3268 * Context: can sleep
3270 * This call may only be used from a context that may sleep. The sleep
3271 * is non-interruptible, and has no timeout.
3273 * This call should be used by drivers that require exclusive access to the
3274 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3275 * exclusive access is over. Data transfer must be done by spi_sync_locked
3276 * and spi_async_locked calls when the SPI bus lock is held.
3278 * Return: always zero.
3280 int spi_bus_lock(struct spi_controller *ctlr)
3282 unsigned long flags;
3284 mutex_lock(&ctlr->bus_lock_mutex);
3286 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3287 ctlr->bus_lock_flag = 1;
3288 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3290 /* mutex remains locked until spi_bus_unlock is called */
3292 return 0;
3294 EXPORT_SYMBOL_GPL(spi_bus_lock);
3297 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3298 * @ctlr: SPI bus master that was locked for exclusive bus access
3299 * Context: can sleep
3301 * This call may only be used from a context that may sleep. The sleep
3302 * is non-interruptible, and has no timeout.
3304 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3305 * call.
3307 * Return: always zero.
3309 int spi_bus_unlock(struct spi_controller *ctlr)
3311 ctlr->bus_lock_flag = 0;
3313 mutex_unlock(&ctlr->bus_lock_mutex);
3315 return 0;
3317 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3319 /* portable code must never pass more than 32 bytes */
3320 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
3322 static u8 *buf;
3325 * spi_write_then_read - SPI synchronous write followed by read
3326 * @spi: device with which data will be exchanged
3327 * @txbuf: data to be written (need not be dma-safe)
3328 * @n_tx: size of txbuf, in bytes
3329 * @rxbuf: buffer into which data will be read (need not be dma-safe)
3330 * @n_rx: size of rxbuf, in bytes
3331 * Context: can sleep
3333 * This performs a half duplex MicroWire style transaction with the
3334 * device, sending txbuf and then reading rxbuf. The return value
3335 * is zero for success, else a negative errno status code.
3336 * This call may only be used from a context that may sleep.
3338 * Parameters to this routine are always copied using a small buffer;
3339 * portable code should never use this for more than 32 bytes.
3340 * Performance-sensitive or bulk transfer code should instead use
3341 * spi_{async,sync}() calls with dma-safe buffers.
3343 * Return: zero on success, else a negative error code.
3345 int spi_write_then_read(struct spi_device *spi,
3346 const void *txbuf, unsigned n_tx,
3347 void *rxbuf, unsigned n_rx)
3349 static DEFINE_MUTEX(lock);
3351 int status;
3352 struct spi_message message;
3353 struct spi_transfer x[2];
3354 u8 *local_buf;
3356 /* Use preallocated DMA-safe buffer if we can. We can't avoid
3357 * copying here, (as a pure convenience thing), but we can
3358 * keep heap costs out of the hot path unless someone else is
3359 * using the pre-allocated buffer or the transfer is too large.
3361 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
3362 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
3363 GFP_KERNEL | GFP_DMA);
3364 if (!local_buf)
3365 return -ENOMEM;
3366 } else {
3367 local_buf = buf;
3370 spi_message_init(&message);
3371 memset(x, 0, sizeof(x));
3372 if (n_tx) {
3373 x[0].len = n_tx;
3374 spi_message_add_tail(&x[0], &message);
3376 if (n_rx) {
3377 x[1].len = n_rx;
3378 spi_message_add_tail(&x[1], &message);
3381 memcpy(local_buf, txbuf, n_tx);
3382 x[0].tx_buf = local_buf;
3383 x[1].rx_buf = local_buf + n_tx;
3385 /* do the i/o */
3386 status = spi_sync(spi, &message);
3387 if (status == 0)
3388 memcpy(rxbuf, x[1].rx_buf, n_rx);
3390 if (x[0].tx_buf == buf)
3391 mutex_unlock(&lock);
3392 else
3393 kfree(local_buf);
3395 return status;
3397 EXPORT_SYMBOL_GPL(spi_write_then_read);
3399 /*-------------------------------------------------------------------------*/
3401 #if IS_ENABLED(CONFIG_OF)
3402 static int __spi_of_device_match(struct device *dev, void *data)
3404 return dev->of_node == data;
3407 /* must call put_device() when done with returned spi_device device */
3408 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
3410 struct device *dev = bus_find_device(&spi_bus_type, NULL, node,
3411 __spi_of_device_match);
3412 return dev ? to_spi_device(dev) : NULL;
3414 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
3415 #endif /* IS_ENABLED(CONFIG_OF) */
3417 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
3418 static int __spi_of_controller_match(struct device *dev, const void *data)
3420 return dev->of_node == data;
3423 /* the spi controllers are not using spi_bus, so we find it with another way */
3424 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
3426 struct device *dev;
3428 dev = class_find_device(&spi_master_class, NULL, node,
3429 __spi_of_controller_match);
3430 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3431 dev = class_find_device(&spi_slave_class, NULL, node,
3432 __spi_of_controller_match);
3433 if (!dev)
3434 return NULL;
3436 /* reference got in class_find_device */
3437 return container_of(dev, struct spi_controller, dev);
3440 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
3441 void *arg)
3443 struct of_reconfig_data *rd = arg;
3444 struct spi_controller *ctlr;
3445 struct spi_device *spi;
3447 switch (of_reconfig_get_state_change(action, arg)) {
3448 case OF_RECONFIG_CHANGE_ADD:
3449 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
3450 if (ctlr == NULL)
3451 return NOTIFY_OK; /* not for us */
3453 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
3454 put_device(&ctlr->dev);
3455 return NOTIFY_OK;
3458 spi = of_register_spi_device(ctlr, rd->dn);
3459 put_device(&ctlr->dev);
3461 if (IS_ERR(spi)) {
3462 pr_err("%s: failed to create for '%pOF'\n",
3463 __func__, rd->dn);
3464 of_node_clear_flag(rd->dn, OF_POPULATED);
3465 return notifier_from_errno(PTR_ERR(spi));
3467 break;
3469 case OF_RECONFIG_CHANGE_REMOVE:
3470 /* already depopulated? */
3471 if (!of_node_check_flag(rd->dn, OF_POPULATED))
3472 return NOTIFY_OK;
3474 /* find our device by node */
3475 spi = of_find_spi_device_by_node(rd->dn);
3476 if (spi == NULL)
3477 return NOTIFY_OK; /* no? not meant for us */
3479 /* unregister takes one ref away */
3480 spi_unregister_device(spi);
3482 /* and put the reference of the find */
3483 put_device(&spi->dev);
3484 break;
3487 return NOTIFY_OK;
3490 static struct notifier_block spi_of_notifier = {
3491 .notifier_call = of_spi_notify,
3493 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3494 extern struct notifier_block spi_of_notifier;
3495 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3497 #if IS_ENABLED(CONFIG_ACPI)
3498 static int spi_acpi_controller_match(struct device *dev, const void *data)
3500 return ACPI_COMPANION(dev->parent) == data;
3503 static int spi_acpi_device_match(struct device *dev, void *data)
3505 return ACPI_COMPANION(dev) == data;
3508 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
3510 struct device *dev;
3512 dev = class_find_device(&spi_master_class, NULL, adev,
3513 spi_acpi_controller_match);
3514 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3515 dev = class_find_device(&spi_slave_class, NULL, adev,
3516 spi_acpi_controller_match);
3517 if (!dev)
3518 return NULL;
3520 return container_of(dev, struct spi_controller, dev);
3523 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
3525 struct device *dev;
3527 dev = bus_find_device(&spi_bus_type, NULL, adev, spi_acpi_device_match);
3529 return dev ? to_spi_device(dev) : NULL;
3532 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
3533 void *arg)
3535 struct acpi_device *adev = arg;
3536 struct spi_controller *ctlr;
3537 struct spi_device *spi;
3539 switch (value) {
3540 case ACPI_RECONFIG_DEVICE_ADD:
3541 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
3542 if (!ctlr)
3543 break;
3545 acpi_register_spi_device(ctlr, adev);
3546 put_device(&ctlr->dev);
3547 break;
3548 case ACPI_RECONFIG_DEVICE_REMOVE:
3549 if (!acpi_device_enumerated(adev))
3550 break;
3552 spi = acpi_spi_find_device_by_adev(adev);
3553 if (!spi)
3554 break;
3556 spi_unregister_device(spi);
3557 put_device(&spi->dev);
3558 break;
3561 return NOTIFY_OK;
3564 static struct notifier_block spi_acpi_notifier = {
3565 .notifier_call = acpi_spi_notify,
3567 #else
3568 extern struct notifier_block spi_acpi_notifier;
3569 #endif
3571 static int __init spi_init(void)
3573 int status;
3575 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
3576 if (!buf) {
3577 status = -ENOMEM;
3578 goto err0;
3581 status = bus_register(&spi_bus_type);
3582 if (status < 0)
3583 goto err1;
3585 status = class_register(&spi_master_class);
3586 if (status < 0)
3587 goto err2;
3589 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
3590 status = class_register(&spi_slave_class);
3591 if (status < 0)
3592 goto err3;
3595 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
3596 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
3597 if (IS_ENABLED(CONFIG_ACPI))
3598 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
3600 return 0;
3602 err3:
3603 class_unregister(&spi_master_class);
3604 err2:
3605 bus_unregister(&spi_bus_type);
3606 err1:
3607 kfree(buf);
3608 buf = NULL;
3609 err0:
3610 return status;
3613 /* board_info is normally registered in arch_initcall(),
3614 * but even essential drivers wait till later
3616 * REVISIT only boardinfo really needs static linking. the rest (device and
3617 * driver registration) _could_ be dynamically linked (modular) ... costs
3618 * include needing to have boardinfo data structures be much more public.
3620 postcore_initcall(spi_init);