Merge branches 'topic/core', 'topic/slave' and 'fix/doc' of git://git.kernel.org...
[linux-2.6/btrfs-unstable.git] / drivers / spi / spi.c
blobc3f6b524b3ceb6c1bfd455f9423f1944faebf6d4
1 /*
2 * SPI init/core code
4 * Copyright (C) 2005 David Brownell
5 * Copyright (C) 2008 Secret Lab Technologies Ltd.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
18 #include <linux/kernel.h>
19 #include <linux/device.h>
20 #include <linux/init.h>
21 #include <linux/cache.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/dmaengine.h>
24 #include <linux/mutex.h>
25 #include <linux/of_device.h>
26 #include <linux/of_irq.h>
27 #include <linux/clk/clk-conf.h>
28 #include <linux/slab.h>
29 #include <linux/mod_devicetable.h>
30 #include <linux/spi/spi.h>
31 #include <linux/of_gpio.h>
32 #include <linux/pm_runtime.h>
33 #include <linux/pm_domain.h>
34 #include <linux/property.h>
35 #include <linux/export.h>
36 #include <linux/sched/rt.h>
37 #include <uapi/linux/sched/types.h>
38 #include <linux/delay.h>
39 #include <linux/kthread.h>
40 #include <linux/ioport.h>
41 #include <linux/acpi.h>
42 #include <linux/highmem.h>
44 #define CREATE_TRACE_POINTS
45 #include <trace/events/spi.h>
47 static void spidev_release(struct device *dev)
49 struct spi_device *spi = to_spi_device(dev);
51 /* spi masters may cleanup for released devices */
52 if (spi->master->cleanup)
53 spi->master->cleanup(spi);
55 spi_master_put(spi->master);
56 kfree(spi);
59 static ssize_t
60 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
62 const struct spi_device *spi = to_spi_device(dev);
63 int len;
65 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
66 if (len != -ENODEV)
67 return len;
69 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
71 static DEVICE_ATTR_RO(modalias);
73 #define SPI_STATISTICS_ATTRS(field, file) \
74 static ssize_t spi_master_##field##_show(struct device *dev, \
75 struct device_attribute *attr, \
76 char *buf) \
77 { \
78 struct spi_master *master = container_of(dev, \
79 struct spi_master, dev); \
80 return spi_statistics_##field##_show(&master->statistics, buf); \
81 } \
82 static struct device_attribute dev_attr_spi_master_##field = { \
83 .attr = { .name = file, .mode = 0444 }, \
84 .show = spi_master_##field##_show, \
85 }; \
86 static ssize_t spi_device_##field##_show(struct device *dev, \
87 struct device_attribute *attr, \
88 char *buf) \
89 { \
90 struct spi_device *spi = to_spi_device(dev); \
91 return spi_statistics_##field##_show(&spi->statistics, buf); \
92 } \
93 static struct device_attribute dev_attr_spi_device_##field = { \
94 .attr = { .name = file, .mode = 0444 }, \
95 .show = spi_device_##field##_show, \
98 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
99 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
100 char *buf) \
102 unsigned long flags; \
103 ssize_t len; \
104 spin_lock_irqsave(&stat->lock, flags); \
105 len = sprintf(buf, format_string, stat->field); \
106 spin_unlock_irqrestore(&stat->lock, flags); \
107 return len; \
109 SPI_STATISTICS_ATTRS(name, file)
111 #define SPI_STATISTICS_SHOW(field, format_string) \
112 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
113 field, format_string)
115 SPI_STATISTICS_SHOW(messages, "%lu");
116 SPI_STATISTICS_SHOW(transfers, "%lu");
117 SPI_STATISTICS_SHOW(errors, "%lu");
118 SPI_STATISTICS_SHOW(timedout, "%lu");
120 SPI_STATISTICS_SHOW(spi_sync, "%lu");
121 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
122 SPI_STATISTICS_SHOW(spi_async, "%lu");
124 SPI_STATISTICS_SHOW(bytes, "%llu");
125 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
126 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
128 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
129 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
130 "transfer_bytes_histo_" number, \
131 transfer_bytes_histo[index], "%lu")
132 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
133 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
134 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
135 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
136 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
137 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
138 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
139 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
140 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
141 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
142 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
143 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
144 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
145 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
146 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
147 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
148 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
150 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
152 static struct attribute *spi_dev_attrs[] = {
153 &dev_attr_modalias.attr,
154 NULL,
157 static const struct attribute_group spi_dev_group = {
158 .attrs = spi_dev_attrs,
161 static struct attribute *spi_device_statistics_attrs[] = {
162 &dev_attr_spi_device_messages.attr,
163 &dev_attr_spi_device_transfers.attr,
164 &dev_attr_spi_device_errors.attr,
165 &dev_attr_spi_device_timedout.attr,
166 &dev_attr_spi_device_spi_sync.attr,
167 &dev_attr_spi_device_spi_sync_immediate.attr,
168 &dev_attr_spi_device_spi_async.attr,
169 &dev_attr_spi_device_bytes.attr,
170 &dev_attr_spi_device_bytes_rx.attr,
171 &dev_attr_spi_device_bytes_tx.attr,
172 &dev_attr_spi_device_transfer_bytes_histo0.attr,
173 &dev_attr_spi_device_transfer_bytes_histo1.attr,
174 &dev_attr_spi_device_transfer_bytes_histo2.attr,
175 &dev_attr_spi_device_transfer_bytes_histo3.attr,
176 &dev_attr_spi_device_transfer_bytes_histo4.attr,
177 &dev_attr_spi_device_transfer_bytes_histo5.attr,
178 &dev_attr_spi_device_transfer_bytes_histo6.attr,
179 &dev_attr_spi_device_transfer_bytes_histo7.attr,
180 &dev_attr_spi_device_transfer_bytes_histo8.attr,
181 &dev_attr_spi_device_transfer_bytes_histo9.attr,
182 &dev_attr_spi_device_transfer_bytes_histo10.attr,
183 &dev_attr_spi_device_transfer_bytes_histo11.attr,
184 &dev_attr_spi_device_transfer_bytes_histo12.attr,
185 &dev_attr_spi_device_transfer_bytes_histo13.attr,
186 &dev_attr_spi_device_transfer_bytes_histo14.attr,
187 &dev_attr_spi_device_transfer_bytes_histo15.attr,
188 &dev_attr_spi_device_transfer_bytes_histo16.attr,
189 &dev_attr_spi_device_transfers_split_maxsize.attr,
190 NULL,
193 static const struct attribute_group spi_device_statistics_group = {
194 .name = "statistics",
195 .attrs = spi_device_statistics_attrs,
198 static const struct attribute_group *spi_dev_groups[] = {
199 &spi_dev_group,
200 &spi_device_statistics_group,
201 NULL,
204 static struct attribute *spi_master_statistics_attrs[] = {
205 &dev_attr_spi_master_messages.attr,
206 &dev_attr_spi_master_transfers.attr,
207 &dev_attr_spi_master_errors.attr,
208 &dev_attr_spi_master_timedout.attr,
209 &dev_attr_spi_master_spi_sync.attr,
210 &dev_attr_spi_master_spi_sync_immediate.attr,
211 &dev_attr_spi_master_spi_async.attr,
212 &dev_attr_spi_master_bytes.attr,
213 &dev_attr_spi_master_bytes_rx.attr,
214 &dev_attr_spi_master_bytes_tx.attr,
215 &dev_attr_spi_master_transfer_bytes_histo0.attr,
216 &dev_attr_spi_master_transfer_bytes_histo1.attr,
217 &dev_attr_spi_master_transfer_bytes_histo2.attr,
218 &dev_attr_spi_master_transfer_bytes_histo3.attr,
219 &dev_attr_spi_master_transfer_bytes_histo4.attr,
220 &dev_attr_spi_master_transfer_bytes_histo5.attr,
221 &dev_attr_spi_master_transfer_bytes_histo6.attr,
222 &dev_attr_spi_master_transfer_bytes_histo7.attr,
223 &dev_attr_spi_master_transfer_bytes_histo8.attr,
224 &dev_attr_spi_master_transfer_bytes_histo9.attr,
225 &dev_attr_spi_master_transfer_bytes_histo10.attr,
226 &dev_attr_spi_master_transfer_bytes_histo11.attr,
227 &dev_attr_spi_master_transfer_bytes_histo12.attr,
228 &dev_attr_spi_master_transfer_bytes_histo13.attr,
229 &dev_attr_spi_master_transfer_bytes_histo14.attr,
230 &dev_attr_spi_master_transfer_bytes_histo15.attr,
231 &dev_attr_spi_master_transfer_bytes_histo16.attr,
232 &dev_attr_spi_master_transfers_split_maxsize.attr,
233 NULL,
236 static const struct attribute_group spi_master_statistics_group = {
237 .name = "statistics",
238 .attrs = spi_master_statistics_attrs,
241 static const struct attribute_group *spi_master_groups[] = {
242 &spi_master_statistics_group,
243 NULL,
246 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
247 struct spi_transfer *xfer,
248 struct spi_master *master)
250 unsigned long flags;
251 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
253 if (l2len < 0)
254 l2len = 0;
256 spin_lock_irqsave(&stats->lock, flags);
258 stats->transfers++;
259 stats->transfer_bytes_histo[l2len]++;
261 stats->bytes += xfer->len;
262 if ((xfer->tx_buf) &&
263 (xfer->tx_buf != master->dummy_tx))
264 stats->bytes_tx += xfer->len;
265 if ((xfer->rx_buf) &&
266 (xfer->rx_buf != master->dummy_rx))
267 stats->bytes_rx += xfer->len;
269 spin_unlock_irqrestore(&stats->lock, flags);
271 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
273 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
274 * and the sysfs version makes coldplug work too.
277 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
278 const struct spi_device *sdev)
280 while (id->name[0]) {
281 if (!strcmp(sdev->modalias, id->name))
282 return id;
283 id++;
285 return NULL;
288 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
290 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
292 return spi_match_id(sdrv->id_table, sdev);
294 EXPORT_SYMBOL_GPL(spi_get_device_id);
296 static int spi_match_device(struct device *dev, struct device_driver *drv)
298 const struct spi_device *spi = to_spi_device(dev);
299 const struct spi_driver *sdrv = to_spi_driver(drv);
301 /* Attempt an OF style match */
302 if (of_driver_match_device(dev, drv))
303 return 1;
305 /* Then try ACPI */
306 if (acpi_driver_match_device(dev, drv))
307 return 1;
309 if (sdrv->id_table)
310 return !!spi_match_id(sdrv->id_table, spi);
312 return strcmp(spi->modalias, drv->name) == 0;
315 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
317 const struct spi_device *spi = to_spi_device(dev);
318 int rc;
320 rc = acpi_device_uevent_modalias(dev, env);
321 if (rc != -ENODEV)
322 return rc;
324 add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
325 return 0;
328 struct bus_type spi_bus_type = {
329 .name = "spi",
330 .dev_groups = spi_dev_groups,
331 .match = spi_match_device,
332 .uevent = spi_uevent,
334 EXPORT_SYMBOL_GPL(spi_bus_type);
337 static int spi_drv_probe(struct device *dev)
339 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
340 struct spi_device *spi = to_spi_device(dev);
341 int ret;
343 ret = of_clk_set_defaults(dev->of_node, false);
344 if (ret)
345 return ret;
347 if (dev->of_node) {
348 spi->irq = of_irq_get(dev->of_node, 0);
349 if (spi->irq == -EPROBE_DEFER)
350 return -EPROBE_DEFER;
351 if (spi->irq < 0)
352 spi->irq = 0;
355 ret = dev_pm_domain_attach(dev, true);
356 if (ret != -EPROBE_DEFER) {
357 ret = sdrv->probe(spi);
358 if (ret)
359 dev_pm_domain_detach(dev, true);
362 return ret;
365 static int spi_drv_remove(struct device *dev)
367 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
368 int ret;
370 ret = sdrv->remove(to_spi_device(dev));
371 dev_pm_domain_detach(dev, true);
373 return ret;
376 static void spi_drv_shutdown(struct device *dev)
378 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
380 sdrv->shutdown(to_spi_device(dev));
384 * __spi_register_driver - register a SPI driver
385 * @owner: owner module of the driver to register
386 * @sdrv: the driver to register
387 * Context: can sleep
389 * Return: zero on success, else a negative error code.
391 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
393 sdrv->driver.owner = owner;
394 sdrv->driver.bus = &spi_bus_type;
395 if (sdrv->probe)
396 sdrv->driver.probe = spi_drv_probe;
397 if (sdrv->remove)
398 sdrv->driver.remove = spi_drv_remove;
399 if (sdrv->shutdown)
400 sdrv->driver.shutdown = spi_drv_shutdown;
401 return driver_register(&sdrv->driver);
403 EXPORT_SYMBOL_GPL(__spi_register_driver);
405 /*-------------------------------------------------------------------------*/
407 /* SPI devices should normally not be created by SPI device drivers; that
408 * would make them board-specific. Similarly with SPI master drivers.
409 * Device registration normally goes into like arch/.../mach.../board-YYY.c
410 * with other readonly (flashable) information about mainboard devices.
413 struct boardinfo {
414 struct list_head list;
415 struct spi_board_info board_info;
418 static LIST_HEAD(board_list);
419 static LIST_HEAD(spi_master_list);
422 * Used to protect add/del opertion for board_info list and
423 * spi_master list, and their matching process
425 static DEFINE_MUTEX(board_lock);
428 * spi_alloc_device - Allocate a new SPI device
429 * @master: Controller to which device is connected
430 * Context: can sleep
432 * Allows a driver to allocate and initialize a spi_device without
433 * registering it immediately. This allows a driver to directly
434 * fill the spi_device with device parameters before calling
435 * spi_add_device() on it.
437 * Caller is responsible to call spi_add_device() on the returned
438 * spi_device structure to add it to the SPI master. If the caller
439 * needs to discard the spi_device without adding it, then it should
440 * call spi_dev_put() on it.
442 * Return: a pointer to the new device, or NULL.
444 struct spi_device *spi_alloc_device(struct spi_master *master)
446 struct spi_device *spi;
448 if (!spi_master_get(master))
449 return NULL;
451 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
452 if (!spi) {
453 spi_master_put(master);
454 return NULL;
457 spi->master = master;
458 spi->dev.parent = &master->dev;
459 spi->dev.bus = &spi_bus_type;
460 spi->dev.release = spidev_release;
461 spi->cs_gpio = -ENOENT;
463 spin_lock_init(&spi->statistics.lock);
465 device_initialize(&spi->dev);
466 return spi;
468 EXPORT_SYMBOL_GPL(spi_alloc_device);
470 static void spi_dev_set_name(struct spi_device *spi)
472 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
474 if (adev) {
475 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
476 return;
479 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->master->dev),
480 spi->chip_select);
483 static int spi_dev_check(struct device *dev, void *data)
485 struct spi_device *spi = to_spi_device(dev);
486 struct spi_device *new_spi = data;
488 if (spi->master == new_spi->master &&
489 spi->chip_select == new_spi->chip_select)
490 return -EBUSY;
491 return 0;
495 * spi_add_device - Add spi_device allocated with spi_alloc_device
496 * @spi: spi_device to register
498 * Companion function to spi_alloc_device. Devices allocated with
499 * spi_alloc_device can be added onto the spi bus with this function.
501 * Return: 0 on success; negative errno on failure
503 int spi_add_device(struct spi_device *spi)
505 static DEFINE_MUTEX(spi_add_lock);
506 struct spi_master *master = spi->master;
507 struct device *dev = master->dev.parent;
508 int status;
510 /* Chipselects are numbered 0..max; validate. */
511 if (spi->chip_select >= master->num_chipselect) {
512 dev_err(dev, "cs%d >= max %d\n",
513 spi->chip_select,
514 master->num_chipselect);
515 return -EINVAL;
518 /* Set the bus ID string */
519 spi_dev_set_name(spi);
521 /* We need to make sure there's no other device with this
522 * chipselect **BEFORE** we call setup(), else we'll trash
523 * its configuration. Lock against concurrent add() calls.
525 mutex_lock(&spi_add_lock);
527 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
528 if (status) {
529 dev_err(dev, "chipselect %d already in use\n",
530 spi->chip_select);
531 goto done;
534 if (master->cs_gpios)
535 spi->cs_gpio = master->cs_gpios[spi->chip_select];
537 /* Drivers may modify this initial i/o setup, but will
538 * normally rely on the device being setup. Devices
539 * using SPI_CS_HIGH can't coexist well otherwise...
541 status = spi_setup(spi);
542 if (status < 0) {
543 dev_err(dev, "can't setup %s, status %d\n",
544 dev_name(&spi->dev), status);
545 goto done;
548 /* Device may be bound to an active driver when this returns */
549 status = device_add(&spi->dev);
550 if (status < 0)
551 dev_err(dev, "can't add %s, status %d\n",
552 dev_name(&spi->dev), status);
553 else
554 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
556 done:
557 mutex_unlock(&spi_add_lock);
558 return status;
560 EXPORT_SYMBOL_GPL(spi_add_device);
563 * spi_new_device - instantiate one new SPI device
564 * @master: Controller to which device is connected
565 * @chip: Describes the SPI device
566 * Context: can sleep
568 * On typical mainboards, this is purely internal; and it's not needed
569 * after board init creates the hard-wired devices. Some development
570 * platforms may not be able to use spi_register_board_info though, and
571 * this is exported so that for example a USB or parport based adapter
572 * driver could add devices (which it would learn about out-of-band).
574 * Return: the new device, or NULL.
576 struct spi_device *spi_new_device(struct spi_master *master,
577 struct spi_board_info *chip)
579 struct spi_device *proxy;
580 int status;
582 /* NOTE: caller did any chip->bus_num checks necessary.
584 * Also, unless we change the return value convention to use
585 * error-or-pointer (not NULL-or-pointer), troubleshootability
586 * suggests syslogged diagnostics are best here (ugh).
589 proxy = spi_alloc_device(master);
590 if (!proxy)
591 return NULL;
593 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
595 proxy->chip_select = chip->chip_select;
596 proxy->max_speed_hz = chip->max_speed_hz;
597 proxy->mode = chip->mode;
598 proxy->irq = chip->irq;
599 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
600 proxy->dev.platform_data = (void *) chip->platform_data;
601 proxy->controller_data = chip->controller_data;
602 proxy->controller_state = NULL;
604 if (chip->properties) {
605 status = device_add_properties(&proxy->dev, chip->properties);
606 if (status) {
607 dev_err(&master->dev,
608 "failed to add properties to '%s': %d\n",
609 chip->modalias, status);
610 goto err_dev_put;
614 status = spi_add_device(proxy);
615 if (status < 0)
616 goto err_remove_props;
618 return proxy;
620 err_remove_props:
621 if (chip->properties)
622 device_remove_properties(&proxy->dev);
623 err_dev_put:
624 spi_dev_put(proxy);
625 return NULL;
627 EXPORT_SYMBOL_GPL(spi_new_device);
630 * spi_unregister_device - unregister a single SPI device
631 * @spi: spi_device to unregister
633 * Start making the passed SPI device vanish. Normally this would be handled
634 * by spi_unregister_master().
636 void spi_unregister_device(struct spi_device *spi)
638 if (!spi)
639 return;
641 if (spi->dev.of_node) {
642 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
643 of_node_put(spi->dev.of_node);
645 if (ACPI_COMPANION(&spi->dev))
646 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
647 device_unregister(&spi->dev);
649 EXPORT_SYMBOL_GPL(spi_unregister_device);
651 static void spi_match_master_to_boardinfo(struct spi_master *master,
652 struct spi_board_info *bi)
654 struct spi_device *dev;
656 if (master->bus_num != bi->bus_num)
657 return;
659 dev = spi_new_device(master, bi);
660 if (!dev)
661 dev_err(master->dev.parent, "can't create new device for %s\n",
662 bi->modalias);
666 * spi_register_board_info - register SPI devices for a given board
667 * @info: array of chip descriptors
668 * @n: how many descriptors are provided
669 * Context: can sleep
671 * Board-specific early init code calls this (probably during arch_initcall)
672 * with segments of the SPI device table. Any device nodes are created later,
673 * after the relevant parent SPI controller (bus_num) is defined. We keep
674 * this table of devices forever, so that reloading a controller driver will
675 * not make Linux forget about these hard-wired devices.
677 * Other code can also call this, e.g. a particular add-on board might provide
678 * SPI devices through its expansion connector, so code initializing that board
679 * would naturally declare its SPI devices.
681 * The board info passed can safely be __initdata ... but be careful of
682 * any embedded pointers (platform_data, etc), they're copied as-is.
683 * Device properties are deep-copied though.
685 * Return: zero on success, else a negative error code.
687 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
689 struct boardinfo *bi;
690 int i;
692 if (!n)
693 return 0;
695 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
696 if (!bi)
697 return -ENOMEM;
699 for (i = 0; i < n; i++, bi++, info++) {
700 struct spi_master *master;
702 memcpy(&bi->board_info, info, sizeof(*info));
703 if (info->properties) {
704 bi->board_info.properties =
705 property_entries_dup(info->properties);
706 if (IS_ERR(bi->board_info.properties))
707 return PTR_ERR(bi->board_info.properties);
710 mutex_lock(&board_lock);
711 list_add_tail(&bi->list, &board_list);
712 list_for_each_entry(master, &spi_master_list, list)
713 spi_match_master_to_boardinfo(master, &bi->board_info);
714 mutex_unlock(&board_lock);
717 return 0;
720 /*-------------------------------------------------------------------------*/
722 static void spi_set_cs(struct spi_device *spi, bool enable)
724 if (spi->mode & SPI_CS_HIGH)
725 enable = !enable;
727 if (gpio_is_valid(spi->cs_gpio)) {
728 gpio_set_value(spi->cs_gpio, !enable);
729 /* Some SPI masters need both GPIO CS & slave_select */
730 if ((spi->master->flags & SPI_MASTER_GPIO_SS) &&
731 spi->master->set_cs)
732 spi->master->set_cs(spi, !enable);
733 } else if (spi->master->set_cs) {
734 spi->master->set_cs(spi, !enable);
738 #ifdef CONFIG_HAS_DMA
739 static int spi_map_buf(struct spi_master *master, struct device *dev,
740 struct sg_table *sgt, void *buf, size_t len,
741 enum dma_data_direction dir)
743 const bool vmalloced_buf = is_vmalloc_addr(buf);
744 unsigned int max_seg_size = dma_get_max_seg_size(dev);
745 #ifdef CONFIG_HIGHMEM
746 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
747 (unsigned long)buf < (PKMAP_BASE +
748 (LAST_PKMAP * PAGE_SIZE)));
749 #else
750 const bool kmap_buf = false;
751 #endif
752 int desc_len;
753 int sgs;
754 struct page *vm_page;
755 struct scatterlist *sg;
756 void *sg_buf;
757 size_t min;
758 int i, ret;
760 if (vmalloced_buf || kmap_buf) {
761 desc_len = min_t(int, max_seg_size, PAGE_SIZE);
762 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
763 } else if (virt_addr_valid(buf)) {
764 desc_len = min_t(int, max_seg_size, master->max_dma_len);
765 sgs = DIV_ROUND_UP(len, desc_len);
766 } else {
767 return -EINVAL;
770 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
771 if (ret != 0)
772 return ret;
774 sg = &sgt->sgl[0];
775 for (i = 0; i < sgs; i++) {
777 if (vmalloced_buf || kmap_buf) {
778 min = min_t(size_t,
779 len, desc_len - offset_in_page(buf));
780 if (vmalloced_buf)
781 vm_page = vmalloc_to_page(buf);
782 else
783 vm_page = kmap_to_page(buf);
784 if (!vm_page) {
785 sg_free_table(sgt);
786 return -ENOMEM;
788 sg_set_page(sg, vm_page,
789 min, offset_in_page(buf));
790 } else {
791 min = min_t(size_t, len, desc_len);
792 sg_buf = buf;
793 sg_set_buf(sg, sg_buf, min);
796 buf += min;
797 len -= min;
798 sg = sg_next(sg);
801 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
802 if (!ret)
803 ret = -ENOMEM;
804 if (ret < 0) {
805 sg_free_table(sgt);
806 return ret;
809 sgt->nents = ret;
811 return 0;
814 static void spi_unmap_buf(struct spi_master *master, struct device *dev,
815 struct sg_table *sgt, enum dma_data_direction dir)
817 if (sgt->orig_nents) {
818 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
819 sg_free_table(sgt);
823 static int __spi_map_msg(struct spi_master *master, struct spi_message *msg)
825 struct device *tx_dev, *rx_dev;
826 struct spi_transfer *xfer;
827 int ret;
829 if (!master->can_dma)
830 return 0;
832 if (master->dma_tx)
833 tx_dev = master->dma_tx->device->dev;
834 else
835 tx_dev = master->dev.parent;
837 if (master->dma_rx)
838 rx_dev = master->dma_rx->device->dev;
839 else
840 rx_dev = master->dev.parent;
842 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
843 if (!master->can_dma(master, msg->spi, xfer))
844 continue;
846 if (xfer->tx_buf != NULL) {
847 ret = spi_map_buf(master, tx_dev, &xfer->tx_sg,
848 (void *)xfer->tx_buf, xfer->len,
849 DMA_TO_DEVICE);
850 if (ret != 0)
851 return ret;
854 if (xfer->rx_buf != NULL) {
855 ret = spi_map_buf(master, rx_dev, &xfer->rx_sg,
856 xfer->rx_buf, xfer->len,
857 DMA_FROM_DEVICE);
858 if (ret != 0) {
859 spi_unmap_buf(master, tx_dev, &xfer->tx_sg,
860 DMA_TO_DEVICE);
861 return ret;
866 master->cur_msg_mapped = true;
868 return 0;
871 static int __spi_unmap_msg(struct spi_master *master, struct spi_message *msg)
873 struct spi_transfer *xfer;
874 struct device *tx_dev, *rx_dev;
876 if (!master->cur_msg_mapped || !master->can_dma)
877 return 0;
879 if (master->dma_tx)
880 tx_dev = master->dma_tx->device->dev;
881 else
882 tx_dev = master->dev.parent;
884 if (master->dma_rx)
885 rx_dev = master->dma_rx->device->dev;
886 else
887 rx_dev = master->dev.parent;
889 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
890 if (!master->can_dma(master, msg->spi, xfer))
891 continue;
893 spi_unmap_buf(master, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
894 spi_unmap_buf(master, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
897 return 0;
899 #else /* !CONFIG_HAS_DMA */
900 static inline int spi_map_buf(struct spi_master *master,
901 struct device *dev, struct sg_table *sgt,
902 void *buf, size_t len,
903 enum dma_data_direction dir)
905 return -EINVAL;
908 static inline void spi_unmap_buf(struct spi_master *master,
909 struct device *dev, struct sg_table *sgt,
910 enum dma_data_direction dir)
914 static inline int __spi_map_msg(struct spi_master *master,
915 struct spi_message *msg)
917 return 0;
920 static inline int __spi_unmap_msg(struct spi_master *master,
921 struct spi_message *msg)
923 return 0;
925 #endif /* !CONFIG_HAS_DMA */
927 static inline int spi_unmap_msg(struct spi_master *master,
928 struct spi_message *msg)
930 struct spi_transfer *xfer;
932 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
934 * Restore the original value of tx_buf or rx_buf if they are
935 * NULL.
937 if (xfer->tx_buf == master->dummy_tx)
938 xfer->tx_buf = NULL;
939 if (xfer->rx_buf == master->dummy_rx)
940 xfer->rx_buf = NULL;
943 return __spi_unmap_msg(master, msg);
946 static int spi_map_msg(struct spi_master *master, struct spi_message *msg)
948 struct spi_transfer *xfer;
949 void *tmp;
950 unsigned int max_tx, max_rx;
952 if (master->flags & (SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX)) {
953 max_tx = 0;
954 max_rx = 0;
956 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
957 if ((master->flags & SPI_MASTER_MUST_TX) &&
958 !xfer->tx_buf)
959 max_tx = max(xfer->len, max_tx);
960 if ((master->flags & SPI_MASTER_MUST_RX) &&
961 !xfer->rx_buf)
962 max_rx = max(xfer->len, max_rx);
965 if (max_tx) {
966 tmp = krealloc(master->dummy_tx, max_tx,
967 GFP_KERNEL | GFP_DMA);
968 if (!tmp)
969 return -ENOMEM;
970 master->dummy_tx = tmp;
971 memset(tmp, 0, max_tx);
974 if (max_rx) {
975 tmp = krealloc(master->dummy_rx, max_rx,
976 GFP_KERNEL | GFP_DMA);
977 if (!tmp)
978 return -ENOMEM;
979 master->dummy_rx = tmp;
982 if (max_tx || max_rx) {
983 list_for_each_entry(xfer, &msg->transfers,
984 transfer_list) {
985 if (!xfer->tx_buf)
986 xfer->tx_buf = master->dummy_tx;
987 if (!xfer->rx_buf)
988 xfer->rx_buf = master->dummy_rx;
993 return __spi_map_msg(master, msg);
997 * spi_transfer_one_message - Default implementation of transfer_one_message()
999 * This is a standard implementation of transfer_one_message() for
1000 * drivers which implement a transfer_one() operation. It provides
1001 * standard handling of delays and chip select management.
1003 static int spi_transfer_one_message(struct spi_master *master,
1004 struct spi_message *msg)
1006 struct spi_transfer *xfer;
1007 bool keep_cs = false;
1008 int ret = 0;
1009 unsigned long long ms = 1;
1010 struct spi_statistics *statm = &master->statistics;
1011 struct spi_statistics *stats = &msg->spi->statistics;
1013 spi_set_cs(msg->spi, true);
1015 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1016 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1018 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1019 trace_spi_transfer_start(msg, xfer);
1021 spi_statistics_add_transfer_stats(statm, xfer, master);
1022 spi_statistics_add_transfer_stats(stats, xfer, master);
1024 if (xfer->tx_buf || xfer->rx_buf) {
1025 reinit_completion(&master->xfer_completion);
1027 ret = master->transfer_one(master, msg->spi, xfer);
1028 if (ret < 0) {
1029 SPI_STATISTICS_INCREMENT_FIELD(statm,
1030 errors);
1031 SPI_STATISTICS_INCREMENT_FIELD(stats,
1032 errors);
1033 dev_err(&msg->spi->dev,
1034 "SPI transfer failed: %d\n", ret);
1035 goto out;
1038 if (ret > 0) {
1039 ret = 0;
1040 ms = 8LL * 1000LL * xfer->len;
1041 do_div(ms, xfer->speed_hz);
1042 ms += ms + 200; /* some tolerance */
1044 if (ms > UINT_MAX)
1045 ms = UINT_MAX;
1047 ms = wait_for_completion_timeout(&master->xfer_completion,
1048 msecs_to_jiffies(ms));
1051 if (ms == 0) {
1052 SPI_STATISTICS_INCREMENT_FIELD(statm,
1053 timedout);
1054 SPI_STATISTICS_INCREMENT_FIELD(stats,
1055 timedout);
1056 dev_err(&msg->spi->dev,
1057 "SPI transfer timed out\n");
1058 msg->status = -ETIMEDOUT;
1060 } else {
1061 if (xfer->len)
1062 dev_err(&msg->spi->dev,
1063 "Bufferless transfer has length %u\n",
1064 xfer->len);
1067 trace_spi_transfer_stop(msg, xfer);
1069 if (msg->status != -EINPROGRESS)
1070 goto out;
1072 if (xfer->delay_usecs) {
1073 u16 us = xfer->delay_usecs;
1075 if (us <= 10)
1076 udelay(us);
1077 else
1078 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1081 if (xfer->cs_change) {
1082 if (list_is_last(&xfer->transfer_list,
1083 &msg->transfers)) {
1084 keep_cs = true;
1085 } else {
1086 spi_set_cs(msg->spi, false);
1087 udelay(10);
1088 spi_set_cs(msg->spi, true);
1092 msg->actual_length += xfer->len;
1095 out:
1096 if (ret != 0 || !keep_cs)
1097 spi_set_cs(msg->spi, false);
1099 if (msg->status == -EINPROGRESS)
1100 msg->status = ret;
1102 if (msg->status && master->handle_err)
1103 master->handle_err(master, msg);
1105 spi_res_release(master, msg);
1107 spi_finalize_current_message(master);
1109 return ret;
1113 * spi_finalize_current_transfer - report completion of a transfer
1114 * @master: the master reporting completion
1116 * Called by SPI drivers using the core transfer_one_message()
1117 * implementation to notify it that the current interrupt driven
1118 * transfer has finished and the next one may be scheduled.
1120 void spi_finalize_current_transfer(struct spi_master *master)
1122 complete(&master->xfer_completion);
1124 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1127 * __spi_pump_messages - function which processes spi message queue
1128 * @master: master to process queue for
1129 * @in_kthread: true if we are in the context of the message pump thread
1131 * This function checks if there is any spi message in the queue that
1132 * needs processing and if so call out to the driver to initialize hardware
1133 * and transfer each message.
1135 * Note that it is called both from the kthread itself and also from
1136 * inside spi_sync(); the queue extraction handling at the top of the
1137 * function should deal with this safely.
1139 static void __spi_pump_messages(struct spi_master *master, bool in_kthread)
1141 unsigned long flags;
1142 bool was_busy = false;
1143 int ret;
1145 /* Lock queue */
1146 spin_lock_irqsave(&master->queue_lock, flags);
1148 /* Make sure we are not already running a message */
1149 if (master->cur_msg) {
1150 spin_unlock_irqrestore(&master->queue_lock, flags);
1151 return;
1154 /* If another context is idling the device then defer */
1155 if (master->idling) {
1156 kthread_queue_work(&master->kworker, &master->pump_messages);
1157 spin_unlock_irqrestore(&master->queue_lock, flags);
1158 return;
1161 /* Check if the queue is idle */
1162 if (list_empty(&master->queue) || !master->running) {
1163 if (!master->busy) {
1164 spin_unlock_irqrestore(&master->queue_lock, flags);
1165 return;
1168 /* Only do teardown in the thread */
1169 if (!in_kthread) {
1170 kthread_queue_work(&master->kworker,
1171 &master->pump_messages);
1172 spin_unlock_irqrestore(&master->queue_lock, flags);
1173 return;
1176 master->busy = false;
1177 master->idling = true;
1178 spin_unlock_irqrestore(&master->queue_lock, flags);
1180 kfree(master->dummy_rx);
1181 master->dummy_rx = NULL;
1182 kfree(master->dummy_tx);
1183 master->dummy_tx = NULL;
1184 if (master->unprepare_transfer_hardware &&
1185 master->unprepare_transfer_hardware(master))
1186 dev_err(&master->dev,
1187 "failed to unprepare transfer hardware\n");
1188 if (master->auto_runtime_pm) {
1189 pm_runtime_mark_last_busy(master->dev.parent);
1190 pm_runtime_put_autosuspend(master->dev.parent);
1192 trace_spi_master_idle(master);
1194 spin_lock_irqsave(&master->queue_lock, flags);
1195 master->idling = false;
1196 spin_unlock_irqrestore(&master->queue_lock, flags);
1197 return;
1200 /* Extract head of queue */
1201 master->cur_msg =
1202 list_first_entry(&master->queue, struct spi_message, queue);
1204 list_del_init(&master->cur_msg->queue);
1205 if (master->busy)
1206 was_busy = true;
1207 else
1208 master->busy = true;
1209 spin_unlock_irqrestore(&master->queue_lock, flags);
1211 mutex_lock(&master->io_mutex);
1213 if (!was_busy && master->auto_runtime_pm) {
1214 ret = pm_runtime_get_sync(master->dev.parent);
1215 if (ret < 0) {
1216 dev_err(&master->dev, "Failed to power device: %d\n",
1217 ret);
1218 mutex_unlock(&master->io_mutex);
1219 return;
1223 if (!was_busy)
1224 trace_spi_master_busy(master);
1226 if (!was_busy && master->prepare_transfer_hardware) {
1227 ret = master->prepare_transfer_hardware(master);
1228 if (ret) {
1229 dev_err(&master->dev,
1230 "failed to prepare transfer hardware\n");
1232 if (master->auto_runtime_pm)
1233 pm_runtime_put(master->dev.parent);
1234 mutex_unlock(&master->io_mutex);
1235 return;
1239 trace_spi_message_start(master->cur_msg);
1241 if (master->prepare_message) {
1242 ret = master->prepare_message(master, master->cur_msg);
1243 if (ret) {
1244 dev_err(&master->dev,
1245 "failed to prepare message: %d\n", ret);
1246 master->cur_msg->status = ret;
1247 spi_finalize_current_message(master);
1248 goto out;
1250 master->cur_msg_prepared = true;
1253 ret = spi_map_msg(master, master->cur_msg);
1254 if (ret) {
1255 master->cur_msg->status = ret;
1256 spi_finalize_current_message(master);
1257 goto out;
1260 ret = master->transfer_one_message(master, master->cur_msg);
1261 if (ret) {
1262 dev_err(&master->dev,
1263 "failed to transfer one message from queue\n");
1264 goto out;
1267 out:
1268 mutex_unlock(&master->io_mutex);
1270 /* Prod the scheduler in case transfer_one() was busy waiting */
1271 if (!ret)
1272 cond_resched();
1276 * spi_pump_messages - kthread work function which processes spi message queue
1277 * @work: pointer to kthread work struct contained in the master struct
1279 static void spi_pump_messages(struct kthread_work *work)
1281 struct spi_master *master =
1282 container_of(work, struct spi_master, pump_messages);
1284 __spi_pump_messages(master, true);
1287 static int spi_init_queue(struct spi_master *master)
1289 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1291 master->running = false;
1292 master->busy = false;
1294 kthread_init_worker(&master->kworker);
1295 master->kworker_task = kthread_run(kthread_worker_fn,
1296 &master->kworker, "%s",
1297 dev_name(&master->dev));
1298 if (IS_ERR(master->kworker_task)) {
1299 dev_err(&master->dev, "failed to create message pump task\n");
1300 return PTR_ERR(master->kworker_task);
1302 kthread_init_work(&master->pump_messages, spi_pump_messages);
1305 * Master config will indicate if this controller should run the
1306 * message pump with high (realtime) priority to reduce the transfer
1307 * latency on the bus by minimising the delay between a transfer
1308 * request and the scheduling of the message pump thread. Without this
1309 * setting the message pump thread will remain at default priority.
1311 if (master->rt) {
1312 dev_info(&master->dev,
1313 "will run message pump with realtime priority\n");
1314 sched_setscheduler(master->kworker_task, SCHED_FIFO, &param);
1317 return 0;
1321 * spi_get_next_queued_message() - called by driver to check for queued
1322 * messages
1323 * @master: the master to check for queued messages
1325 * If there are more messages in the queue, the next message is returned from
1326 * this call.
1328 * Return: the next message in the queue, else NULL if the queue is empty.
1330 struct spi_message *spi_get_next_queued_message(struct spi_master *master)
1332 struct spi_message *next;
1333 unsigned long flags;
1335 /* get a pointer to the next message, if any */
1336 spin_lock_irqsave(&master->queue_lock, flags);
1337 next = list_first_entry_or_null(&master->queue, struct spi_message,
1338 queue);
1339 spin_unlock_irqrestore(&master->queue_lock, flags);
1341 return next;
1343 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1346 * spi_finalize_current_message() - the current message is complete
1347 * @master: the master to return the message to
1349 * Called by the driver to notify the core that the message in the front of the
1350 * queue is complete and can be removed from the queue.
1352 void spi_finalize_current_message(struct spi_master *master)
1354 struct spi_message *mesg;
1355 unsigned long flags;
1356 int ret;
1358 spin_lock_irqsave(&master->queue_lock, flags);
1359 mesg = master->cur_msg;
1360 spin_unlock_irqrestore(&master->queue_lock, flags);
1362 spi_unmap_msg(master, mesg);
1364 if (master->cur_msg_prepared && master->unprepare_message) {
1365 ret = master->unprepare_message(master, mesg);
1366 if (ret) {
1367 dev_err(&master->dev,
1368 "failed to unprepare message: %d\n", ret);
1372 spin_lock_irqsave(&master->queue_lock, flags);
1373 master->cur_msg = NULL;
1374 master->cur_msg_prepared = false;
1375 kthread_queue_work(&master->kworker, &master->pump_messages);
1376 spin_unlock_irqrestore(&master->queue_lock, flags);
1378 trace_spi_message_done(mesg);
1380 mesg->state = NULL;
1381 if (mesg->complete)
1382 mesg->complete(mesg->context);
1384 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1386 static int spi_start_queue(struct spi_master *master)
1388 unsigned long flags;
1390 spin_lock_irqsave(&master->queue_lock, flags);
1392 if (master->running || master->busy) {
1393 spin_unlock_irqrestore(&master->queue_lock, flags);
1394 return -EBUSY;
1397 master->running = true;
1398 master->cur_msg = NULL;
1399 spin_unlock_irqrestore(&master->queue_lock, flags);
1401 kthread_queue_work(&master->kworker, &master->pump_messages);
1403 return 0;
1406 static int spi_stop_queue(struct spi_master *master)
1408 unsigned long flags;
1409 unsigned limit = 500;
1410 int ret = 0;
1412 spin_lock_irqsave(&master->queue_lock, flags);
1415 * This is a bit lame, but is optimized for the common execution path.
1416 * A wait_queue on the master->busy could be used, but then the common
1417 * execution path (pump_messages) would be required to call wake_up or
1418 * friends on every SPI message. Do this instead.
1420 while ((!list_empty(&master->queue) || master->busy) && limit--) {
1421 spin_unlock_irqrestore(&master->queue_lock, flags);
1422 usleep_range(10000, 11000);
1423 spin_lock_irqsave(&master->queue_lock, flags);
1426 if (!list_empty(&master->queue) || master->busy)
1427 ret = -EBUSY;
1428 else
1429 master->running = false;
1431 spin_unlock_irqrestore(&master->queue_lock, flags);
1433 if (ret) {
1434 dev_warn(&master->dev,
1435 "could not stop message queue\n");
1436 return ret;
1438 return ret;
1441 static int spi_destroy_queue(struct spi_master *master)
1443 int ret;
1445 ret = spi_stop_queue(master);
1448 * kthread_flush_worker will block until all work is done.
1449 * If the reason that stop_queue timed out is that the work will never
1450 * finish, then it does no good to call flush/stop thread, so
1451 * return anyway.
1453 if (ret) {
1454 dev_err(&master->dev, "problem destroying queue\n");
1455 return ret;
1458 kthread_flush_worker(&master->kworker);
1459 kthread_stop(master->kworker_task);
1461 return 0;
1464 static int __spi_queued_transfer(struct spi_device *spi,
1465 struct spi_message *msg,
1466 bool need_pump)
1468 struct spi_master *master = spi->master;
1469 unsigned long flags;
1471 spin_lock_irqsave(&master->queue_lock, flags);
1473 if (!master->running) {
1474 spin_unlock_irqrestore(&master->queue_lock, flags);
1475 return -ESHUTDOWN;
1477 msg->actual_length = 0;
1478 msg->status = -EINPROGRESS;
1480 list_add_tail(&msg->queue, &master->queue);
1481 if (!master->busy && need_pump)
1482 kthread_queue_work(&master->kworker, &master->pump_messages);
1484 spin_unlock_irqrestore(&master->queue_lock, flags);
1485 return 0;
1489 * spi_queued_transfer - transfer function for queued transfers
1490 * @spi: spi device which is requesting transfer
1491 * @msg: spi message which is to handled is queued to driver queue
1493 * Return: zero on success, else a negative error code.
1495 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1497 return __spi_queued_transfer(spi, msg, true);
1500 static int spi_master_initialize_queue(struct spi_master *master)
1502 int ret;
1504 master->transfer = spi_queued_transfer;
1505 if (!master->transfer_one_message)
1506 master->transfer_one_message = spi_transfer_one_message;
1508 /* Initialize and start queue */
1509 ret = spi_init_queue(master);
1510 if (ret) {
1511 dev_err(&master->dev, "problem initializing queue\n");
1512 goto err_init_queue;
1514 master->queued = true;
1515 ret = spi_start_queue(master);
1516 if (ret) {
1517 dev_err(&master->dev, "problem starting queue\n");
1518 goto err_start_queue;
1521 return 0;
1523 err_start_queue:
1524 spi_destroy_queue(master);
1525 err_init_queue:
1526 return ret;
1529 /*-------------------------------------------------------------------------*/
1531 #if defined(CONFIG_OF)
1532 static int of_spi_parse_dt(struct spi_master *master, struct spi_device *spi,
1533 struct device_node *nc)
1535 u32 value;
1536 int rc;
1538 /* Mode (clock phase/polarity/etc.) */
1539 if (of_find_property(nc, "spi-cpha", NULL))
1540 spi->mode |= SPI_CPHA;
1541 if (of_find_property(nc, "spi-cpol", NULL))
1542 spi->mode |= SPI_CPOL;
1543 if (of_find_property(nc, "spi-cs-high", NULL))
1544 spi->mode |= SPI_CS_HIGH;
1545 if (of_find_property(nc, "spi-3wire", NULL))
1546 spi->mode |= SPI_3WIRE;
1547 if (of_find_property(nc, "spi-lsb-first", NULL))
1548 spi->mode |= SPI_LSB_FIRST;
1550 /* Device DUAL/QUAD mode */
1551 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1552 switch (value) {
1553 case 1:
1554 break;
1555 case 2:
1556 spi->mode |= SPI_TX_DUAL;
1557 break;
1558 case 4:
1559 spi->mode |= SPI_TX_QUAD;
1560 break;
1561 default:
1562 dev_warn(&master->dev,
1563 "spi-tx-bus-width %d not supported\n",
1564 value);
1565 break;
1569 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1570 switch (value) {
1571 case 1:
1572 break;
1573 case 2:
1574 spi->mode |= SPI_RX_DUAL;
1575 break;
1576 case 4:
1577 spi->mode |= SPI_RX_QUAD;
1578 break;
1579 default:
1580 dev_warn(&master->dev,
1581 "spi-rx-bus-width %d not supported\n",
1582 value);
1583 break;
1587 if (spi_controller_is_slave(master)) {
1588 if (strcmp(nc->name, "slave")) {
1589 dev_err(&master->dev, "%s is not called 'slave'\n",
1590 nc->full_name);
1591 return -EINVAL;
1593 return 0;
1596 /* Device address */
1597 rc = of_property_read_u32(nc, "reg", &value);
1598 if (rc) {
1599 dev_err(&master->dev, "%s has no valid 'reg' property (%d)\n",
1600 nc->full_name, rc);
1601 return rc;
1603 spi->chip_select = value;
1605 /* Device speed */
1606 rc = of_property_read_u32(nc, "spi-max-frequency", &value);
1607 if (rc) {
1608 dev_err(&master->dev, "%s has no valid 'spi-max-frequency' property (%d)\n",
1609 nc->full_name, rc);
1610 return rc;
1612 spi->max_speed_hz = value;
1614 return 0;
1617 static struct spi_device *
1618 of_register_spi_device(struct spi_master *master, struct device_node *nc)
1620 struct spi_device *spi;
1621 int rc;
1623 /* Alloc an spi_device */
1624 spi = spi_alloc_device(master);
1625 if (!spi) {
1626 dev_err(&master->dev, "spi_device alloc error for %s\n",
1627 nc->full_name);
1628 rc = -ENOMEM;
1629 goto err_out;
1632 /* Select device driver */
1633 rc = of_modalias_node(nc, spi->modalias,
1634 sizeof(spi->modalias));
1635 if (rc < 0) {
1636 dev_err(&master->dev, "cannot find modalias for %s\n",
1637 nc->full_name);
1638 goto err_out;
1641 rc = of_spi_parse_dt(master, spi, nc);
1642 if (rc)
1643 goto err_out;
1645 /* Store a pointer to the node in the device structure */
1646 of_node_get(nc);
1647 spi->dev.of_node = nc;
1649 /* Register the new device */
1650 rc = spi_add_device(spi);
1651 if (rc) {
1652 dev_err(&master->dev, "spi_device register error %s\n",
1653 nc->full_name);
1654 goto err_of_node_put;
1657 return spi;
1659 err_of_node_put:
1660 of_node_put(nc);
1661 err_out:
1662 spi_dev_put(spi);
1663 return ERR_PTR(rc);
1667 * of_register_spi_devices() - Register child devices onto the SPI bus
1668 * @master: Pointer to spi_master device
1670 * Registers an spi_device for each child node of controller node which
1671 * represents a valid SPI slave.
1673 static void of_register_spi_devices(struct spi_master *master)
1675 struct spi_device *spi;
1676 struct device_node *nc;
1678 if (!master->dev.of_node)
1679 return;
1681 for_each_available_child_of_node(master->dev.of_node, nc) {
1682 if (of_node_test_and_set_flag(nc, OF_POPULATED))
1683 continue;
1684 spi = of_register_spi_device(master, nc);
1685 if (IS_ERR(spi)) {
1686 dev_warn(&master->dev, "Failed to create SPI device for %s\n",
1687 nc->full_name);
1688 of_node_clear_flag(nc, OF_POPULATED);
1692 #else
1693 static void of_register_spi_devices(struct spi_master *master) { }
1694 #endif
1696 #ifdef CONFIG_ACPI
1697 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
1699 struct spi_device *spi = data;
1700 struct spi_master *master = spi->master;
1702 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
1703 struct acpi_resource_spi_serialbus *sb;
1705 sb = &ares->data.spi_serial_bus;
1706 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
1708 * ACPI DeviceSelection numbering is handled by the
1709 * host controller driver in Windows and can vary
1710 * from driver to driver. In Linux we always expect
1711 * 0 .. max - 1 so we need to ask the driver to
1712 * translate between the two schemes.
1714 if (master->fw_translate_cs) {
1715 int cs = master->fw_translate_cs(master,
1716 sb->device_selection);
1717 if (cs < 0)
1718 return cs;
1719 spi->chip_select = cs;
1720 } else {
1721 spi->chip_select = sb->device_selection;
1724 spi->max_speed_hz = sb->connection_speed;
1726 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
1727 spi->mode |= SPI_CPHA;
1728 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
1729 spi->mode |= SPI_CPOL;
1730 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
1731 spi->mode |= SPI_CS_HIGH;
1733 } else if (spi->irq < 0) {
1734 struct resource r;
1736 if (acpi_dev_resource_interrupt(ares, 0, &r))
1737 spi->irq = r.start;
1740 /* Always tell the ACPI core to skip this resource */
1741 return 1;
1744 static acpi_status acpi_register_spi_device(struct spi_master *master,
1745 struct acpi_device *adev)
1747 struct list_head resource_list;
1748 struct spi_device *spi;
1749 int ret;
1751 if (acpi_bus_get_status(adev) || !adev->status.present ||
1752 acpi_device_enumerated(adev))
1753 return AE_OK;
1755 spi = spi_alloc_device(master);
1756 if (!spi) {
1757 dev_err(&master->dev, "failed to allocate SPI device for %s\n",
1758 dev_name(&adev->dev));
1759 return AE_NO_MEMORY;
1762 ACPI_COMPANION_SET(&spi->dev, adev);
1763 spi->irq = -1;
1765 INIT_LIST_HEAD(&resource_list);
1766 ret = acpi_dev_get_resources(adev, &resource_list,
1767 acpi_spi_add_resource, spi);
1768 acpi_dev_free_resource_list(&resource_list);
1770 if (ret < 0 || !spi->max_speed_hz) {
1771 spi_dev_put(spi);
1772 return AE_OK;
1775 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
1776 sizeof(spi->modalias));
1778 if (spi->irq < 0)
1779 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
1781 acpi_device_set_enumerated(adev);
1783 adev->power.flags.ignore_parent = true;
1784 if (spi_add_device(spi)) {
1785 adev->power.flags.ignore_parent = false;
1786 dev_err(&master->dev, "failed to add SPI device %s from ACPI\n",
1787 dev_name(&adev->dev));
1788 spi_dev_put(spi);
1791 return AE_OK;
1794 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
1795 void *data, void **return_value)
1797 struct spi_master *master = data;
1798 struct acpi_device *adev;
1800 if (acpi_bus_get_device(handle, &adev))
1801 return AE_OK;
1803 return acpi_register_spi_device(master, adev);
1806 static void acpi_register_spi_devices(struct spi_master *master)
1808 acpi_status status;
1809 acpi_handle handle;
1811 handle = ACPI_HANDLE(master->dev.parent);
1812 if (!handle)
1813 return;
1815 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
1816 acpi_spi_add_device, NULL,
1817 master, NULL);
1818 if (ACPI_FAILURE(status))
1819 dev_warn(&master->dev, "failed to enumerate SPI slaves\n");
1821 #else
1822 static inline void acpi_register_spi_devices(struct spi_master *master) {}
1823 #endif /* CONFIG_ACPI */
1825 static void spi_master_release(struct device *dev)
1827 struct spi_master *master;
1829 master = container_of(dev, struct spi_master, dev);
1830 kfree(master);
1833 static struct class spi_master_class = {
1834 .name = "spi_master",
1835 .owner = THIS_MODULE,
1836 .dev_release = spi_master_release,
1837 .dev_groups = spi_master_groups,
1840 #ifdef CONFIG_SPI_SLAVE
1842 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
1843 * controller
1844 * @spi: device used for the current transfer
1846 int spi_slave_abort(struct spi_device *spi)
1848 struct spi_master *master = spi->master;
1850 if (spi_controller_is_slave(master) && master->slave_abort)
1851 return master->slave_abort(master);
1853 return -ENOTSUPP;
1855 EXPORT_SYMBOL_GPL(spi_slave_abort);
1857 static int match_true(struct device *dev, void *data)
1859 return 1;
1862 static ssize_t spi_slave_show(struct device *dev,
1863 struct device_attribute *attr, char *buf)
1865 struct spi_master *ctlr = container_of(dev, struct spi_master, dev);
1866 struct device *child;
1868 child = device_find_child(&ctlr->dev, NULL, match_true);
1869 return sprintf(buf, "%s\n",
1870 child ? to_spi_device(child)->modalias : NULL);
1873 static ssize_t spi_slave_store(struct device *dev,
1874 struct device_attribute *attr, const char *buf,
1875 size_t count)
1877 struct spi_master *ctlr = container_of(dev, struct spi_master, dev);
1878 struct spi_device *spi;
1879 struct device *child;
1880 char name[32];
1881 int rc;
1883 rc = sscanf(buf, "%31s", name);
1884 if (rc != 1 || !name[0])
1885 return -EINVAL;
1887 child = device_find_child(&ctlr->dev, NULL, match_true);
1888 if (child) {
1889 /* Remove registered slave */
1890 device_unregister(child);
1891 put_device(child);
1894 if (strcmp(name, "(null)")) {
1895 /* Register new slave */
1896 spi = spi_alloc_device(ctlr);
1897 if (!spi)
1898 return -ENOMEM;
1900 strlcpy(spi->modalias, name, sizeof(spi->modalias));
1902 rc = spi_add_device(spi);
1903 if (rc) {
1904 spi_dev_put(spi);
1905 return rc;
1909 return count;
1912 static DEVICE_ATTR(slave, 0644, spi_slave_show, spi_slave_store);
1914 static struct attribute *spi_slave_attrs[] = {
1915 &dev_attr_slave.attr,
1916 NULL,
1919 static const struct attribute_group spi_slave_group = {
1920 .attrs = spi_slave_attrs,
1923 static const struct attribute_group *spi_slave_groups[] = {
1924 &spi_master_statistics_group,
1925 &spi_slave_group,
1926 NULL,
1929 static struct class spi_slave_class = {
1930 .name = "spi_slave",
1931 .owner = THIS_MODULE,
1932 .dev_release = spi_master_release,
1933 .dev_groups = spi_slave_groups,
1935 #else
1936 extern struct class spi_slave_class; /* dummy */
1937 #endif
1940 * __spi_alloc_controller - allocate an SPI master or slave controller
1941 * @dev: the controller, possibly using the platform_bus
1942 * @size: how much zeroed driver-private data to allocate; the pointer to this
1943 * memory is in the driver_data field of the returned device,
1944 * accessible with spi_master_get_devdata().
1945 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
1946 * slave (true) controller
1947 * Context: can sleep
1949 * This call is used only by SPI controller drivers, which are the
1950 * only ones directly touching chip registers. It's how they allocate
1951 * an spi_master structure, prior to calling spi_register_master().
1953 * This must be called from context that can sleep.
1955 * The caller is responsible for assigning the bus number and initializing the
1956 * controller's methods before calling spi_register_master(); and (after errors
1957 * adding the device) calling spi_master_put() to prevent a memory leak.
1959 * Return: the SPI controller structure on success, else NULL.
1961 struct spi_master *__spi_alloc_controller(struct device *dev,
1962 unsigned int size, bool slave)
1964 struct spi_master *master;
1966 if (!dev)
1967 return NULL;
1969 master = kzalloc(size + sizeof(*master), GFP_KERNEL);
1970 if (!master)
1971 return NULL;
1973 device_initialize(&master->dev);
1974 master->bus_num = -1;
1975 master->num_chipselect = 1;
1976 master->slave = slave;
1977 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
1978 master->dev.class = &spi_slave_class;
1979 else
1980 master->dev.class = &spi_master_class;
1981 master->dev.parent = dev;
1982 pm_suspend_ignore_children(&master->dev, true);
1983 spi_master_set_devdata(master, &master[1]);
1985 return master;
1987 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
1989 #ifdef CONFIG_OF
1990 static int of_spi_register_master(struct spi_master *master)
1992 int nb, i, *cs;
1993 struct device_node *np = master->dev.of_node;
1995 if (!np)
1996 return 0;
1998 nb = of_gpio_named_count(np, "cs-gpios");
1999 master->num_chipselect = max_t(int, nb, master->num_chipselect);
2001 /* Return error only for an incorrectly formed cs-gpios property */
2002 if (nb == 0 || nb == -ENOENT)
2003 return 0;
2004 else if (nb < 0)
2005 return nb;
2007 cs = devm_kzalloc(&master->dev,
2008 sizeof(int) * master->num_chipselect,
2009 GFP_KERNEL);
2010 master->cs_gpios = cs;
2012 if (!master->cs_gpios)
2013 return -ENOMEM;
2015 for (i = 0; i < master->num_chipselect; i++)
2016 cs[i] = -ENOENT;
2018 for (i = 0; i < nb; i++)
2019 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2021 return 0;
2023 #else
2024 static int of_spi_register_master(struct spi_master *master)
2026 return 0;
2028 #endif
2031 * spi_register_master - register SPI master controller
2032 * @master: initialized master, originally from spi_alloc_master()
2033 * Context: can sleep
2035 * SPI master controllers connect to their drivers using some non-SPI bus,
2036 * such as the platform bus. The final stage of probe() in that code
2037 * includes calling spi_register_master() to hook up to this SPI bus glue.
2039 * SPI controllers use board specific (often SOC specific) bus numbers,
2040 * and board-specific addressing for SPI devices combines those numbers
2041 * with chip select numbers. Since SPI does not directly support dynamic
2042 * device identification, boards need configuration tables telling which
2043 * chip is at which address.
2045 * This must be called from context that can sleep. It returns zero on
2046 * success, else a negative error code (dropping the master's refcount).
2047 * After a successful return, the caller is responsible for calling
2048 * spi_unregister_master().
2050 * Return: zero on success, else a negative error code.
2052 int spi_register_master(struct spi_master *master)
2054 static atomic_t dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
2055 struct device *dev = master->dev.parent;
2056 struct boardinfo *bi;
2057 int status = -ENODEV;
2058 int dynamic = 0;
2060 if (!dev)
2061 return -ENODEV;
2063 if (!spi_controller_is_slave(master)) {
2064 status = of_spi_register_master(master);
2065 if (status)
2066 return status;
2069 /* even if it's just one always-selected device, there must
2070 * be at least one chipselect
2072 if (master->num_chipselect == 0)
2073 return -EINVAL;
2075 if ((master->bus_num < 0) && master->dev.of_node)
2076 master->bus_num = of_alias_get_id(master->dev.of_node, "spi");
2078 /* convention: dynamically assigned bus IDs count down from the max */
2079 if (master->bus_num < 0) {
2080 /* FIXME switch to an IDR based scheme, something like
2081 * I2C now uses, so we can't run out of "dynamic" IDs
2083 master->bus_num = atomic_dec_return(&dyn_bus_id);
2084 dynamic = 1;
2087 INIT_LIST_HEAD(&master->queue);
2088 spin_lock_init(&master->queue_lock);
2089 spin_lock_init(&master->bus_lock_spinlock);
2090 mutex_init(&master->bus_lock_mutex);
2091 mutex_init(&master->io_mutex);
2092 master->bus_lock_flag = 0;
2093 init_completion(&master->xfer_completion);
2094 if (!master->max_dma_len)
2095 master->max_dma_len = INT_MAX;
2097 /* register the device, then userspace will see it.
2098 * registration fails if the bus ID is in use.
2100 dev_set_name(&master->dev, "spi%u", master->bus_num);
2101 status = device_add(&master->dev);
2102 if (status < 0)
2103 goto done;
2104 dev_dbg(dev, "registered %s %s%s\n",
2105 spi_controller_is_slave(master) ? "slave" : "master",
2106 dev_name(&master->dev), dynamic ? " (dynamic)" : "");
2108 /* If we're using a queued driver, start the queue */
2109 if (master->transfer)
2110 dev_info(dev, "master is unqueued, this is deprecated\n");
2111 else {
2112 status = spi_master_initialize_queue(master);
2113 if (status) {
2114 device_del(&master->dev);
2115 goto done;
2118 /* add statistics */
2119 spin_lock_init(&master->statistics.lock);
2121 mutex_lock(&board_lock);
2122 list_add_tail(&master->list, &spi_master_list);
2123 list_for_each_entry(bi, &board_list, list)
2124 spi_match_master_to_boardinfo(master, &bi->board_info);
2125 mutex_unlock(&board_lock);
2127 /* Register devices from the device tree and ACPI */
2128 of_register_spi_devices(master);
2129 acpi_register_spi_devices(master);
2130 done:
2131 return status;
2133 EXPORT_SYMBOL_GPL(spi_register_master);
2135 static void devm_spi_unregister(struct device *dev, void *res)
2137 spi_unregister_master(*(struct spi_master **)res);
2141 * devm_spi_register_master - register managed SPI master controller
2142 * @dev: device managing SPI master
2143 * @master: initialized master, originally from spi_alloc_master()
2144 * Context: can sleep
2146 * Register a SPI device as with spi_register_master() which will
2147 * automatically be unregister
2149 * Return: zero on success, else a negative error code.
2151 int devm_spi_register_master(struct device *dev, struct spi_master *master)
2153 struct spi_master **ptr;
2154 int ret;
2156 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2157 if (!ptr)
2158 return -ENOMEM;
2160 ret = spi_register_master(master);
2161 if (!ret) {
2162 *ptr = master;
2163 devres_add(dev, ptr);
2164 } else {
2165 devres_free(ptr);
2168 return ret;
2170 EXPORT_SYMBOL_GPL(devm_spi_register_master);
2172 static int __unregister(struct device *dev, void *null)
2174 spi_unregister_device(to_spi_device(dev));
2175 return 0;
2179 * spi_unregister_master - unregister SPI master controller
2180 * @master: the master being unregistered
2181 * Context: can sleep
2183 * This call is used only by SPI master controller drivers, which are the
2184 * only ones directly touching chip registers.
2186 * This must be called from context that can sleep.
2188 void spi_unregister_master(struct spi_master *master)
2190 int dummy;
2192 if (master->queued) {
2193 if (spi_destroy_queue(master))
2194 dev_err(&master->dev, "queue remove failed\n");
2197 mutex_lock(&board_lock);
2198 list_del(&master->list);
2199 mutex_unlock(&board_lock);
2201 dummy = device_for_each_child(&master->dev, NULL, __unregister);
2202 device_unregister(&master->dev);
2204 EXPORT_SYMBOL_GPL(spi_unregister_master);
2206 int spi_master_suspend(struct spi_master *master)
2208 int ret;
2210 /* Basically no-ops for non-queued masters */
2211 if (!master->queued)
2212 return 0;
2214 ret = spi_stop_queue(master);
2215 if (ret)
2216 dev_err(&master->dev, "queue stop failed\n");
2218 return ret;
2220 EXPORT_SYMBOL_GPL(spi_master_suspend);
2222 int spi_master_resume(struct spi_master *master)
2224 int ret;
2226 if (!master->queued)
2227 return 0;
2229 ret = spi_start_queue(master);
2230 if (ret)
2231 dev_err(&master->dev, "queue restart failed\n");
2233 return ret;
2235 EXPORT_SYMBOL_GPL(spi_master_resume);
2237 static int __spi_master_match(struct device *dev, const void *data)
2239 struct spi_master *m;
2240 const u16 *bus_num = data;
2242 m = container_of(dev, struct spi_master, dev);
2243 return m->bus_num == *bus_num;
2247 * spi_busnum_to_master - look up master associated with bus_num
2248 * @bus_num: the master's bus number
2249 * Context: can sleep
2251 * This call may be used with devices that are registered after
2252 * arch init time. It returns a refcounted pointer to the relevant
2253 * spi_master (which the caller must release), or NULL if there is
2254 * no such master registered.
2256 * Return: the SPI master structure on success, else NULL.
2258 struct spi_master *spi_busnum_to_master(u16 bus_num)
2260 struct device *dev;
2261 struct spi_master *master = NULL;
2263 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2264 __spi_master_match);
2265 if (dev)
2266 master = container_of(dev, struct spi_master, dev);
2267 /* reference got in class_find_device */
2268 return master;
2270 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2272 /*-------------------------------------------------------------------------*/
2274 /* Core methods for SPI resource management */
2277 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2278 * during the processing of a spi_message while using
2279 * spi_transfer_one
2280 * @spi: the spi device for which we allocate memory
2281 * @release: the release code to execute for this resource
2282 * @size: size to alloc and return
2283 * @gfp: GFP allocation flags
2285 * Return: the pointer to the allocated data
2287 * This may get enhanced in the future to allocate from a memory pool
2288 * of the @spi_device or @spi_master to avoid repeated allocations.
2290 void *spi_res_alloc(struct spi_device *spi,
2291 spi_res_release_t release,
2292 size_t size, gfp_t gfp)
2294 struct spi_res *sres;
2296 sres = kzalloc(sizeof(*sres) + size, gfp);
2297 if (!sres)
2298 return NULL;
2300 INIT_LIST_HEAD(&sres->entry);
2301 sres->release = release;
2303 return sres->data;
2305 EXPORT_SYMBOL_GPL(spi_res_alloc);
2308 * spi_res_free - free an spi resource
2309 * @res: pointer to the custom data of a resource
2312 void spi_res_free(void *res)
2314 struct spi_res *sres = container_of(res, struct spi_res, data);
2316 if (!res)
2317 return;
2319 WARN_ON(!list_empty(&sres->entry));
2320 kfree(sres);
2322 EXPORT_SYMBOL_GPL(spi_res_free);
2325 * spi_res_add - add a spi_res to the spi_message
2326 * @message: the spi message
2327 * @res: the spi_resource
2329 void spi_res_add(struct spi_message *message, void *res)
2331 struct spi_res *sres = container_of(res, struct spi_res, data);
2333 WARN_ON(!list_empty(&sres->entry));
2334 list_add_tail(&sres->entry, &message->resources);
2336 EXPORT_SYMBOL_GPL(spi_res_add);
2339 * spi_res_release - release all spi resources for this message
2340 * @master: the @spi_master
2341 * @message: the @spi_message
2343 void spi_res_release(struct spi_master *master,
2344 struct spi_message *message)
2346 struct spi_res *res;
2348 while (!list_empty(&message->resources)) {
2349 res = list_last_entry(&message->resources,
2350 struct spi_res, entry);
2352 if (res->release)
2353 res->release(master, message, res->data);
2355 list_del(&res->entry);
2357 kfree(res);
2360 EXPORT_SYMBOL_GPL(spi_res_release);
2362 /*-------------------------------------------------------------------------*/
2364 /* Core methods for spi_message alterations */
2366 static void __spi_replace_transfers_release(struct spi_master *master,
2367 struct spi_message *msg,
2368 void *res)
2370 struct spi_replaced_transfers *rxfer = res;
2371 size_t i;
2373 /* call extra callback if requested */
2374 if (rxfer->release)
2375 rxfer->release(master, msg, res);
2377 /* insert replaced transfers back into the message */
2378 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
2380 /* remove the formerly inserted entries */
2381 for (i = 0; i < rxfer->inserted; i++)
2382 list_del(&rxfer->inserted_transfers[i].transfer_list);
2386 * spi_replace_transfers - replace transfers with several transfers
2387 * and register change with spi_message.resources
2388 * @msg: the spi_message we work upon
2389 * @xfer_first: the first spi_transfer we want to replace
2390 * @remove: number of transfers to remove
2391 * @insert: the number of transfers we want to insert instead
2392 * @release: extra release code necessary in some circumstances
2393 * @extradatasize: extra data to allocate (with alignment guarantees
2394 * of struct @spi_transfer)
2395 * @gfp: gfp flags
2397 * Returns: pointer to @spi_replaced_transfers,
2398 * PTR_ERR(...) in case of errors.
2400 struct spi_replaced_transfers *spi_replace_transfers(
2401 struct spi_message *msg,
2402 struct spi_transfer *xfer_first,
2403 size_t remove,
2404 size_t insert,
2405 spi_replaced_release_t release,
2406 size_t extradatasize,
2407 gfp_t gfp)
2409 struct spi_replaced_transfers *rxfer;
2410 struct spi_transfer *xfer;
2411 size_t i;
2413 /* allocate the structure using spi_res */
2414 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
2415 insert * sizeof(struct spi_transfer)
2416 + sizeof(struct spi_replaced_transfers)
2417 + extradatasize,
2418 gfp);
2419 if (!rxfer)
2420 return ERR_PTR(-ENOMEM);
2422 /* the release code to invoke before running the generic release */
2423 rxfer->release = release;
2425 /* assign extradata */
2426 if (extradatasize)
2427 rxfer->extradata =
2428 &rxfer->inserted_transfers[insert];
2430 /* init the replaced_transfers list */
2431 INIT_LIST_HEAD(&rxfer->replaced_transfers);
2433 /* assign the list_entry after which we should reinsert
2434 * the @replaced_transfers - it may be spi_message.messages!
2436 rxfer->replaced_after = xfer_first->transfer_list.prev;
2438 /* remove the requested number of transfers */
2439 for (i = 0; i < remove; i++) {
2440 /* if the entry after replaced_after it is msg->transfers
2441 * then we have been requested to remove more transfers
2442 * than are in the list
2444 if (rxfer->replaced_after->next == &msg->transfers) {
2445 dev_err(&msg->spi->dev,
2446 "requested to remove more spi_transfers than are available\n");
2447 /* insert replaced transfers back into the message */
2448 list_splice(&rxfer->replaced_transfers,
2449 rxfer->replaced_after);
2451 /* free the spi_replace_transfer structure */
2452 spi_res_free(rxfer);
2454 /* and return with an error */
2455 return ERR_PTR(-EINVAL);
2458 /* remove the entry after replaced_after from list of
2459 * transfers and add it to list of replaced_transfers
2461 list_move_tail(rxfer->replaced_after->next,
2462 &rxfer->replaced_transfers);
2465 /* create copy of the given xfer with identical settings
2466 * based on the first transfer to get removed
2468 for (i = 0; i < insert; i++) {
2469 /* we need to run in reverse order */
2470 xfer = &rxfer->inserted_transfers[insert - 1 - i];
2472 /* copy all spi_transfer data */
2473 memcpy(xfer, xfer_first, sizeof(*xfer));
2475 /* add to list */
2476 list_add(&xfer->transfer_list, rxfer->replaced_after);
2478 /* clear cs_change and delay_usecs for all but the last */
2479 if (i) {
2480 xfer->cs_change = false;
2481 xfer->delay_usecs = 0;
2485 /* set up inserted */
2486 rxfer->inserted = insert;
2488 /* and register it with spi_res/spi_message */
2489 spi_res_add(msg, rxfer);
2491 return rxfer;
2493 EXPORT_SYMBOL_GPL(spi_replace_transfers);
2495 static int __spi_split_transfer_maxsize(struct spi_master *master,
2496 struct spi_message *msg,
2497 struct spi_transfer **xferp,
2498 size_t maxsize,
2499 gfp_t gfp)
2501 struct spi_transfer *xfer = *xferp, *xfers;
2502 struct spi_replaced_transfers *srt;
2503 size_t offset;
2504 size_t count, i;
2506 /* warn once about this fact that we are splitting a transfer */
2507 dev_warn_once(&msg->spi->dev,
2508 "spi_transfer of length %i exceed max length of %zu - needed to split transfers\n",
2509 xfer->len, maxsize);
2511 /* calculate how many we have to replace */
2512 count = DIV_ROUND_UP(xfer->len, maxsize);
2514 /* create replacement */
2515 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
2516 if (IS_ERR(srt))
2517 return PTR_ERR(srt);
2518 xfers = srt->inserted_transfers;
2520 /* now handle each of those newly inserted spi_transfers
2521 * note that the replacements spi_transfers all are preset
2522 * to the same values as *xferp, so tx_buf, rx_buf and len
2523 * are all identical (as well as most others)
2524 * so we just have to fix up len and the pointers.
2526 * this also includes support for the depreciated
2527 * spi_message.is_dma_mapped interface
2530 /* the first transfer just needs the length modified, so we
2531 * run it outside the loop
2533 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
2535 /* all the others need rx_buf/tx_buf also set */
2536 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
2537 /* update rx_buf, tx_buf and dma */
2538 if (xfers[i].rx_buf)
2539 xfers[i].rx_buf += offset;
2540 if (xfers[i].rx_dma)
2541 xfers[i].rx_dma += offset;
2542 if (xfers[i].tx_buf)
2543 xfers[i].tx_buf += offset;
2544 if (xfers[i].tx_dma)
2545 xfers[i].tx_dma += offset;
2547 /* update length */
2548 xfers[i].len = min(maxsize, xfers[i].len - offset);
2551 /* we set up xferp to the last entry we have inserted,
2552 * so that we skip those already split transfers
2554 *xferp = &xfers[count - 1];
2556 /* increment statistics counters */
2557 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics,
2558 transfers_split_maxsize);
2559 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
2560 transfers_split_maxsize);
2562 return 0;
2566 * spi_split_tranfers_maxsize - split spi transfers into multiple transfers
2567 * when an individual transfer exceeds a
2568 * certain size
2569 * @master: the @spi_master for this transfer
2570 * @msg: the @spi_message to transform
2571 * @maxsize: the maximum when to apply this
2572 * @gfp: GFP allocation flags
2574 * Return: status of transformation
2576 int spi_split_transfers_maxsize(struct spi_master *master,
2577 struct spi_message *msg,
2578 size_t maxsize,
2579 gfp_t gfp)
2581 struct spi_transfer *xfer;
2582 int ret;
2584 /* iterate over the transfer_list,
2585 * but note that xfer is advanced to the last transfer inserted
2586 * to avoid checking sizes again unnecessarily (also xfer does
2587 * potentiall belong to a different list by the time the
2588 * replacement has happened
2590 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
2591 if (xfer->len > maxsize) {
2592 ret = __spi_split_transfer_maxsize(
2593 master, msg, &xfer, maxsize, gfp);
2594 if (ret)
2595 return ret;
2599 return 0;
2601 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
2603 /*-------------------------------------------------------------------------*/
2605 /* Core methods for SPI master protocol drivers. Some of the
2606 * other core methods are currently defined as inline functions.
2609 static int __spi_validate_bits_per_word(struct spi_master *master, u8 bits_per_word)
2611 if (master->bits_per_word_mask) {
2612 /* Only 32 bits fit in the mask */
2613 if (bits_per_word > 32)
2614 return -EINVAL;
2615 if (!(master->bits_per_word_mask &
2616 SPI_BPW_MASK(bits_per_word)))
2617 return -EINVAL;
2620 return 0;
2624 * spi_setup - setup SPI mode and clock rate
2625 * @spi: the device whose settings are being modified
2626 * Context: can sleep, and no requests are queued to the device
2628 * SPI protocol drivers may need to update the transfer mode if the
2629 * device doesn't work with its default. They may likewise need
2630 * to update clock rates or word sizes from initial values. This function
2631 * changes those settings, and must be called from a context that can sleep.
2632 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
2633 * effect the next time the device is selected and data is transferred to
2634 * or from it. When this function returns, the spi device is deselected.
2636 * Note that this call will fail if the protocol driver specifies an option
2637 * that the underlying controller or its driver does not support. For
2638 * example, not all hardware supports wire transfers using nine bit words,
2639 * LSB-first wire encoding, or active-high chipselects.
2641 * Return: zero on success, else a negative error code.
2643 int spi_setup(struct spi_device *spi)
2645 unsigned bad_bits, ugly_bits;
2646 int status;
2648 /* check mode to prevent that DUAL and QUAD set at the same time
2650 if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
2651 ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
2652 dev_err(&spi->dev,
2653 "setup: can not select dual and quad at the same time\n");
2654 return -EINVAL;
2656 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
2658 if ((spi->mode & SPI_3WIRE) && (spi->mode &
2659 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
2660 return -EINVAL;
2661 /* help drivers fail *cleanly* when they need options
2662 * that aren't supported with their current master
2664 bad_bits = spi->mode & ~spi->master->mode_bits;
2665 ugly_bits = bad_bits &
2666 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD);
2667 if (ugly_bits) {
2668 dev_warn(&spi->dev,
2669 "setup: ignoring unsupported mode bits %x\n",
2670 ugly_bits);
2671 spi->mode &= ~ugly_bits;
2672 bad_bits &= ~ugly_bits;
2674 if (bad_bits) {
2675 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
2676 bad_bits);
2677 return -EINVAL;
2680 if (!spi->bits_per_word)
2681 spi->bits_per_word = 8;
2683 status = __spi_validate_bits_per_word(spi->master, spi->bits_per_word);
2684 if (status)
2685 return status;
2687 if (!spi->max_speed_hz)
2688 spi->max_speed_hz = spi->master->max_speed_hz;
2690 if (spi->master->setup)
2691 status = spi->master->setup(spi);
2693 spi_set_cs(spi, false);
2695 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
2696 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
2697 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
2698 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
2699 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
2700 (spi->mode & SPI_LOOP) ? "loopback, " : "",
2701 spi->bits_per_word, spi->max_speed_hz,
2702 status);
2704 return status;
2706 EXPORT_SYMBOL_GPL(spi_setup);
2708 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
2710 struct spi_master *master = spi->master;
2711 struct spi_transfer *xfer;
2712 int w_size;
2714 if (list_empty(&message->transfers))
2715 return -EINVAL;
2717 /* Half-duplex links include original MicroWire, and ones with
2718 * only one data pin like SPI_3WIRE (switches direction) or where
2719 * either MOSI or MISO is missing. They can also be caused by
2720 * software limitations.
2722 if ((master->flags & SPI_MASTER_HALF_DUPLEX)
2723 || (spi->mode & SPI_3WIRE)) {
2724 unsigned flags = master->flags;
2726 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2727 if (xfer->rx_buf && xfer->tx_buf)
2728 return -EINVAL;
2729 if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
2730 return -EINVAL;
2731 if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
2732 return -EINVAL;
2737 * Set transfer bits_per_word and max speed as spi device default if
2738 * it is not set for this transfer.
2739 * Set transfer tx_nbits and rx_nbits as single transfer default
2740 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
2742 message->frame_length = 0;
2743 list_for_each_entry(xfer, &message->transfers, transfer_list) {
2744 message->frame_length += xfer->len;
2745 if (!xfer->bits_per_word)
2746 xfer->bits_per_word = spi->bits_per_word;
2748 if (!xfer->speed_hz)
2749 xfer->speed_hz = spi->max_speed_hz;
2750 if (!xfer->speed_hz)
2751 xfer->speed_hz = master->max_speed_hz;
2753 if (master->max_speed_hz &&
2754 xfer->speed_hz > master->max_speed_hz)
2755 xfer->speed_hz = master->max_speed_hz;
2757 if (__spi_validate_bits_per_word(master, xfer->bits_per_word))
2758 return -EINVAL;
2761 * SPI transfer length should be multiple of SPI word size
2762 * where SPI word size should be power-of-two multiple
2764 if (xfer->bits_per_word <= 8)
2765 w_size = 1;
2766 else if (xfer->bits_per_word <= 16)
2767 w_size = 2;
2768 else
2769 w_size = 4;
2771 /* No partial transfers accepted */
2772 if (xfer->len % w_size)
2773 return -EINVAL;
2775 if (xfer->speed_hz && master->min_speed_hz &&
2776 xfer->speed_hz < master->min_speed_hz)
2777 return -EINVAL;
2779 if (xfer->tx_buf && !xfer->tx_nbits)
2780 xfer->tx_nbits = SPI_NBITS_SINGLE;
2781 if (xfer->rx_buf && !xfer->rx_nbits)
2782 xfer->rx_nbits = SPI_NBITS_SINGLE;
2783 /* check transfer tx/rx_nbits:
2784 * 1. check the value matches one of single, dual and quad
2785 * 2. check tx/rx_nbits match the mode in spi_device
2787 if (xfer->tx_buf) {
2788 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
2789 xfer->tx_nbits != SPI_NBITS_DUAL &&
2790 xfer->tx_nbits != SPI_NBITS_QUAD)
2791 return -EINVAL;
2792 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
2793 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
2794 return -EINVAL;
2795 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
2796 !(spi->mode & SPI_TX_QUAD))
2797 return -EINVAL;
2799 /* check transfer rx_nbits */
2800 if (xfer->rx_buf) {
2801 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
2802 xfer->rx_nbits != SPI_NBITS_DUAL &&
2803 xfer->rx_nbits != SPI_NBITS_QUAD)
2804 return -EINVAL;
2805 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
2806 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
2807 return -EINVAL;
2808 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
2809 !(spi->mode & SPI_RX_QUAD))
2810 return -EINVAL;
2814 message->status = -EINPROGRESS;
2816 return 0;
2819 static int __spi_async(struct spi_device *spi, struct spi_message *message)
2821 struct spi_master *master = spi->master;
2823 message->spi = spi;
2825 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics, spi_async);
2826 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
2828 trace_spi_message_submit(message);
2830 return master->transfer(spi, message);
2834 * spi_async - asynchronous SPI transfer
2835 * @spi: device with which data will be exchanged
2836 * @message: describes the data transfers, including completion callback
2837 * Context: any (irqs may be blocked, etc)
2839 * This call may be used in_irq and other contexts which can't sleep,
2840 * as well as from task contexts which can sleep.
2842 * The completion callback is invoked in a context which can't sleep.
2843 * Before that invocation, the value of message->status is undefined.
2844 * When the callback is issued, message->status holds either zero (to
2845 * indicate complete success) or a negative error code. After that
2846 * callback returns, the driver which issued the transfer request may
2847 * deallocate the associated memory; it's no longer in use by any SPI
2848 * core or controller driver code.
2850 * Note that although all messages to a spi_device are handled in
2851 * FIFO order, messages may go to different devices in other orders.
2852 * Some device might be higher priority, or have various "hard" access
2853 * time requirements, for example.
2855 * On detection of any fault during the transfer, processing of
2856 * the entire message is aborted, and the device is deselected.
2857 * Until returning from the associated message completion callback,
2858 * no other spi_message queued to that device will be processed.
2859 * (This rule applies equally to all the synchronous transfer calls,
2860 * which are wrappers around this core asynchronous primitive.)
2862 * Return: zero on success, else a negative error code.
2864 int spi_async(struct spi_device *spi, struct spi_message *message)
2866 struct spi_master *master = spi->master;
2867 int ret;
2868 unsigned long flags;
2870 ret = __spi_validate(spi, message);
2871 if (ret != 0)
2872 return ret;
2874 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
2876 if (master->bus_lock_flag)
2877 ret = -EBUSY;
2878 else
2879 ret = __spi_async(spi, message);
2881 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
2883 return ret;
2885 EXPORT_SYMBOL_GPL(spi_async);
2888 * spi_async_locked - version of spi_async with exclusive bus usage
2889 * @spi: device with which data will be exchanged
2890 * @message: describes the data transfers, including completion callback
2891 * Context: any (irqs may be blocked, etc)
2893 * This call may be used in_irq and other contexts which can't sleep,
2894 * as well as from task contexts which can sleep.
2896 * The completion callback is invoked in a context which can't sleep.
2897 * Before that invocation, the value of message->status is undefined.
2898 * When the callback is issued, message->status holds either zero (to
2899 * indicate complete success) or a negative error code. After that
2900 * callback returns, the driver which issued the transfer request may
2901 * deallocate the associated memory; it's no longer in use by any SPI
2902 * core or controller driver code.
2904 * Note that although all messages to a spi_device are handled in
2905 * FIFO order, messages may go to different devices in other orders.
2906 * Some device might be higher priority, or have various "hard" access
2907 * time requirements, for example.
2909 * On detection of any fault during the transfer, processing of
2910 * the entire message is aborted, and the device is deselected.
2911 * Until returning from the associated message completion callback,
2912 * no other spi_message queued to that device will be processed.
2913 * (This rule applies equally to all the synchronous transfer calls,
2914 * which are wrappers around this core asynchronous primitive.)
2916 * Return: zero on success, else a negative error code.
2918 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
2920 struct spi_master *master = spi->master;
2921 int ret;
2922 unsigned long flags;
2924 ret = __spi_validate(spi, message);
2925 if (ret != 0)
2926 return ret;
2928 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
2930 ret = __spi_async(spi, message);
2932 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
2934 return ret;
2937 EXPORT_SYMBOL_GPL(spi_async_locked);
2940 int spi_flash_read(struct spi_device *spi,
2941 struct spi_flash_read_message *msg)
2944 struct spi_master *master = spi->master;
2945 struct device *rx_dev = NULL;
2946 int ret;
2948 if ((msg->opcode_nbits == SPI_NBITS_DUAL ||
2949 msg->addr_nbits == SPI_NBITS_DUAL) &&
2950 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
2951 return -EINVAL;
2952 if ((msg->opcode_nbits == SPI_NBITS_QUAD ||
2953 msg->addr_nbits == SPI_NBITS_QUAD) &&
2954 !(spi->mode & SPI_TX_QUAD))
2955 return -EINVAL;
2956 if (msg->data_nbits == SPI_NBITS_DUAL &&
2957 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
2958 return -EINVAL;
2959 if (msg->data_nbits == SPI_NBITS_QUAD &&
2960 !(spi->mode & SPI_RX_QUAD))
2961 return -EINVAL;
2963 if (master->auto_runtime_pm) {
2964 ret = pm_runtime_get_sync(master->dev.parent);
2965 if (ret < 0) {
2966 dev_err(&master->dev, "Failed to power device: %d\n",
2967 ret);
2968 return ret;
2972 mutex_lock(&master->bus_lock_mutex);
2973 mutex_lock(&master->io_mutex);
2974 if (master->dma_rx && master->spi_flash_can_dma(spi, msg)) {
2975 rx_dev = master->dma_rx->device->dev;
2976 ret = spi_map_buf(master, rx_dev, &msg->rx_sg,
2977 msg->buf, msg->len,
2978 DMA_FROM_DEVICE);
2979 if (!ret)
2980 msg->cur_msg_mapped = true;
2982 ret = master->spi_flash_read(spi, msg);
2983 if (msg->cur_msg_mapped)
2984 spi_unmap_buf(master, rx_dev, &msg->rx_sg,
2985 DMA_FROM_DEVICE);
2986 mutex_unlock(&master->io_mutex);
2987 mutex_unlock(&master->bus_lock_mutex);
2989 if (master->auto_runtime_pm)
2990 pm_runtime_put(master->dev.parent);
2992 return ret;
2994 EXPORT_SYMBOL_GPL(spi_flash_read);
2996 /*-------------------------------------------------------------------------*/
2998 /* Utility methods for SPI master protocol drivers, layered on
2999 * top of the core. Some other utility methods are defined as
3000 * inline functions.
3003 static void spi_complete(void *arg)
3005 complete(arg);
3008 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3010 DECLARE_COMPLETION_ONSTACK(done);
3011 int status;
3012 struct spi_master *master = spi->master;
3013 unsigned long flags;
3015 status = __spi_validate(spi, message);
3016 if (status != 0)
3017 return status;
3019 message->complete = spi_complete;
3020 message->context = &done;
3021 message->spi = spi;
3023 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics, spi_sync);
3024 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3026 /* If we're not using the legacy transfer method then we will
3027 * try to transfer in the calling context so special case.
3028 * This code would be less tricky if we could remove the
3029 * support for driver implemented message queues.
3031 if (master->transfer == spi_queued_transfer) {
3032 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
3034 trace_spi_message_submit(message);
3036 status = __spi_queued_transfer(spi, message, false);
3038 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
3039 } else {
3040 status = spi_async_locked(spi, message);
3043 if (status == 0) {
3044 /* Push out the messages in the calling context if we
3045 * can.
3047 if (master->transfer == spi_queued_transfer) {
3048 SPI_STATISTICS_INCREMENT_FIELD(&master->statistics,
3049 spi_sync_immediate);
3050 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3051 spi_sync_immediate);
3052 __spi_pump_messages(master, false);
3055 wait_for_completion(&done);
3056 status = message->status;
3058 message->context = NULL;
3059 return status;
3063 * spi_sync - blocking/synchronous SPI data transfers
3064 * @spi: device with which data will be exchanged
3065 * @message: describes the data transfers
3066 * Context: can sleep
3068 * This call may only be used from a context that may sleep. The sleep
3069 * is non-interruptible, and has no timeout. Low-overhead controller
3070 * drivers may DMA directly into and out of the message buffers.
3072 * Note that the SPI device's chip select is active during the message,
3073 * and then is normally disabled between messages. Drivers for some
3074 * frequently-used devices may want to minimize costs of selecting a chip,
3075 * by leaving it selected in anticipation that the next message will go
3076 * to the same chip. (That may increase power usage.)
3078 * Also, the caller is guaranteeing that the memory associated with the
3079 * message will not be freed before this call returns.
3081 * Return: zero on success, else a negative error code.
3083 int spi_sync(struct spi_device *spi, struct spi_message *message)
3085 int ret;
3087 mutex_lock(&spi->master->bus_lock_mutex);
3088 ret = __spi_sync(spi, message);
3089 mutex_unlock(&spi->master->bus_lock_mutex);
3091 return ret;
3093 EXPORT_SYMBOL_GPL(spi_sync);
3096 * spi_sync_locked - version of spi_sync with exclusive bus usage
3097 * @spi: device with which data will be exchanged
3098 * @message: describes the data transfers
3099 * Context: can sleep
3101 * This call may only be used from a context that may sleep. The sleep
3102 * is non-interruptible, and has no timeout. Low-overhead controller
3103 * drivers may DMA directly into and out of the message buffers.
3105 * This call should be used by drivers that require exclusive access to the
3106 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3107 * be released by a spi_bus_unlock call when the exclusive access is over.
3109 * Return: zero on success, else a negative error code.
3111 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3113 return __spi_sync(spi, message);
3115 EXPORT_SYMBOL_GPL(spi_sync_locked);
3118 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3119 * @master: SPI bus master that should be locked for exclusive bus access
3120 * Context: can sleep
3122 * This call may only be used from a context that may sleep. The sleep
3123 * is non-interruptible, and has no timeout.
3125 * This call should be used by drivers that require exclusive access to the
3126 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3127 * exclusive access is over. Data transfer must be done by spi_sync_locked
3128 * and spi_async_locked calls when the SPI bus lock is held.
3130 * Return: always zero.
3132 int spi_bus_lock(struct spi_master *master)
3134 unsigned long flags;
3136 mutex_lock(&master->bus_lock_mutex);
3138 spin_lock_irqsave(&master->bus_lock_spinlock, flags);
3139 master->bus_lock_flag = 1;
3140 spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
3142 /* mutex remains locked until spi_bus_unlock is called */
3144 return 0;
3146 EXPORT_SYMBOL_GPL(spi_bus_lock);
3149 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3150 * @master: SPI bus master that was locked for exclusive bus access
3151 * Context: can sleep
3153 * This call may only be used from a context that may sleep. The sleep
3154 * is non-interruptible, and has no timeout.
3156 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3157 * call.
3159 * Return: always zero.
3161 int spi_bus_unlock(struct spi_master *master)
3163 master->bus_lock_flag = 0;
3165 mutex_unlock(&master->bus_lock_mutex);
3167 return 0;
3169 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3171 /* portable code must never pass more than 32 bytes */
3172 #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
3174 static u8 *buf;
3177 * spi_write_then_read - SPI synchronous write followed by read
3178 * @spi: device with which data will be exchanged
3179 * @txbuf: data to be written (need not be dma-safe)
3180 * @n_tx: size of txbuf, in bytes
3181 * @rxbuf: buffer into which data will be read (need not be dma-safe)
3182 * @n_rx: size of rxbuf, in bytes
3183 * Context: can sleep
3185 * This performs a half duplex MicroWire style transaction with the
3186 * device, sending txbuf and then reading rxbuf. The return value
3187 * is zero for success, else a negative errno status code.
3188 * This call may only be used from a context that may sleep.
3190 * Parameters to this routine are always copied using a small buffer;
3191 * portable code should never use this for more than 32 bytes.
3192 * Performance-sensitive or bulk transfer code should instead use
3193 * spi_{async,sync}() calls with dma-safe buffers.
3195 * Return: zero on success, else a negative error code.
3197 int spi_write_then_read(struct spi_device *spi,
3198 const void *txbuf, unsigned n_tx,
3199 void *rxbuf, unsigned n_rx)
3201 static DEFINE_MUTEX(lock);
3203 int status;
3204 struct spi_message message;
3205 struct spi_transfer x[2];
3206 u8 *local_buf;
3208 /* Use preallocated DMA-safe buffer if we can. We can't avoid
3209 * copying here, (as a pure convenience thing), but we can
3210 * keep heap costs out of the hot path unless someone else is
3211 * using the pre-allocated buffer or the transfer is too large.
3213 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
3214 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
3215 GFP_KERNEL | GFP_DMA);
3216 if (!local_buf)
3217 return -ENOMEM;
3218 } else {
3219 local_buf = buf;
3222 spi_message_init(&message);
3223 memset(x, 0, sizeof(x));
3224 if (n_tx) {
3225 x[0].len = n_tx;
3226 spi_message_add_tail(&x[0], &message);
3228 if (n_rx) {
3229 x[1].len = n_rx;
3230 spi_message_add_tail(&x[1], &message);
3233 memcpy(local_buf, txbuf, n_tx);
3234 x[0].tx_buf = local_buf;
3235 x[1].rx_buf = local_buf + n_tx;
3237 /* do the i/o */
3238 status = spi_sync(spi, &message);
3239 if (status == 0)
3240 memcpy(rxbuf, x[1].rx_buf, n_rx);
3242 if (x[0].tx_buf == buf)
3243 mutex_unlock(&lock);
3244 else
3245 kfree(local_buf);
3247 return status;
3249 EXPORT_SYMBOL_GPL(spi_write_then_read);
3251 /*-------------------------------------------------------------------------*/
3253 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
3254 static int __spi_of_device_match(struct device *dev, void *data)
3256 return dev->of_node == data;
3259 /* must call put_device() when done with returned spi_device device */
3260 static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
3262 struct device *dev = bus_find_device(&spi_bus_type, NULL, node,
3263 __spi_of_device_match);
3264 return dev ? to_spi_device(dev) : NULL;
3267 static int __spi_of_master_match(struct device *dev, const void *data)
3269 return dev->of_node == data;
3272 /* the spi masters are not using spi_bus, so we find it with another way */
3273 static struct spi_master *of_find_spi_master_by_node(struct device_node *node)
3275 struct device *dev;
3277 dev = class_find_device(&spi_master_class, NULL, node,
3278 __spi_of_master_match);
3279 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3280 dev = class_find_device(&spi_slave_class, NULL, node,
3281 __spi_of_master_match);
3282 if (!dev)
3283 return NULL;
3285 /* reference got in class_find_device */
3286 return container_of(dev, struct spi_master, dev);
3289 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
3290 void *arg)
3292 struct of_reconfig_data *rd = arg;
3293 struct spi_master *master;
3294 struct spi_device *spi;
3296 switch (of_reconfig_get_state_change(action, arg)) {
3297 case OF_RECONFIG_CHANGE_ADD:
3298 master = of_find_spi_master_by_node(rd->dn->parent);
3299 if (master == NULL)
3300 return NOTIFY_OK; /* not for us */
3302 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
3303 put_device(&master->dev);
3304 return NOTIFY_OK;
3307 spi = of_register_spi_device(master, rd->dn);
3308 put_device(&master->dev);
3310 if (IS_ERR(spi)) {
3311 pr_err("%s: failed to create for '%s'\n",
3312 __func__, rd->dn->full_name);
3313 of_node_clear_flag(rd->dn, OF_POPULATED);
3314 return notifier_from_errno(PTR_ERR(spi));
3316 break;
3318 case OF_RECONFIG_CHANGE_REMOVE:
3319 /* already depopulated? */
3320 if (!of_node_check_flag(rd->dn, OF_POPULATED))
3321 return NOTIFY_OK;
3323 /* find our device by node */
3324 spi = of_find_spi_device_by_node(rd->dn);
3325 if (spi == NULL)
3326 return NOTIFY_OK; /* no? not meant for us */
3328 /* unregister takes one ref away */
3329 spi_unregister_device(spi);
3331 /* and put the reference of the find */
3332 put_device(&spi->dev);
3333 break;
3336 return NOTIFY_OK;
3339 static struct notifier_block spi_of_notifier = {
3340 .notifier_call = of_spi_notify,
3342 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3343 extern struct notifier_block spi_of_notifier;
3344 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3346 #if IS_ENABLED(CONFIG_ACPI)
3347 static int spi_acpi_master_match(struct device *dev, const void *data)
3349 return ACPI_COMPANION(dev->parent) == data;
3352 static int spi_acpi_device_match(struct device *dev, void *data)
3354 return ACPI_COMPANION(dev) == data;
3357 static struct spi_master *acpi_spi_find_master_by_adev(struct acpi_device *adev)
3359 struct device *dev;
3361 dev = class_find_device(&spi_master_class, NULL, adev,
3362 spi_acpi_master_match);
3363 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3364 dev = class_find_device(&spi_slave_class, NULL, adev,
3365 spi_acpi_master_match);
3366 if (!dev)
3367 return NULL;
3369 return container_of(dev, struct spi_master, dev);
3372 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
3374 struct device *dev;
3376 dev = bus_find_device(&spi_bus_type, NULL, adev, spi_acpi_device_match);
3378 return dev ? to_spi_device(dev) : NULL;
3381 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
3382 void *arg)
3384 struct acpi_device *adev = arg;
3385 struct spi_master *master;
3386 struct spi_device *spi;
3388 switch (value) {
3389 case ACPI_RECONFIG_DEVICE_ADD:
3390 master = acpi_spi_find_master_by_adev(adev->parent);
3391 if (!master)
3392 break;
3394 acpi_register_spi_device(master, adev);
3395 put_device(&master->dev);
3396 break;
3397 case ACPI_RECONFIG_DEVICE_REMOVE:
3398 if (!acpi_device_enumerated(adev))
3399 break;
3401 spi = acpi_spi_find_device_by_adev(adev);
3402 if (!spi)
3403 break;
3405 spi_unregister_device(spi);
3406 put_device(&spi->dev);
3407 break;
3410 return NOTIFY_OK;
3413 static struct notifier_block spi_acpi_notifier = {
3414 .notifier_call = acpi_spi_notify,
3416 #else
3417 extern struct notifier_block spi_acpi_notifier;
3418 #endif
3420 static int __init spi_init(void)
3422 int status;
3424 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
3425 if (!buf) {
3426 status = -ENOMEM;
3427 goto err0;
3430 status = bus_register(&spi_bus_type);
3431 if (status < 0)
3432 goto err1;
3434 status = class_register(&spi_master_class);
3435 if (status < 0)
3436 goto err2;
3438 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
3439 status = class_register(&spi_slave_class);
3440 if (status < 0)
3441 goto err3;
3444 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
3445 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
3446 if (IS_ENABLED(CONFIG_ACPI))
3447 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
3449 return 0;
3451 err3:
3452 class_unregister(&spi_master_class);
3453 err2:
3454 bus_unregister(&spi_bus_type);
3455 err1:
3456 kfree(buf);
3457 buf = NULL;
3458 err0:
3459 return status;
3462 /* board_info is normally registered in arch_initcall(),
3463 * but even essential drivers wait till later
3465 * REVISIT only boardinfo really needs static linking. the rest (device and
3466 * driver registration) _could_ be dynamically linked (modular) ... costs
3467 * include needing to have boardinfo data structures be much more public.
3469 postcore_initcall(spi_init);