blob: a7c35989fc156c226fcc54416e234d7a126ff97a [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0-or-later
2// SPI init/core code
3//
4// Copyright (C) 2005 David Brownell
5// Copyright (C) 2008 Secret Lab Technologies Ltd.
6
7#include <linux/kernel.h>
8#include <linux/device.h>
9#include <linux/init.h>
10#include <linux/cache.h>
11#include <linux/dma-mapping.h>
12#include <linux/dmaengine.h>
13#include <linux/mutex.h>
14#include <linux/of_device.h>
15#include <linux/of_irq.h>
16#include <linux/clk/clk-conf.h>
17#include <linux/slab.h>
18#include <linux/mod_devicetable.h>
19#include <linux/spi/spi.h>
20#include <linux/spi/spi-mem.h>
21#include <linux/of_gpio.h>
22#include <linux/gpio/consumer.h>
23#include <linux/pm_runtime.h>
24#include <linux/pm_domain.h>
25#include <linux/property.h>
26#include <linux/export.h>
27#include <linux/sched/rt.h>
28#include <uapi/linux/sched/types.h>
29#include <linux/delay.h>
30#include <linux/kthread.h>
31#include <linux/ioport.h>
32#include <linux/acpi.h>
33#include <linux/highmem.h>
34#include <linux/idr.h>
35#include <linux/platform_data/x86/apple.h>
36
37#define CREATE_TRACE_POINTS
38#include <trace/events/spi.h>
39EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
41
42#include "internals.h"
43
44static DEFINE_IDR(spi_master_idr);
45
46static void spidev_release(struct device *dev)
47{
48 struct spi_device *spi = to_spi_device(dev);
49
50 spi_controller_put(spi->controller);
51 kfree(spi->driver_override);
52 kfree(spi);
53}
54
55static ssize_t
56modalias_show(struct device *dev, struct device_attribute *a, char *buf)
57{
58 const struct spi_device *spi = to_spi_device(dev);
59 int len;
60
61 len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
62 if (len != -ENODEV)
63 return len;
64
65 return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
66}
67static DEVICE_ATTR_RO(modalias);
68
69static ssize_t driver_override_store(struct device *dev,
70 struct device_attribute *a,
71 const char *buf, size_t count)
72{
73 struct spi_device *spi = to_spi_device(dev);
74 const char *end = memchr(buf, '\n', count);
75 const size_t len = end ? end - buf : count;
76 const char *driver_override, *old;
77
78 /* We need to keep extra room for a newline when displaying value */
79 if (len >= (PAGE_SIZE - 1))
80 return -EINVAL;
81
82 driver_override = kstrndup(buf, len, GFP_KERNEL);
83 if (!driver_override)
84 return -ENOMEM;
85
86 device_lock(dev);
87 old = spi->driver_override;
88 if (len) {
89 spi->driver_override = driver_override;
90 } else {
91 /* Emptry string, disable driver override */
92 spi->driver_override = NULL;
93 kfree(driver_override);
94 }
95 device_unlock(dev);
96 kfree(old);
97
98 return count;
99}
100
101static ssize_t driver_override_show(struct device *dev,
102 struct device_attribute *a, char *buf)
103{
104 const struct spi_device *spi = to_spi_device(dev);
105 ssize_t len;
106
107 device_lock(dev);
108 len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
109 device_unlock(dev);
110 return len;
111}
112static DEVICE_ATTR_RW(driver_override);
113
114#define SPI_STATISTICS_ATTRS(field, file) \
115static ssize_t spi_controller_##field##_show(struct device *dev, \
116 struct device_attribute *attr, \
117 char *buf) \
118{ \
119 struct spi_controller *ctlr = container_of(dev, \
120 struct spi_controller, dev); \
121 return spi_statistics_##field##_show(&ctlr->statistics, buf); \
122} \
123static struct device_attribute dev_attr_spi_controller_##field = { \
124 .attr = { .name = file, .mode = 0444 }, \
125 .show = spi_controller_##field##_show, \
126}; \
127static ssize_t spi_device_##field##_show(struct device *dev, \
128 struct device_attribute *attr, \
129 char *buf) \
130{ \
131 struct spi_device *spi = to_spi_device(dev); \
132 return spi_statistics_##field##_show(&spi->statistics, buf); \
133} \
134static struct device_attribute dev_attr_spi_device_##field = { \
135 .attr = { .name = file, .mode = 0444 }, \
136 .show = spi_device_##field##_show, \
137}
138
139#define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
140static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
141 char *buf) \
142{ \
143 unsigned long flags; \
144 ssize_t len; \
145 spin_lock_irqsave(&stat->lock, flags); \
146 len = sprintf(buf, format_string, stat->field); \
147 spin_unlock_irqrestore(&stat->lock, flags); \
148 return len; \
149} \
150SPI_STATISTICS_ATTRS(name, file)
151
152#define SPI_STATISTICS_SHOW(field, format_string) \
153 SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
154 field, format_string)
155
156SPI_STATISTICS_SHOW(messages, "%lu");
157SPI_STATISTICS_SHOW(transfers, "%lu");
158SPI_STATISTICS_SHOW(errors, "%lu");
159SPI_STATISTICS_SHOW(timedout, "%lu");
160
161SPI_STATISTICS_SHOW(spi_sync, "%lu");
162SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
163SPI_STATISTICS_SHOW(spi_async, "%lu");
164
165SPI_STATISTICS_SHOW(bytes, "%llu");
166SPI_STATISTICS_SHOW(bytes_rx, "%llu");
167SPI_STATISTICS_SHOW(bytes_tx, "%llu");
168
169#define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
170 SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
171 "transfer_bytes_histo_" number, \
172 transfer_bytes_histo[index], "%lu")
173SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
174SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
175SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
176SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
177SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
178SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
179SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
180SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
181SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
182SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
183SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
184SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
185SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
186SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
187SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
188SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
189SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
190
191SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
192
193static struct attribute *spi_dev_attrs[] = {
194 &dev_attr_modalias.attr,
195 &dev_attr_driver_override.attr,
196 NULL,
197};
198
199static const struct attribute_group spi_dev_group = {
200 .attrs = spi_dev_attrs,
201};
202
203static struct attribute *spi_device_statistics_attrs[] = {
204 &dev_attr_spi_device_messages.attr,
205 &dev_attr_spi_device_transfers.attr,
206 &dev_attr_spi_device_errors.attr,
207 &dev_attr_spi_device_timedout.attr,
208 &dev_attr_spi_device_spi_sync.attr,
209 &dev_attr_spi_device_spi_sync_immediate.attr,
210 &dev_attr_spi_device_spi_async.attr,
211 &dev_attr_spi_device_bytes.attr,
212 &dev_attr_spi_device_bytes_rx.attr,
213 &dev_attr_spi_device_bytes_tx.attr,
214 &dev_attr_spi_device_transfer_bytes_histo0.attr,
215 &dev_attr_spi_device_transfer_bytes_histo1.attr,
216 &dev_attr_spi_device_transfer_bytes_histo2.attr,
217 &dev_attr_spi_device_transfer_bytes_histo3.attr,
218 &dev_attr_spi_device_transfer_bytes_histo4.attr,
219 &dev_attr_spi_device_transfer_bytes_histo5.attr,
220 &dev_attr_spi_device_transfer_bytes_histo6.attr,
221 &dev_attr_spi_device_transfer_bytes_histo7.attr,
222 &dev_attr_spi_device_transfer_bytes_histo8.attr,
223 &dev_attr_spi_device_transfer_bytes_histo9.attr,
224 &dev_attr_spi_device_transfer_bytes_histo10.attr,
225 &dev_attr_spi_device_transfer_bytes_histo11.attr,
226 &dev_attr_spi_device_transfer_bytes_histo12.attr,
227 &dev_attr_spi_device_transfer_bytes_histo13.attr,
228 &dev_attr_spi_device_transfer_bytes_histo14.attr,
229 &dev_attr_spi_device_transfer_bytes_histo15.attr,
230 &dev_attr_spi_device_transfer_bytes_histo16.attr,
231 &dev_attr_spi_device_transfers_split_maxsize.attr,
232 NULL,
233};
234
235static const struct attribute_group spi_device_statistics_group = {
236 .name = "statistics",
237 .attrs = spi_device_statistics_attrs,
238};
239
240static const struct attribute_group *spi_dev_groups[] = {
241 &spi_dev_group,
242 &spi_device_statistics_group,
243 NULL,
244};
245
246static struct attribute *spi_controller_statistics_attrs[] = {
247 &dev_attr_spi_controller_messages.attr,
248 &dev_attr_spi_controller_transfers.attr,
249 &dev_attr_spi_controller_errors.attr,
250 &dev_attr_spi_controller_timedout.attr,
251 &dev_attr_spi_controller_spi_sync.attr,
252 &dev_attr_spi_controller_spi_sync_immediate.attr,
253 &dev_attr_spi_controller_spi_async.attr,
254 &dev_attr_spi_controller_bytes.attr,
255 &dev_attr_spi_controller_bytes_rx.attr,
256 &dev_attr_spi_controller_bytes_tx.attr,
257 &dev_attr_spi_controller_transfer_bytes_histo0.attr,
258 &dev_attr_spi_controller_transfer_bytes_histo1.attr,
259 &dev_attr_spi_controller_transfer_bytes_histo2.attr,
260 &dev_attr_spi_controller_transfer_bytes_histo3.attr,
261 &dev_attr_spi_controller_transfer_bytes_histo4.attr,
262 &dev_attr_spi_controller_transfer_bytes_histo5.attr,
263 &dev_attr_spi_controller_transfer_bytes_histo6.attr,
264 &dev_attr_spi_controller_transfer_bytes_histo7.attr,
265 &dev_attr_spi_controller_transfer_bytes_histo8.attr,
266 &dev_attr_spi_controller_transfer_bytes_histo9.attr,
267 &dev_attr_spi_controller_transfer_bytes_histo10.attr,
268 &dev_attr_spi_controller_transfer_bytes_histo11.attr,
269 &dev_attr_spi_controller_transfer_bytes_histo12.attr,
270 &dev_attr_spi_controller_transfer_bytes_histo13.attr,
271 &dev_attr_spi_controller_transfer_bytes_histo14.attr,
272 &dev_attr_spi_controller_transfer_bytes_histo15.attr,
273 &dev_attr_spi_controller_transfer_bytes_histo16.attr,
274 &dev_attr_spi_controller_transfers_split_maxsize.attr,
275 NULL,
276};
277
278static const struct attribute_group spi_controller_statistics_group = {
279 .name = "statistics",
280 .attrs = spi_controller_statistics_attrs,
281};
282
283static const struct attribute_group *spi_master_groups[] = {
284 &spi_controller_statistics_group,
285 NULL,
286};
287
288void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
289 struct spi_transfer *xfer,
290 struct spi_controller *ctlr)
291{
292 unsigned long flags;
293 int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
294
295 if (l2len < 0)
296 l2len = 0;
297
298 spin_lock_irqsave(&stats->lock, flags);
299
300 stats->transfers++;
301 stats->transfer_bytes_histo[l2len]++;
302
303 stats->bytes += xfer->len;
304 if ((xfer->tx_buf) &&
305 (xfer->tx_buf != ctlr->dummy_tx))
306 stats->bytes_tx += xfer->len;
307 if ((xfer->rx_buf) &&
308 (xfer->rx_buf != ctlr->dummy_rx))
309 stats->bytes_rx += xfer->len;
310
311 spin_unlock_irqrestore(&stats->lock, flags);
312}
313EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
314
315/* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
316 * and the sysfs version makes coldplug work too.
317 */
318
319static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
320 const struct spi_device *sdev)
321{
322 while (id->name[0]) {
323 if (!strcmp(sdev->modalias, id->name))
324 return id;
325 id++;
326 }
327 return NULL;
328}
329
330const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
331{
332 const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
333
334 return spi_match_id(sdrv->id_table, sdev);
335}
336EXPORT_SYMBOL_GPL(spi_get_device_id);
337
338static int spi_match_device(struct device *dev, struct device_driver *drv)
339{
340 const struct spi_device *spi = to_spi_device(dev);
341 const struct spi_driver *sdrv = to_spi_driver(drv);
342
343 /* Check override first, and if set, only use the named driver */
344 if (spi->driver_override)
345 return strcmp(spi->driver_override, drv->name) == 0;
346
347 /* Attempt an OF style match */
348 if (of_driver_match_device(dev, drv))
349 return 1;
350
351 /* Then try ACPI */
352 if (acpi_driver_match_device(dev, drv))
353 return 1;
354
355 if (sdrv->id_table)
356 return !!spi_match_id(sdrv->id_table, spi);
357
358 return strcmp(spi->modalias, drv->name) == 0;
359}
360
361static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
362{
363 const struct spi_device *spi = to_spi_device(dev);
364 int rc;
365
366 rc = acpi_device_uevent_modalias(dev, env);
367 if (rc != -ENODEV)
368 return rc;
369
370 return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
371}
372
373struct bus_type spi_bus_type = {
374 .name = "spi",
375 .dev_groups = spi_dev_groups,
376 .match = spi_match_device,
377 .uevent = spi_uevent,
378};
379EXPORT_SYMBOL_GPL(spi_bus_type);
380
381
382static int spi_drv_probe(struct device *dev)
383{
384 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
385 struct spi_device *spi = to_spi_device(dev);
386 int ret;
387
388 ret = of_clk_set_defaults(dev->of_node, false);
389 if (ret)
390 return ret;
391
392 if (dev->of_node) {
393 spi->irq = of_irq_get(dev->of_node, 0);
394 if (spi->irq == -EPROBE_DEFER)
395 return -EPROBE_DEFER;
396 if (spi->irq < 0)
397 spi->irq = 0;
398 }
399
400 if (has_acpi_companion(dev) && spi->irq < 0) {
401 struct acpi_device *adev = to_acpi_device_node(dev->fwnode);
402
403 spi->irq = acpi_dev_gpio_irq_get(adev, 0);
404 if (spi->irq == -EPROBE_DEFER)
405 return -EPROBE_DEFER;
406 if (spi->irq < 0)
407 spi->irq = 0;
408 }
409
410 ret = dev_pm_domain_attach(dev, true);
411 if (ret)
412 return ret;
413
414 if (sdrv->probe) {
415 ret = sdrv->probe(spi);
416 if (ret)
417 dev_pm_domain_detach(dev, true);
418 }
419
420 return ret;
421}
422
423static int spi_drv_remove(struct device *dev)
424{
425 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
426 int ret = 0;
427
428 if (sdrv->remove)
429 ret = sdrv->remove(to_spi_device(dev));
430 dev_pm_domain_detach(dev, true);
431
432 return ret;
433}
434
435static void spi_drv_shutdown(struct device *dev)
436{
437 const struct spi_driver *sdrv = to_spi_driver(dev->driver);
438
439 sdrv->shutdown(to_spi_device(dev));
440}
441
442/**
443 * __spi_register_driver - register a SPI driver
444 * @owner: owner module of the driver to register
445 * @sdrv: the driver to register
446 * Context: can sleep
447 *
448 * Return: zero on success, else a negative error code.
449 */
450int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
451{
452 sdrv->driver.owner = owner;
453 sdrv->driver.bus = &spi_bus_type;
454 sdrv->driver.probe = spi_drv_probe;
455 sdrv->driver.remove = spi_drv_remove;
456 if (sdrv->shutdown)
457 sdrv->driver.shutdown = spi_drv_shutdown;
458 return driver_register(&sdrv->driver);
459}
460EXPORT_SYMBOL_GPL(__spi_register_driver);
461
462/*-------------------------------------------------------------------------*/
463
464/* SPI devices should normally not be created by SPI device drivers; that
465 * would make them board-specific. Similarly with SPI controller drivers.
466 * Device registration normally goes into like arch/.../mach.../board-YYY.c
467 * with other readonly (flashable) information about mainboard devices.
468 */
469
470struct boardinfo {
471 struct list_head list;
472 struct spi_board_info board_info;
473};
474
475static LIST_HEAD(board_list);
476static LIST_HEAD(spi_controller_list);
477
478/*
479 * Used to protect add/del opertion for board_info list and
480 * spi_controller list, and their matching process
481 * also used to protect object of type struct idr
482 */
483static DEFINE_MUTEX(board_lock);
484
485/**
486 * spi_alloc_device - Allocate a new SPI device
487 * @ctlr: Controller to which device is connected
488 * Context: can sleep
489 *
490 * Allows a driver to allocate and initialize a spi_device without
491 * registering it immediately. This allows a driver to directly
492 * fill the spi_device with device parameters before calling
493 * spi_add_device() on it.
494 *
495 * Caller is responsible to call spi_add_device() on the returned
496 * spi_device structure to add it to the SPI controller. If the caller
497 * needs to discard the spi_device without adding it, then it should
498 * call spi_dev_put() on it.
499 *
500 * Return: a pointer to the new device, or NULL.
501 */
502struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
503{
504 struct spi_device *spi;
505
506 if (!spi_controller_get(ctlr))
507 return NULL;
508
509 spi = kzalloc(sizeof(*spi), GFP_KERNEL);
510 if (!spi) {
511 spi_controller_put(ctlr);
512 return NULL;
513 }
514
515 spi->master = spi->controller = ctlr;
516 spi->dev.parent = &ctlr->dev;
517 spi->dev.bus = &spi_bus_type;
518 spi->dev.release = spidev_release;
519 spi->cs_gpio = -ENOENT;
520
521 spin_lock_init(&spi->statistics.lock);
522
523 device_initialize(&spi->dev);
524 return spi;
525}
526EXPORT_SYMBOL_GPL(spi_alloc_device);
527
528static void spi_dev_set_name(struct spi_device *spi)
529{
530 struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
531
532 if (adev) {
533 dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
534 return;
535 }
536
537 dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
538 spi->chip_select);
539}
540
541static int spi_dev_check(struct device *dev, void *data)
542{
543 struct spi_device *spi = to_spi_device(dev);
544 struct spi_device *new_spi = data;
545
546 if (spi->controller == new_spi->controller &&
547 spi->chip_select == new_spi->chip_select)
548 return -EBUSY;
549 return 0;
550}
551
552static void spi_cleanup(struct spi_device *spi)
553{
554 if (spi->controller->cleanup)
555 spi->controller->cleanup(spi);
556}
557
558/**
559 * spi_add_device - Add spi_device allocated with spi_alloc_device
560 * @spi: spi_device to register
561 *
562 * Companion function to spi_alloc_device. Devices allocated with
563 * spi_alloc_device can be added onto the spi bus with this function.
564 *
565 * Return: 0 on success; negative errno on failure
566 */
567int spi_add_device(struct spi_device *spi)
568{
569 struct spi_controller *ctlr = spi->controller;
570 struct device *dev = ctlr->dev.parent;
571 int status;
572
573 /* Chipselects are numbered 0..max; validate. */
574 if (spi->chip_select >= ctlr->num_chipselect) {
575 dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
576 ctlr->num_chipselect);
577 return -EINVAL;
578 }
579
580 /* Set the bus ID string */
581 spi_dev_set_name(spi);
582
583 /* We need to make sure there's no other device with this
584 * chipselect **BEFORE** we call setup(), else we'll trash
585 * its configuration. Lock against concurrent add() calls.
586 */
587 mutex_lock(&ctlr->add_lock);
588
589 status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
590 if (status) {
591 dev_err(dev, "chipselect %d already in use\n",
592 spi->chip_select);
593 goto done;
594 }
595
596 /* Controller may unregister concurrently */
597 if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
598 !device_is_registered(&ctlr->dev)) {
599 status = -ENODEV;
600 goto done;
601 }
602
603 /* Descriptors take precedence */
604 if (ctlr->cs_gpiods)
605 spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
606 else if (ctlr->cs_gpios)
607 spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
608
609 /* Drivers may modify this initial i/o setup, but will
610 * normally rely on the device being setup. Devices
611 * using SPI_CS_HIGH can't coexist well otherwise...
612 */
613 status = spi_setup(spi);
614 if (status < 0) {
615 dev_err(dev, "can't setup %s, status %d\n",
616 dev_name(&spi->dev), status);
617 goto done;
618 }
619
620 /* Device may be bound to an active driver when this returns */
621 status = device_add(&spi->dev);
622 if (status < 0) {
623 dev_err(dev, "can't add %s, status %d\n",
624 dev_name(&spi->dev), status);
625 spi_cleanup(spi);
626 } else {
627 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
628 }
629
630done:
631 mutex_unlock(&ctlr->add_lock);
632 return status;
633}
634EXPORT_SYMBOL_GPL(spi_add_device);
635
636/**
637 * spi_new_device - instantiate one new SPI device
638 * @ctlr: Controller to which device is connected
639 * @chip: Describes the SPI device
640 * Context: can sleep
641 *
642 * On typical mainboards, this is purely internal; and it's not needed
643 * after board init creates the hard-wired devices. Some development
644 * platforms may not be able to use spi_register_board_info though, and
645 * this is exported so that for example a USB or parport based adapter
646 * driver could add devices (which it would learn about out-of-band).
647 *
648 * Return: the new device, or NULL.
649 */
650struct spi_device *spi_new_device(struct spi_controller *ctlr,
651 struct spi_board_info *chip)
652{
653 struct spi_device *proxy;
654 int status;
655
656 /* NOTE: caller did any chip->bus_num checks necessary.
657 *
658 * Also, unless we change the return value convention to use
659 * error-or-pointer (not NULL-or-pointer), troubleshootability
660 * suggests syslogged diagnostics are best here (ugh).
661 */
662
663 proxy = spi_alloc_device(ctlr);
664 if (!proxy)
665 return NULL;
666
667 WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
668
669 proxy->chip_select = chip->chip_select;
670 proxy->max_speed_hz = chip->max_speed_hz;
671 proxy->mode = chip->mode;
672 proxy->irq = chip->irq;
673 strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
674 proxy->dev.platform_data = (void *) chip->platform_data;
675 proxy->controller_data = chip->controller_data;
676 proxy->controller_state = NULL;
677
678 if (chip->properties) {
679 status = device_add_properties(&proxy->dev, chip->properties);
680 if (status) {
681 dev_err(&ctlr->dev,
682 "failed to add properties to '%s': %d\n",
683 chip->modalias, status);
684 goto err_dev_put;
685 }
686 }
687
688 status = spi_add_device(proxy);
689 if (status < 0)
690 goto err_remove_props;
691
692 return proxy;
693
694err_remove_props:
695 if (chip->properties)
696 device_remove_properties(&proxy->dev);
697err_dev_put:
698 spi_dev_put(proxy);
699 return NULL;
700}
701EXPORT_SYMBOL_GPL(spi_new_device);
702
703/**
704 * spi_unregister_device - unregister a single SPI device
705 * @spi: spi_device to unregister
706 *
707 * Start making the passed SPI device vanish. Normally this would be handled
708 * by spi_unregister_controller().
709 */
710void spi_unregister_device(struct spi_device *spi)
711{
712 if (!spi)
713 return;
714
715 if (spi->dev.of_node) {
716 of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
717 of_node_put(spi->dev.of_node);
718 }
719 if (ACPI_COMPANION(&spi->dev))
720 acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
721 device_del(&spi->dev);
722 spi_cleanup(spi);
723 put_device(&spi->dev);
724}
725EXPORT_SYMBOL_GPL(spi_unregister_device);
726
727static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
728 struct spi_board_info *bi)
729{
730 struct spi_device *dev;
731
732 if (ctlr->bus_num != bi->bus_num)
733 return;
734
735 dev = spi_new_device(ctlr, bi);
736 if (!dev)
737 dev_err(ctlr->dev.parent, "can't create new device for %s\n",
738 bi->modalias);
739}
740
741/**
742 * spi_register_board_info - register SPI devices for a given board
743 * @info: array of chip descriptors
744 * @n: how many descriptors are provided
745 * Context: can sleep
746 *
747 * Board-specific early init code calls this (probably during arch_initcall)
748 * with segments of the SPI device table. Any device nodes are created later,
749 * after the relevant parent SPI controller (bus_num) is defined. We keep
750 * this table of devices forever, so that reloading a controller driver will
751 * not make Linux forget about these hard-wired devices.
752 *
753 * Other code can also call this, e.g. a particular add-on board might provide
754 * SPI devices through its expansion connector, so code initializing that board
755 * would naturally declare its SPI devices.
756 *
757 * The board info passed can safely be __initdata ... but be careful of
758 * any embedded pointers (platform_data, etc), they're copied as-is.
759 * Device properties are deep-copied though.
760 *
761 * Return: zero on success, else a negative error code.
762 */
763int spi_register_board_info(struct spi_board_info const *info, unsigned n)
764{
765 struct boardinfo *bi;
766 int i;
767
768 if (!n)
769 return 0;
770
771 bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
772 if (!bi)
773 return -ENOMEM;
774
775 for (i = 0; i < n; i++, bi++, info++) {
776 struct spi_controller *ctlr;
777
778 memcpy(&bi->board_info, info, sizeof(*info));
779 if (info->properties) {
780 bi->board_info.properties =
781 property_entries_dup(info->properties);
782 if (IS_ERR(bi->board_info.properties))
783 return PTR_ERR(bi->board_info.properties);
784 }
785
786 mutex_lock(&board_lock);
787 list_add_tail(&bi->list, &board_list);
788 list_for_each_entry(ctlr, &spi_controller_list, list)
789 spi_match_controller_to_boardinfo(ctlr,
790 &bi->board_info);
791 mutex_unlock(&board_lock);
792 }
793
794 return 0;
795}
796
797/*-------------------------------------------------------------------------*/
798
799static void spi_set_cs(struct spi_device *spi, bool enable)
800{
801 if (spi->mode & SPI_CS_HIGH)
802 enable = !enable;
803
804 if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
805 /*
806 * Honour the SPI_NO_CS flag and invert the enable line, as
807 * active low is default for SPI. Execution paths that handle
808 * polarity inversion in gpiolib (such as device tree) will
809 * enforce active high using the SPI_CS_HIGH resulting in a
810 * double inversion through the code above.
811 */
812 if (!(spi->mode & SPI_NO_CS)) {
813 if (spi->cs_gpiod)
814 gpiod_set_value_cansleep(spi->cs_gpiod,
815 !enable);
816 else
817 gpio_set_value_cansleep(spi->cs_gpio, !enable);
818 }
819 /* Some SPI masters need both GPIO CS & slave_select */
820 if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
821 spi->controller->set_cs)
822 spi->controller->set_cs(spi, !enable);
823 } else if (spi->controller->set_cs) {
824 spi->controller->set_cs(spi, !enable);
825 }
826}
827
828#ifdef CONFIG_HAS_DMA
829int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
830 struct sg_table *sgt, void *buf, size_t len,
831 enum dma_data_direction dir)
832{
833 const bool vmalloced_buf = is_vmalloc_addr(buf);
834 unsigned int max_seg_size = dma_get_max_seg_size(dev);
835#ifdef CONFIG_HIGHMEM
836 const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
837 (unsigned long)buf < (PKMAP_BASE +
838 (LAST_PKMAP * PAGE_SIZE)));
839#else
840 const bool kmap_buf = false;
841#endif
842 int desc_len;
843 int sgs;
844 struct page *vm_page;
845 struct scatterlist *sg;
846 void *sg_buf;
847 size_t min;
848 int i, ret;
849
850 if (vmalloced_buf || kmap_buf) {
851 desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
852 sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
853 } else if (virt_addr_valid(buf)) {
854 desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
855 sgs = DIV_ROUND_UP(len, desc_len);
856 } else {
857 return -EINVAL;
858 }
859
860 ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
861 if (ret != 0)
862 return ret;
863
864 sg = &sgt->sgl[0];
865 for (i = 0; i < sgs; i++) {
866
867 if (vmalloced_buf || kmap_buf) {
868 /*
869 * Next scatterlist entry size is the minimum between
870 * the desc_len and the remaining buffer length that
871 * fits in a page.
872 */
873 min = min_t(size_t, desc_len,
874 min_t(size_t, len,
875 PAGE_SIZE - offset_in_page(buf)));
876 if (vmalloced_buf)
877 vm_page = vmalloc_to_page(buf);
878 else
879 vm_page = kmap_to_page(buf);
880 if (!vm_page) {
881 sg_free_table(sgt);
882 return -ENOMEM;
883 }
884 sg_set_page(sg, vm_page,
885 min, offset_in_page(buf));
886 } else {
887 min = min_t(size_t, len, desc_len);
888 sg_buf = buf;
889 sg_set_buf(sg, sg_buf, min);
890 }
891
892 buf += min;
893 len -= min;
894 sg = sg_next(sg);
895 }
896
897 ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
898 if (!ret)
899 ret = -ENOMEM;
900 if (ret < 0) {
901 sg_free_table(sgt);
902 return ret;
903 }
904
905 sgt->nents = ret;
906
907 return 0;
908}
909
910void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
911 struct sg_table *sgt, enum dma_data_direction dir)
912{
913 if (sgt->orig_nents) {
914 dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
915 sg_free_table(sgt);
916 }
917}
918
919static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
920{
921 struct device *tx_dev, *rx_dev;
922 struct spi_transfer *xfer;
923 int ret;
924
925 if (!ctlr->can_dma)
926 return 0;
927
928 if (ctlr->dma_tx)
929 tx_dev = ctlr->dma_tx->device->dev;
930 else
931 tx_dev = ctlr->dev.parent;
932
933 if (ctlr->dma_rx)
934 rx_dev = ctlr->dma_rx->device->dev;
935 else
936 rx_dev = ctlr->dev.parent;
937
938 ret = -ENOMSG;
939 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
940 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
941 continue;
942
943 if (xfer->tx_buf != NULL) {
944 ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
945 (void *)xfer->tx_buf, xfer->len,
946 DMA_TO_DEVICE);
947 if (ret != 0)
948 return ret;
949 }
950
951 if (xfer->rx_buf != NULL) {
952 ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
953 xfer->rx_buf, xfer->len,
954 DMA_FROM_DEVICE);
955 if (ret != 0) {
956 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
957 DMA_TO_DEVICE);
958 return ret;
959 }
960 }
961 }
962 /* No transfer has been mapped, bail out with success */
963 if (ret)
964 return 0;
965
966 ctlr->cur_msg_mapped = true;
967
968 return 0;
969}
970
971static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
972{
973 struct spi_transfer *xfer;
974 struct device *tx_dev, *rx_dev;
975
976 if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
977 return 0;
978
979 if (ctlr->dma_tx)
980 tx_dev = ctlr->dma_tx->device->dev;
981 else
982 tx_dev = ctlr->dev.parent;
983
984 if (ctlr->dma_rx)
985 rx_dev = ctlr->dma_rx->device->dev;
986 else
987 rx_dev = ctlr->dev.parent;
988
989 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
990 if (!ctlr->can_dma(ctlr, msg->spi, xfer))
991 continue;
992
993 spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
994 spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
995 }
996
997 return 0;
998}
999#else /* !CONFIG_HAS_DMA */
1000static inline int __spi_map_msg(struct spi_controller *ctlr,
1001 struct spi_message *msg)
1002{
1003 return 0;
1004}
1005
1006static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1007 struct spi_message *msg)
1008{
1009 return 0;
1010}
1011#endif /* !CONFIG_HAS_DMA */
1012
1013static inline int spi_unmap_msg(struct spi_controller *ctlr,
1014 struct spi_message *msg)
1015{
1016 struct spi_transfer *xfer;
1017
1018 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1019 /*
1020 * Restore the original value of tx_buf or rx_buf if they are
1021 * NULL.
1022 */
1023 if (xfer->tx_buf == ctlr->dummy_tx)
1024 xfer->tx_buf = NULL;
1025 if (xfer->rx_buf == ctlr->dummy_rx)
1026 xfer->rx_buf = NULL;
1027 }
1028
1029 return __spi_unmap_msg(ctlr, msg);
1030}
1031
1032static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1033{
1034 struct spi_transfer *xfer;
1035 void *tmp;
1036 unsigned int max_tx, max_rx;
1037
1038 if (ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX)) {
1039 max_tx = 0;
1040 max_rx = 0;
1041
1042 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1043 if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1044 !xfer->tx_buf)
1045 max_tx = max(xfer->len, max_tx);
1046 if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1047 !xfer->rx_buf)
1048 max_rx = max(xfer->len, max_rx);
1049 }
1050
1051 if (max_tx) {
1052 tmp = krealloc(ctlr->dummy_tx, max_tx,
1053 GFP_KERNEL | GFP_DMA);
1054 if (!tmp)
1055 return -ENOMEM;
1056 ctlr->dummy_tx = tmp;
1057 memset(tmp, 0, max_tx);
1058 }
1059
1060 if (max_rx) {
1061 tmp = krealloc(ctlr->dummy_rx, max_rx,
1062 GFP_KERNEL | GFP_DMA);
1063 if (!tmp)
1064 return -ENOMEM;
1065 ctlr->dummy_rx = tmp;
1066 }
1067
1068 if (max_tx || max_rx) {
1069 list_for_each_entry(xfer, &msg->transfers,
1070 transfer_list) {
1071 if (!xfer->len)
1072 continue;
1073 if (!xfer->tx_buf)
1074 xfer->tx_buf = ctlr->dummy_tx;
1075 if (!xfer->rx_buf)
1076 xfer->rx_buf = ctlr->dummy_rx;
1077 }
1078 }
1079 }
1080
1081 return __spi_map_msg(ctlr, msg);
1082}
1083
1084static int spi_transfer_wait(struct spi_controller *ctlr,
1085 struct spi_message *msg,
1086 struct spi_transfer *xfer)
1087{
1088 struct spi_statistics *statm = &ctlr->statistics;
1089 struct spi_statistics *stats = &msg->spi->statistics;
1090 unsigned long long ms = 1;
1091
1092 if (spi_controller_is_slave(ctlr)) {
1093 if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1094 dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1095 return -EINTR;
1096 }
1097 } else {
1098 ms = 8LL * 1000LL * xfer->len;
1099 do_div(ms, xfer->speed_hz);
1100 ms += ms + 200; /* some tolerance */
1101
1102 if (ms > UINT_MAX)
1103 ms = UINT_MAX;
1104
1105 ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1106 msecs_to_jiffies(ms));
1107
1108 if (ms == 0) {
1109 SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1110 SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1111 dev_err(&msg->spi->dev,
1112 "SPI transfer timed out\n");
1113 return -ETIMEDOUT;
1114 }
1115 }
1116
1117 return 0;
1118}
1119
1120static void _spi_transfer_delay_ns(u32 ns)
1121{
1122 if (!ns)
1123 return;
1124 if (ns <= 1000) {
1125 ndelay(ns);
1126 } else {
1127 u32 us = DIV_ROUND_UP(ns, 1000);
1128
1129 if (us <= 10)
1130 udelay(us);
1131 else
1132 usleep_range(us, us + DIV_ROUND_UP(us, 10));
1133 }
1134}
1135
1136static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1137 struct spi_transfer *xfer)
1138{
1139 u32 delay = xfer->cs_change_delay;
1140 u32 unit = xfer->cs_change_delay_unit;
1141 u32 hz;
1142
1143 /* return early on "fast" mode - for everything but USECS */
1144 if (!delay && unit != SPI_DELAY_UNIT_USECS)
1145 return;
1146
1147 switch (unit) {
1148 case SPI_DELAY_UNIT_USECS:
1149 /* for compatibility use default of 10us */
1150 if (!delay)
1151 delay = 10000;
1152 else
1153 delay *= 1000;
1154 break;
1155 case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1156 break;
1157 case SPI_DELAY_UNIT_SCK:
1158 /* if there is no effective speed know, then approximate
1159 * by underestimating with half the requested hz
1160 */
1161 hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1162 delay *= DIV_ROUND_UP(1000000000, hz);
1163 break;
1164 default:
1165 dev_err_once(&msg->spi->dev,
1166 "Use of unsupported delay unit %i, using default of 10us\n",
1167 xfer->cs_change_delay_unit);
1168 delay = 10000;
1169 }
1170 /* now sleep for the requested amount of time */
1171 _spi_transfer_delay_ns(delay);
1172}
1173
1174/*
1175 * spi_transfer_one_message - Default implementation of transfer_one_message()
1176 *
1177 * This is a standard implementation of transfer_one_message() for
1178 * drivers which implement a transfer_one() operation. It provides
1179 * standard handling of delays and chip select management.
1180 */
1181static int spi_transfer_one_message(struct spi_controller *ctlr,
1182 struct spi_message *msg)
1183{
1184 struct spi_transfer *xfer;
1185 bool keep_cs = false;
1186 int ret = 0;
1187 struct spi_statistics *statm = &ctlr->statistics;
1188 struct spi_statistics *stats = &msg->spi->statistics;
1189
1190 spi_set_cs(msg->spi, true);
1191
1192 SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1193 SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1194
1195 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1196 trace_spi_transfer_start(msg, xfer);
1197
1198 spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1199 spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1200
1201 if (xfer->tx_buf || xfer->rx_buf) {
1202 reinit_completion(&ctlr->xfer_completion);
1203
1204 ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1205 if (ret < 0) {
1206 SPI_STATISTICS_INCREMENT_FIELD(statm,
1207 errors);
1208 SPI_STATISTICS_INCREMENT_FIELD(stats,
1209 errors);
1210 dev_err(&msg->spi->dev,
1211 "SPI transfer failed: %d\n", ret);
1212 goto out;
1213 }
1214
1215 if (ret > 0) {
1216 ret = spi_transfer_wait(ctlr, msg, xfer);
1217 if (ret < 0)
1218 msg->status = ret;
1219 }
1220 } else {
1221 if (xfer->len)
1222 dev_err(&msg->spi->dev,
1223 "Bufferless transfer has length %u\n",
1224 xfer->len);
1225 }
1226
1227 trace_spi_transfer_stop(msg, xfer);
1228
1229 if (msg->status != -EINPROGRESS)
1230 goto out;
1231
1232 if (xfer->delay_usecs)
1233 _spi_transfer_delay_ns(xfer->delay_usecs * 1000);
1234
1235 if (xfer->cs_change) {
1236 if (list_is_last(&xfer->transfer_list,
1237 &msg->transfers)) {
1238 keep_cs = true;
1239 } else {
1240 spi_set_cs(msg->spi, false);
1241 _spi_transfer_cs_change_delay(msg, xfer);
1242 spi_set_cs(msg->spi, true);
1243 }
1244 }
1245
1246 msg->actual_length += xfer->len;
1247 }
1248
1249out:
1250 if (ret != 0 || !keep_cs)
1251 spi_set_cs(msg->spi, false);
1252
1253 if (msg->status == -EINPROGRESS)
1254 msg->status = ret;
1255
1256 if (msg->status && ctlr->handle_err)
1257 ctlr->handle_err(ctlr, msg);
1258
1259 spi_finalize_current_message(ctlr);
1260
1261 return ret;
1262}
1263
1264/**
1265 * spi_finalize_current_transfer - report completion of a transfer
1266 * @ctlr: the controller reporting completion
1267 *
1268 * Called by SPI drivers using the core transfer_one_message()
1269 * implementation to notify it that the current interrupt driven
1270 * transfer has finished and the next one may be scheduled.
1271 */
1272void spi_finalize_current_transfer(struct spi_controller *ctlr)
1273{
1274 complete(&ctlr->xfer_completion);
1275}
1276EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1277
1278/**
1279 * __spi_pump_messages - function which processes spi message queue
1280 * @ctlr: controller to process queue for
1281 * @in_kthread: true if we are in the context of the message pump thread
1282 *
1283 * This function checks if there is any spi message in the queue that
1284 * needs processing and if so call out to the driver to initialize hardware
1285 * and transfer each message.
1286 *
1287 * Note that it is called both from the kthread itself and also from
1288 * inside spi_sync(); the queue extraction handling at the top of the
1289 * function should deal with this safely.
1290 */
1291static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1292{
1293 struct spi_message *msg;
1294 bool was_busy = false;
1295 unsigned long flags;
1296 int ret;
1297
1298 /* Lock queue */
1299 spin_lock_irqsave(&ctlr->queue_lock, flags);
1300
1301 /* Make sure we are not already running a message */
1302 if (ctlr->cur_msg) {
1303 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1304 return;
1305 }
1306
1307 /* If another context is idling the device then defer */
1308 if (ctlr->idling) {
1309 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1310 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1311 return;
1312 }
1313
1314 /* Check if the queue is idle */
1315 if (list_empty(&ctlr->queue) || !ctlr->running) {
1316 if (!ctlr->busy) {
1317 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1318 return;
1319 }
1320
1321 /* Only do teardown in the thread */
1322 if (!in_kthread) {
1323 kthread_queue_work(&ctlr->kworker,
1324 &ctlr->pump_messages);
1325 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1326 return;
1327 }
1328
1329 ctlr->busy = false;
1330 ctlr->idling = true;
1331 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1332
1333 kfree(ctlr->dummy_rx);
1334 ctlr->dummy_rx = NULL;
1335 kfree(ctlr->dummy_tx);
1336 ctlr->dummy_tx = NULL;
1337 if (ctlr->unprepare_transfer_hardware &&
1338 ctlr->unprepare_transfer_hardware(ctlr))
1339 dev_err(&ctlr->dev,
1340 "failed to unprepare transfer hardware\n");
1341 if (ctlr->auto_runtime_pm) {
1342 pm_runtime_mark_last_busy(ctlr->dev.parent);
1343 pm_runtime_put_autosuspend(ctlr->dev.parent);
1344 }
1345 trace_spi_controller_idle(ctlr);
1346
1347 spin_lock_irqsave(&ctlr->queue_lock, flags);
1348 ctlr->idling = false;
1349 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1350 return;
1351 }
1352
1353 /* Extract head of queue */
1354 msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1355 ctlr->cur_msg = msg;
1356
1357 list_del_init(&msg->queue);
1358 if (ctlr->busy)
1359 was_busy = true;
1360 else
1361 ctlr->busy = true;
1362 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1363
1364 mutex_lock(&ctlr->io_mutex);
1365
1366 if (!was_busy && ctlr->auto_runtime_pm) {
1367 ret = pm_runtime_get_sync(ctlr->dev.parent);
1368 if (ret < 0) {
1369 pm_runtime_put_noidle(ctlr->dev.parent);
1370 dev_err(&ctlr->dev, "Failed to power device: %d\n",
1371 ret);
1372 mutex_unlock(&ctlr->io_mutex);
1373 return;
1374 }
1375 }
1376
1377 if (!was_busy)
1378 trace_spi_controller_busy(ctlr);
1379
1380 if (!was_busy && ctlr->prepare_transfer_hardware) {
1381 ret = ctlr->prepare_transfer_hardware(ctlr);
1382 if (ret) {
1383 dev_err(&ctlr->dev,
1384 "failed to prepare transfer hardware: %d\n",
1385 ret);
1386
1387 if (ctlr->auto_runtime_pm)
1388 pm_runtime_put(ctlr->dev.parent);
1389
1390 msg->status = ret;
1391 spi_finalize_current_message(ctlr);
1392
1393 mutex_unlock(&ctlr->io_mutex);
1394 return;
1395 }
1396 }
1397
1398 trace_spi_message_start(msg);
1399
1400 if (ctlr->prepare_message) {
1401 ret = ctlr->prepare_message(ctlr, msg);
1402 if (ret) {
1403 dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1404 ret);
1405 msg->status = ret;
1406 spi_finalize_current_message(ctlr);
1407 goto out;
1408 }
1409 ctlr->cur_msg_prepared = true;
1410 }
1411
1412 ret = spi_map_msg(ctlr, msg);
1413 if (ret) {
1414 msg->status = ret;
1415 spi_finalize_current_message(ctlr);
1416 goto out;
1417 }
1418
1419 ret = ctlr->transfer_one_message(ctlr, msg);
1420 if (ret) {
1421 dev_err(&ctlr->dev,
1422 "failed to transfer one message from queue\n");
1423 goto out;
1424 }
1425
1426out:
1427 mutex_unlock(&ctlr->io_mutex);
1428
1429 /* Prod the scheduler in case transfer_one() was busy waiting */
1430 if (!ret)
1431 cond_resched();
1432}
1433
1434/**
1435 * spi_pump_messages - kthread work function which processes spi message queue
1436 * @work: pointer to kthread work struct contained in the controller struct
1437 */
1438static void spi_pump_messages(struct kthread_work *work)
1439{
1440 struct spi_controller *ctlr =
1441 container_of(work, struct spi_controller, pump_messages);
1442
1443 __spi_pump_messages(ctlr, true);
1444}
1445
1446/**
1447 * spi_set_thread_rt - set the controller to pump at realtime priority
1448 * @ctlr: controller to boost priority of
1449 *
1450 * This can be called because the controller requested realtime priority
1451 * (by setting the ->rt value before calling spi_register_controller()) or
1452 * because a device on the bus said that its transfers needed realtime
1453 * priority.
1454 *
1455 * NOTE: at the moment if any device on a bus says it needs realtime then
1456 * the thread will be at realtime priority for all transfers on that
1457 * controller. If this eventually becomes a problem we may see if we can
1458 * find a way to boost the priority only temporarily during relevant
1459 * transfers.
1460 */
1461static void spi_set_thread_rt(struct spi_controller *ctlr)
1462{
1463 struct sched_param param = { .sched_priority = MAX_RT_PRIO / 2 };
1464
1465 dev_info(&ctlr->dev,
1466 "will run message pump with realtime priority\n");
1467 sched_setscheduler(ctlr->kworker_task, SCHED_FIFO, &param);
1468}
1469
1470static int spi_init_queue(struct spi_controller *ctlr)
1471{
1472 ctlr->running = false;
1473 ctlr->busy = false;
1474
1475 kthread_init_worker(&ctlr->kworker);
1476 ctlr->kworker_task = kthread_run(kthread_worker_fn, &ctlr->kworker,
1477 "%s", dev_name(&ctlr->dev));
1478 if (IS_ERR(ctlr->kworker_task)) {
1479 dev_err(&ctlr->dev, "failed to create message pump task\n");
1480 return PTR_ERR(ctlr->kworker_task);
1481 }
1482 kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1483
1484 /*
1485 * Controller config will indicate if this controller should run the
1486 * message pump with high (realtime) priority to reduce the transfer
1487 * latency on the bus by minimising the delay between a transfer
1488 * request and the scheduling of the message pump thread. Without this
1489 * setting the message pump thread will remain at default priority.
1490 */
1491 if (ctlr->rt)
1492 spi_set_thread_rt(ctlr);
1493
1494 return 0;
1495}
1496
1497/**
1498 * spi_get_next_queued_message() - called by driver to check for queued
1499 * messages
1500 * @ctlr: the controller to check for queued messages
1501 *
1502 * If there are more messages in the queue, the next message is returned from
1503 * this call.
1504 *
1505 * Return: the next message in the queue, else NULL if the queue is empty.
1506 */
1507struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1508{
1509 struct spi_message *next;
1510 unsigned long flags;
1511
1512 /* get a pointer to the next message, if any */
1513 spin_lock_irqsave(&ctlr->queue_lock, flags);
1514 next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1515 queue);
1516 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1517
1518 return next;
1519}
1520EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1521
1522/**
1523 * spi_finalize_current_message() - the current message is complete
1524 * @ctlr: the controller to return the message to
1525 *
1526 * Called by the driver to notify the core that the message in the front of the
1527 * queue is complete and can be removed from the queue.
1528 */
1529void spi_finalize_current_message(struct spi_controller *ctlr)
1530{
1531 struct spi_message *mesg;
1532 unsigned long flags;
1533 int ret;
1534
1535 spin_lock_irqsave(&ctlr->queue_lock, flags);
1536 mesg = ctlr->cur_msg;
1537 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1538
1539 spi_unmap_msg(ctlr, mesg);
1540
1541 /* In the prepare_messages callback the spi bus has the opportunity to
1542 * split a transfer to smaller chunks.
1543 * Release splited transfers here since spi_map_msg is done on the
1544 * splited transfers.
1545 */
1546 spi_res_release(ctlr, mesg);
1547
1548 if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1549 ret = ctlr->unprepare_message(ctlr, mesg);
1550 if (ret) {
1551 dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1552 ret);
1553 }
1554 }
1555
1556 spin_lock_irqsave(&ctlr->queue_lock, flags);
1557 ctlr->cur_msg = NULL;
1558 ctlr->cur_msg_prepared = false;
1559 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1560 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1561
1562 trace_spi_message_done(mesg);
1563
1564 mesg->state = NULL;
1565 if (mesg->complete)
1566 mesg->complete(mesg->context);
1567}
1568EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1569
1570static int spi_start_queue(struct spi_controller *ctlr)
1571{
1572 unsigned long flags;
1573
1574 spin_lock_irqsave(&ctlr->queue_lock, flags);
1575
1576 if (ctlr->running || ctlr->busy) {
1577 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1578 return -EBUSY;
1579 }
1580
1581 ctlr->running = true;
1582 ctlr->cur_msg = NULL;
1583 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1584
1585 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1586
1587 return 0;
1588}
1589
1590static int spi_stop_queue(struct spi_controller *ctlr)
1591{
1592 unsigned long flags;
1593 unsigned limit = 500;
1594 int ret = 0;
1595
1596 spin_lock_irqsave(&ctlr->queue_lock, flags);
1597
1598 /*
1599 * This is a bit lame, but is optimized for the common execution path.
1600 * A wait_queue on the ctlr->busy could be used, but then the common
1601 * execution path (pump_messages) would be required to call wake_up or
1602 * friends on every SPI message. Do this instead.
1603 */
1604 while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1605 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1606 usleep_range(10000, 11000);
1607 spin_lock_irqsave(&ctlr->queue_lock, flags);
1608 }
1609
1610 if (!list_empty(&ctlr->queue) || ctlr->busy)
1611 ret = -EBUSY;
1612 else
1613 ctlr->running = false;
1614
1615 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1616
1617 if (ret) {
1618 dev_warn(&ctlr->dev, "could not stop message queue\n");
1619 return ret;
1620 }
1621 return ret;
1622}
1623
1624static int spi_destroy_queue(struct spi_controller *ctlr)
1625{
1626 int ret;
1627
1628 ret = spi_stop_queue(ctlr);
1629
1630 /*
1631 * kthread_flush_worker will block until all work is done.
1632 * If the reason that stop_queue timed out is that the work will never
1633 * finish, then it does no good to call flush/stop thread, so
1634 * return anyway.
1635 */
1636 if (ret) {
1637 dev_err(&ctlr->dev, "problem destroying queue\n");
1638 return ret;
1639 }
1640
1641 kthread_flush_worker(&ctlr->kworker);
1642 kthread_stop(ctlr->kworker_task);
1643
1644 return 0;
1645}
1646
1647static int __spi_queued_transfer(struct spi_device *spi,
1648 struct spi_message *msg,
1649 bool need_pump)
1650{
1651 struct spi_controller *ctlr = spi->controller;
1652 unsigned long flags;
1653
1654 spin_lock_irqsave(&ctlr->queue_lock, flags);
1655
1656 if (!ctlr->running) {
1657 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1658 return -ESHUTDOWN;
1659 }
1660 msg->actual_length = 0;
1661 msg->status = -EINPROGRESS;
1662
1663 list_add_tail(&msg->queue, &ctlr->queue);
1664 if (!ctlr->busy && need_pump)
1665 kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1666
1667 spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1668 return 0;
1669}
1670
1671/**
1672 * spi_queued_transfer - transfer function for queued transfers
1673 * @spi: spi device which is requesting transfer
1674 * @msg: spi message which is to handled is queued to driver queue
1675 *
1676 * Return: zero on success, else a negative error code.
1677 */
1678static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1679{
1680 return __spi_queued_transfer(spi, msg, true);
1681}
1682
1683static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1684{
1685 int ret;
1686
1687 ctlr->transfer = spi_queued_transfer;
1688 if (!ctlr->transfer_one_message)
1689 ctlr->transfer_one_message = spi_transfer_one_message;
1690
1691 /* Initialize and start queue */
1692 ret = spi_init_queue(ctlr);
1693 if (ret) {
1694 dev_err(&ctlr->dev, "problem initializing queue\n");
1695 goto err_init_queue;
1696 }
1697 ctlr->queued = true;
1698 ret = spi_start_queue(ctlr);
1699 if (ret) {
1700 dev_err(&ctlr->dev, "problem starting queue\n");
1701 goto err_start_queue;
1702 }
1703
1704 return 0;
1705
1706err_start_queue:
1707 spi_destroy_queue(ctlr);
1708err_init_queue:
1709 return ret;
1710}
1711
1712/**
1713 * spi_flush_queue - Send all pending messages in the queue from the callers'
1714 * context
1715 * @ctlr: controller to process queue for
1716 *
1717 * This should be used when one wants to ensure all pending messages have been
1718 * sent before doing something. Is used by the spi-mem code to make sure SPI
1719 * memory operations do not preempt regular SPI transfers that have been queued
1720 * before the spi-mem operation.
1721 */
1722void spi_flush_queue(struct spi_controller *ctlr)
1723{
1724 if (ctlr->transfer == spi_queued_transfer)
1725 __spi_pump_messages(ctlr, false);
1726}
1727
1728/*-------------------------------------------------------------------------*/
1729
1730#if defined(CONFIG_OF)
1731static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1732 struct device_node *nc)
1733{
1734 u32 value;
1735 int rc;
1736
1737 /* Mode (clock phase/polarity/etc.) */
1738 if (of_property_read_bool(nc, "spi-cpha"))
1739 spi->mode |= SPI_CPHA;
1740 if (of_property_read_bool(nc, "spi-cpol"))
1741 spi->mode |= SPI_CPOL;
1742 if (of_property_read_bool(nc, "spi-3wire"))
1743 spi->mode |= SPI_3WIRE;
1744 if (of_property_read_bool(nc, "spi-lsb-first"))
1745 spi->mode |= SPI_LSB_FIRST;
1746 if (of_property_read_bool(nc, "spi-cs-high"))
1747 spi->mode |= SPI_CS_HIGH;
1748
1749 /* Device DUAL/QUAD mode */
1750 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1751 switch (value) {
1752 case 1:
1753 break;
1754 case 2:
1755 spi->mode |= SPI_TX_DUAL;
1756 break;
1757 case 4:
1758 spi->mode |= SPI_TX_QUAD;
1759 break;
1760 case 8:
1761 spi->mode |= SPI_TX_OCTAL;
1762 break;
1763 default:
1764 dev_warn(&ctlr->dev,
1765 "spi-tx-bus-width %d not supported\n",
1766 value);
1767 break;
1768 }
1769 }
1770
1771 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1772 switch (value) {
1773 case 1:
1774 break;
1775 case 2:
1776 spi->mode |= SPI_RX_DUAL;
1777 break;
1778 case 4:
1779 spi->mode |= SPI_RX_QUAD;
1780 break;
1781 case 8:
1782 spi->mode |= SPI_RX_OCTAL;
1783 break;
1784 default:
1785 dev_warn(&ctlr->dev,
1786 "spi-rx-bus-width %d not supported\n",
1787 value);
1788 break;
1789 }
1790 }
1791
1792 if (spi_controller_is_slave(ctlr)) {
1793 if (!of_node_name_eq(nc, "slave")) {
1794 dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
1795 nc);
1796 return -EINVAL;
1797 }
1798 return 0;
1799 }
1800
1801 /* Device address */
1802 rc = of_property_read_u32(nc, "reg", &value);
1803 if (rc) {
1804 dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
1805 nc, rc);
1806 return rc;
1807 }
1808 spi->chip_select = value;
1809
1810 /*
1811 * For descriptors associated with the device, polarity inversion is
1812 * handled in the gpiolib, so all gpio chip selects are "active high"
1813 * in the logical sense, the gpiolib will invert the line if need be.
1814 */
1815 if ((ctlr->use_gpio_descriptors) && ctlr->cs_gpiods &&
1816 ctlr->cs_gpiods[spi->chip_select])
1817 spi->mode |= SPI_CS_HIGH;
1818
1819 /* Device speed */
1820 rc = of_property_read_u32(nc, "spi-max-frequency", &value);
1821 if (rc) {
1822 dev_err(&ctlr->dev,
1823 "%pOF has no valid 'spi-max-frequency' property (%d)\n", nc, rc);
1824 return rc;
1825 }
1826 spi->max_speed_hz = value;
1827
1828 return 0;
1829}
1830
1831static struct spi_device *
1832of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
1833{
1834 struct spi_device *spi;
1835 int rc;
1836
1837 /* Alloc an spi_device */
1838 spi = spi_alloc_device(ctlr);
1839 if (!spi) {
1840 dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
1841 rc = -ENOMEM;
1842 goto err_out;
1843 }
1844
1845 /* Select device driver */
1846 rc = of_modalias_node(nc, spi->modalias,
1847 sizeof(spi->modalias));
1848 if (rc < 0) {
1849 dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
1850 goto err_out;
1851 }
1852
1853 rc = of_spi_parse_dt(ctlr, spi, nc);
1854 if (rc)
1855 goto err_out;
1856
1857 /* Store a pointer to the node in the device structure */
1858 of_node_get(nc);
1859 spi->dev.of_node = nc;
1860 spi->dev.fwnode = of_fwnode_handle(nc);
1861
1862 /* Register the new device */
1863 rc = spi_add_device(spi);
1864 if (rc) {
1865 dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
1866 goto err_of_node_put;
1867 }
1868
1869 return spi;
1870
1871err_of_node_put:
1872 of_node_put(nc);
1873err_out:
1874 spi_dev_put(spi);
1875 return ERR_PTR(rc);
1876}
1877
1878/**
1879 * of_register_spi_devices() - Register child devices onto the SPI bus
1880 * @ctlr: Pointer to spi_controller device
1881 *
1882 * Registers an spi_device for each child node of controller node which
1883 * represents a valid SPI slave.
1884 */
1885static void of_register_spi_devices(struct spi_controller *ctlr)
1886{
1887 struct spi_device *spi;
1888 struct device_node *nc;
1889
1890 if (!ctlr->dev.of_node)
1891 return;
1892
1893 for_each_available_child_of_node(ctlr->dev.of_node, nc) {
1894 if (of_node_test_and_set_flag(nc, OF_POPULATED))
1895 continue;
1896 spi = of_register_spi_device(ctlr, nc);
1897 if (IS_ERR(spi)) {
1898 dev_warn(&ctlr->dev,
1899 "Failed to create SPI device for %pOF\n", nc);
1900 of_node_clear_flag(nc, OF_POPULATED);
1901 }
1902 }
1903}
1904#else
1905static void of_register_spi_devices(struct spi_controller *ctlr) { }
1906#endif
1907
1908#ifdef CONFIG_ACPI
1909struct acpi_spi_lookup {
1910 struct spi_controller *ctlr;
1911 u32 max_speed_hz;
1912 u32 mode;
1913 int irq;
1914 u8 bits_per_word;
1915 u8 chip_select;
1916};
1917
1918static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
1919 struct acpi_spi_lookup *lookup)
1920{
1921 const union acpi_object *obj;
1922
1923 if (!x86_apple_machine)
1924 return;
1925
1926 if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
1927 && obj->buffer.length >= 4)
1928 lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
1929
1930 if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
1931 && obj->buffer.length == 8)
1932 lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
1933
1934 if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
1935 && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
1936 lookup->mode |= SPI_LSB_FIRST;
1937
1938 if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
1939 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
1940 lookup->mode |= SPI_CPOL;
1941
1942 if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
1943 && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
1944 lookup->mode |= SPI_CPHA;
1945}
1946
1947static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
1948{
1949 struct acpi_spi_lookup *lookup = data;
1950 struct spi_controller *ctlr = lookup->ctlr;
1951
1952 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
1953 struct acpi_resource_spi_serialbus *sb;
1954 acpi_handle parent_handle;
1955 acpi_status status;
1956
1957 sb = &ares->data.spi_serial_bus;
1958 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
1959
1960 status = acpi_get_handle(NULL,
1961 sb->resource_source.string_ptr,
1962 &parent_handle);
1963
1964 if (ACPI_FAILURE(status) ||
1965 ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
1966 return -ENODEV;
1967
1968 /*
1969 * ACPI DeviceSelection numbering is handled by the
1970 * host controller driver in Windows and can vary
1971 * from driver to driver. In Linux we always expect
1972 * 0 .. max - 1 so we need to ask the driver to
1973 * translate between the two schemes.
1974 */
1975 if (ctlr->fw_translate_cs) {
1976 int cs = ctlr->fw_translate_cs(ctlr,
1977 sb->device_selection);
1978 if (cs < 0)
1979 return cs;
1980 lookup->chip_select = cs;
1981 } else {
1982 lookup->chip_select = sb->device_selection;
1983 }
1984
1985 lookup->max_speed_hz = sb->connection_speed;
1986 lookup->bits_per_word = sb->data_bit_length;
1987
1988 if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
1989 lookup->mode |= SPI_CPHA;
1990 if (sb->clock_polarity == ACPI_SPI_START_HIGH)
1991 lookup->mode |= SPI_CPOL;
1992 if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
1993 lookup->mode |= SPI_CS_HIGH;
1994 }
1995 } else if (lookup->irq < 0) {
1996 struct resource r;
1997
1998 if (acpi_dev_resource_interrupt(ares, 0, &r))
1999 lookup->irq = r.start;
2000 }
2001
2002 /* Always tell the ACPI core to skip this resource */
2003 return 1;
2004}
2005
2006static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2007 struct acpi_device *adev)
2008{
2009 acpi_handle parent_handle = NULL;
2010 struct list_head resource_list;
2011 struct acpi_spi_lookup lookup = {};
2012 struct spi_device *spi;
2013 int ret;
2014
2015 if (acpi_bus_get_status(adev) || !adev->status.present ||
2016 acpi_device_enumerated(adev))
2017 return AE_OK;
2018
2019 lookup.ctlr = ctlr;
2020 lookup.irq = -1;
2021
2022 INIT_LIST_HEAD(&resource_list);
2023 ret = acpi_dev_get_resources(adev, &resource_list,
2024 acpi_spi_add_resource, &lookup);
2025 acpi_dev_free_resource_list(&resource_list);
2026
2027 if (ret < 0)
2028 /* found SPI in _CRS but it points to another controller */
2029 return AE_OK;
2030
2031 if (!lookup.max_speed_hz &&
2032 !ACPI_FAILURE(acpi_get_parent(adev->handle, &parent_handle)) &&
2033 ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2034 /* Apple does not use _CRS but nested devices for SPI slaves */
2035 acpi_spi_parse_apple_properties(adev, &lookup);
2036 }
2037
2038 if (!lookup.max_speed_hz)
2039 return AE_OK;
2040
2041 spi = spi_alloc_device(ctlr);
2042 if (!spi) {
2043 dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2044 dev_name(&adev->dev));
2045 return AE_NO_MEMORY;
2046 }
2047
2048 ACPI_COMPANION_SET(&spi->dev, adev);
2049 spi->max_speed_hz = lookup.max_speed_hz;
2050 spi->mode = lookup.mode;
2051 spi->irq = lookup.irq;
2052 spi->bits_per_word = lookup.bits_per_word;
2053 spi->chip_select = lookup.chip_select;
2054
2055 acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2056 sizeof(spi->modalias));
2057
2058 acpi_device_set_enumerated(adev);
2059
2060 adev->power.flags.ignore_parent = true;
2061 if (spi_add_device(spi)) {
2062 adev->power.flags.ignore_parent = false;
2063 dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2064 dev_name(&adev->dev));
2065 spi_dev_put(spi);
2066 }
2067
2068 return AE_OK;
2069}
2070
2071static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2072 void *data, void **return_value)
2073{
2074 struct spi_controller *ctlr = data;
2075 struct acpi_device *adev;
2076
2077 if (acpi_bus_get_device(handle, &adev))
2078 return AE_OK;
2079
2080 return acpi_register_spi_device(ctlr, adev);
2081}
2082
2083#define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
2084
2085static void acpi_register_spi_devices(struct spi_controller *ctlr)
2086{
2087 acpi_status status;
2088 acpi_handle handle;
2089
2090 handle = ACPI_HANDLE(ctlr->dev.parent);
2091 if (!handle)
2092 return;
2093
2094 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2095 SPI_ACPI_ENUMERATE_MAX_DEPTH,
2096 acpi_spi_add_device, NULL, ctlr, NULL);
2097 if (ACPI_FAILURE(status))
2098 dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2099}
2100#else
2101static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2102#endif /* CONFIG_ACPI */
2103
2104static void spi_controller_release(struct device *dev)
2105{
2106 struct spi_controller *ctlr;
2107
2108 ctlr = container_of(dev, struct spi_controller, dev);
2109 kfree(ctlr);
2110}
2111
2112static struct class spi_master_class = {
2113 .name = "spi_master",
2114 .owner = THIS_MODULE,
2115 .dev_release = spi_controller_release,
2116 .dev_groups = spi_master_groups,
2117};
2118
2119#ifdef CONFIG_SPI_SLAVE
2120/**
2121 * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2122 * controller
2123 * @spi: device used for the current transfer
2124 */
2125int spi_slave_abort(struct spi_device *spi)
2126{
2127 struct spi_controller *ctlr = spi->controller;
2128
2129 if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2130 return ctlr->slave_abort(ctlr);
2131
2132 return -ENOTSUPP;
2133}
2134EXPORT_SYMBOL_GPL(spi_slave_abort);
2135
2136static int match_true(struct device *dev, void *data)
2137{
2138 return 1;
2139}
2140
2141static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2142 char *buf)
2143{
2144 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2145 dev);
2146 struct device *child;
2147
2148 child = device_find_child(&ctlr->dev, NULL, match_true);
2149 return sprintf(buf, "%s\n",
2150 child ? to_spi_device(child)->modalias : NULL);
2151}
2152
2153static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2154 const char *buf, size_t count)
2155{
2156 struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2157 dev);
2158 struct spi_device *spi;
2159 struct device *child;
2160 char name[32];
2161 int rc;
2162
2163 rc = sscanf(buf, "%31s", name);
2164 if (rc != 1 || !name[0])
2165 return -EINVAL;
2166
2167 child = device_find_child(&ctlr->dev, NULL, match_true);
2168 if (child) {
2169 /* Remove registered slave */
2170 device_unregister(child);
2171 put_device(child);
2172 }
2173
2174 if (strcmp(name, "(null)")) {
2175 /* Register new slave */
2176 spi = spi_alloc_device(ctlr);
2177 if (!spi)
2178 return -ENOMEM;
2179
2180 strlcpy(spi->modalias, name, sizeof(spi->modalias));
2181
2182 rc = spi_add_device(spi);
2183 if (rc) {
2184 spi_dev_put(spi);
2185 return rc;
2186 }
2187 }
2188
2189 return count;
2190}
2191
2192static DEVICE_ATTR_RW(slave);
2193
2194static struct attribute *spi_slave_attrs[] = {
2195 &dev_attr_slave.attr,
2196 NULL,
2197};
2198
2199static const struct attribute_group spi_slave_group = {
2200 .attrs = spi_slave_attrs,
2201};
2202
2203static const struct attribute_group *spi_slave_groups[] = {
2204 &spi_controller_statistics_group,
2205 &spi_slave_group,
2206 NULL,
2207};
2208
2209static struct class spi_slave_class = {
2210 .name = "spi_slave",
2211 .owner = THIS_MODULE,
2212 .dev_release = spi_controller_release,
2213 .dev_groups = spi_slave_groups,
2214};
2215#else
2216extern struct class spi_slave_class; /* dummy */
2217#endif
2218
2219/**
2220 * __spi_alloc_controller - allocate an SPI master or slave controller
2221 * @dev: the controller, possibly using the platform_bus
2222 * @size: how much zeroed driver-private data to allocate; the pointer to this
2223 * memory is in the driver_data field of the returned device, accessible
2224 * with spi_controller_get_devdata(); the memory is cacheline aligned;
2225 * drivers granting DMA access to portions of their private data need to
2226 * round up @size using ALIGN(size, dma_get_cache_alignment()).
2227 * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2228 * slave (true) controller
2229 * Context: can sleep
2230 *
2231 * This call is used only by SPI controller drivers, which are the
2232 * only ones directly touching chip registers. It's how they allocate
2233 * an spi_controller structure, prior to calling spi_register_controller().
2234 *
2235 * This must be called from context that can sleep.
2236 *
2237 * The caller is responsible for assigning the bus number and initializing the
2238 * controller's methods before calling spi_register_controller(); and (after
2239 * errors adding the device) calling spi_controller_put() to prevent a memory
2240 * leak.
2241 *
2242 * Return: the SPI controller structure on success, else NULL.
2243 */
2244struct spi_controller *__spi_alloc_controller(struct device *dev,
2245 unsigned int size, bool slave)
2246{
2247 struct spi_controller *ctlr;
2248 size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2249
2250 if (!dev)
2251 return NULL;
2252
2253 ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2254 if (!ctlr)
2255 return NULL;
2256
2257 device_initialize(&ctlr->dev);
2258 ctlr->bus_num = -1;
2259 ctlr->num_chipselect = 1;
2260 ctlr->slave = slave;
2261 if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2262 ctlr->dev.class = &spi_slave_class;
2263 else
2264 ctlr->dev.class = &spi_master_class;
2265 ctlr->dev.parent = dev;
2266 pm_suspend_ignore_children(&ctlr->dev, true);
2267 spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2268
2269 return ctlr;
2270}
2271EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2272
2273static void devm_spi_release_controller(struct device *dev, void *ctlr)
2274{
2275 spi_controller_put(*(struct spi_controller **)ctlr);
2276}
2277
2278/**
2279 * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2280 * @dev: physical device of SPI controller
2281 * @size: how much zeroed driver-private data to allocate
2282 * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2283 * Context: can sleep
2284 *
2285 * Allocate an SPI controller and automatically release a reference on it
2286 * when @dev is unbound from its driver. Drivers are thus relieved from
2287 * having to call spi_controller_put().
2288 *
2289 * The arguments to this function are identical to __spi_alloc_controller().
2290 *
2291 * Return: the SPI controller structure on success, else NULL.
2292 */
2293struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2294 unsigned int size,
2295 bool slave)
2296{
2297 struct spi_controller **ptr, *ctlr;
2298
2299 ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2300 GFP_KERNEL);
2301 if (!ptr)
2302 return NULL;
2303
2304 ctlr = __spi_alloc_controller(dev, size, slave);
2305 if (ctlr) {
2306 ctlr->devm_allocated = true;
2307 *ptr = ctlr;
2308 devres_add(dev, ptr);
2309 } else {
2310 devres_free(ptr);
2311 }
2312
2313 return ctlr;
2314}
2315EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2316
2317#ifdef CONFIG_OF
2318static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2319{
2320 int nb, i, *cs;
2321 struct device_node *np = ctlr->dev.of_node;
2322
2323 if (!np)
2324 return 0;
2325
2326 nb = of_gpio_named_count(np, "cs-gpios");
2327 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2328
2329 /* Return error only for an incorrectly formed cs-gpios property */
2330 if (nb == 0 || nb == -ENOENT)
2331 return 0;
2332 else if (nb < 0)
2333 return nb;
2334
2335 cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2336 GFP_KERNEL);
2337 ctlr->cs_gpios = cs;
2338
2339 if (!ctlr->cs_gpios)
2340 return -ENOMEM;
2341
2342 for (i = 0; i < ctlr->num_chipselect; i++)
2343 cs[i] = -ENOENT;
2344
2345 for (i = 0; i < nb; i++)
2346 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2347
2348 return 0;
2349}
2350#else
2351static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2352{
2353 return 0;
2354}
2355#endif
2356
2357/**
2358 * spi_get_gpio_descs() - grab chip select GPIOs for the master
2359 * @ctlr: The SPI master to grab GPIO descriptors for
2360 */
2361static int spi_get_gpio_descs(struct spi_controller *ctlr)
2362{
2363 int nb, i;
2364 struct gpio_desc **cs;
2365 struct device *dev = &ctlr->dev;
2366
2367 nb = gpiod_count(dev, "cs");
2368 ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2369
2370 /* No GPIOs at all is fine, else return the error */
2371 if (nb == 0 || nb == -ENOENT)
2372 return 0;
2373 else if (nb < 0)
2374 return nb;
2375
2376 cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2377 GFP_KERNEL);
2378 if (!cs)
2379 return -ENOMEM;
2380 ctlr->cs_gpiods = cs;
2381
2382 for (i = 0; i < nb; i++) {
2383 /*
2384 * Most chipselects are active low, the inverted
2385 * semantics are handled by special quirks in gpiolib,
2386 * so initializing them GPIOD_OUT_LOW here means
2387 * "unasserted", in most cases this will drive the physical
2388 * line high.
2389 */
2390 cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2391 GPIOD_OUT_LOW);
2392 if (IS_ERR(cs[i]))
2393 return PTR_ERR(cs[i]);
2394
2395 if (cs[i]) {
2396 /*
2397 * If we find a CS GPIO, name it after the device and
2398 * chip select line.
2399 */
2400 char *gpioname;
2401
2402 gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2403 dev_name(dev), i);
2404 if (!gpioname)
2405 return -ENOMEM;
2406 gpiod_set_consumer_name(cs[i], gpioname);
2407 }
2408 }
2409
2410 return 0;
2411}
2412
2413static int spi_controller_check_ops(struct spi_controller *ctlr)
2414{
2415 /*
2416 * The controller may implement only the high-level SPI-memory like
2417 * operations if it does not support regular SPI transfers, and this is
2418 * valid use case.
2419 * If ->mem_ops is NULL, we request that at least one of the
2420 * ->transfer_xxx() method be implemented.
2421 */
2422 if (ctlr->mem_ops) {
2423 if (!ctlr->mem_ops->exec_op)
2424 return -EINVAL;
2425 } else if (!ctlr->transfer && !ctlr->transfer_one &&
2426 !ctlr->transfer_one_message) {
2427 return -EINVAL;
2428 }
2429
2430 return 0;
2431}
2432
2433/**
2434 * spi_register_controller - register SPI master or slave controller
2435 * @ctlr: initialized master, originally from spi_alloc_master() or
2436 * spi_alloc_slave()
2437 * Context: can sleep
2438 *
2439 * SPI controllers connect to their drivers using some non-SPI bus,
2440 * such as the platform bus. The final stage of probe() in that code
2441 * includes calling spi_register_controller() to hook up to this SPI bus glue.
2442 *
2443 * SPI controllers use board specific (often SOC specific) bus numbers,
2444 * and board-specific addressing for SPI devices combines those numbers
2445 * with chip select numbers. Since SPI does not directly support dynamic
2446 * device identification, boards need configuration tables telling which
2447 * chip is at which address.
2448 *
2449 * This must be called from context that can sleep. It returns zero on
2450 * success, else a negative error code (dropping the controller's refcount).
2451 * After a successful return, the caller is responsible for calling
2452 * spi_unregister_controller().
2453 *
2454 * Return: zero on success, else a negative error code.
2455 */
2456int spi_register_controller(struct spi_controller *ctlr)
2457{
2458 struct device *dev = ctlr->dev.parent;
2459 struct boardinfo *bi;
2460 int status;
2461 int id, first_dynamic;
2462
2463 if (!dev)
2464 return -ENODEV;
2465
2466 /*
2467 * Make sure all necessary hooks are implemented before registering
2468 * the SPI controller.
2469 */
2470 status = spi_controller_check_ops(ctlr);
2471 if (status)
2472 return status;
2473
2474 if (ctlr->bus_num >= 0) {
2475 /* devices with a fixed bus num must check-in with the num */
2476 mutex_lock(&board_lock);
2477 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2478 ctlr->bus_num + 1, GFP_KERNEL);
2479 mutex_unlock(&board_lock);
2480 if (WARN(id < 0, "couldn't get idr"))
2481 return id == -ENOSPC ? -EBUSY : id;
2482 ctlr->bus_num = id;
2483 } else if (ctlr->dev.of_node) {
2484 /* allocate dynamic bus number using Linux idr */
2485 id = of_alias_get_id(ctlr->dev.of_node, "spi");
2486 if (id >= 0) {
2487 ctlr->bus_num = id;
2488 mutex_lock(&board_lock);
2489 id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2490 ctlr->bus_num + 1, GFP_KERNEL);
2491 mutex_unlock(&board_lock);
2492 if (WARN(id < 0, "couldn't get idr"))
2493 return id == -ENOSPC ? -EBUSY : id;
2494 }
2495 }
2496 if (ctlr->bus_num < 0) {
2497 first_dynamic = of_alias_get_highest_id("spi");
2498 if (first_dynamic < 0)
2499 first_dynamic = 0;
2500 else
2501 first_dynamic++;
2502
2503 mutex_lock(&board_lock);
2504 id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2505 0, GFP_KERNEL);
2506 mutex_unlock(&board_lock);
2507 if (WARN(id < 0, "couldn't get idr"))
2508 return id;
2509 ctlr->bus_num = id;
2510 }
2511 INIT_LIST_HEAD(&ctlr->queue);
2512 spin_lock_init(&ctlr->queue_lock);
2513 spin_lock_init(&ctlr->bus_lock_spinlock);
2514 mutex_init(&ctlr->bus_lock_mutex);
2515 mutex_init(&ctlr->io_mutex);
2516 mutex_init(&ctlr->add_lock);
2517 ctlr->bus_lock_flag = 0;
2518 init_completion(&ctlr->xfer_completion);
2519 if (!ctlr->max_dma_len)
2520 ctlr->max_dma_len = INT_MAX;
2521
2522 /* register the device, then userspace will see it.
2523 * registration fails if the bus ID is in use.
2524 */
2525 dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2526
2527 if (!spi_controller_is_slave(ctlr)) {
2528 if (ctlr->use_gpio_descriptors) {
2529 status = spi_get_gpio_descs(ctlr);
2530 if (status)
2531 goto free_bus_id;
2532 /*
2533 * A controller using GPIO descriptors always
2534 * supports SPI_CS_HIGH if need be.
2535 */
2536 ctlr->mode_bits |= SPI_CS_HIGH;
2537 } else {
2538 /* Legacy code path for GPIOs from DT */
2539 status = of_spi_get_gpio_numbers(ctlr);
2540 if (status)
2541 goto free_bus_id;
2542 }
2543 }
2544
2545 /*
2546 * Even if it's just one always-selected device, there must
2547 * be at least one chipselect.
2548 */
2549 if (!ctlr->num_chipselect) {
2550 status = -EINVAL;
2551 goto free_bus_id;
2552 }
2553
2554 status = device_add(&ctlr->dev);
2555 if (status < 0)
2556 goto free_bus_id;
2557 dev_dbg(dev, "registered %s %s\n",
2558 spi_controller_is_slave(ctlr) ? "slave" : "master",
2559 dev_name(&ctlr->dev));
2560
2561 /*
2562 * If we're using a queued driver, start the queue. Note that we don't
2563 * need the queueing logic if the driver is only supporting high-level
2564 * memory operations.
2565 */
2566 if (ctlr->transfer) {
2567 dev_info(dev, "controller is unqueued, this is deprecated\n");
2568 } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2569 status = spi_controller_initialize_queue(ctlr);
2570 if (status) {
2571 device_del(&ctlr->dev);
2572 goto free_bus_id;
2573 }
2574 }
2575 /* add statistics */
2576 spin_lock_init(&ctlr->statistics.lock);
2577
2578 mutex_lock(&board_lock);
2579 list_add_tail(&ctlr->list, &spi_controller_list);
2580 list_for_each_entry(bi, &board_list, list)
2581 spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2582 mutex_unlock(&board_lock);
2583
2584 /* Register devices from the device tree and ACPI */
2585 of_register_spi_devices(ctlr);
2586 acpi_register_spi_devices(ctlr);
2587 return status;
2588
2589free_bus_id:
2590 mutex_lock(&board_lock);
2591 idr_remove(&spi_master_idr, ctlr->bus_num);
2592 mutex_unlock(&board_lock);
2593 return status;
2594}
2595EXPORT_SYMBOL_GPL(spi_register_controller);
2596
2597static void devm_spi_unregister(struct device *dev, void *res)
2598{
2599 spi_unregister_controller(*(struct spi_controller **)res);
2600}
2601
2602/**
2603 * devm_spi_register_controller - register managed SPI master or slave
2604 * controller
2605 * @dev: device managing SPI controller
2606 * @ctlr: initialized controller, originally from spi_alloc_master() or
2607 * spi_alloc_slave()
2608 * Context: can sleep
2609 *
2610 * Register a SPI device as with spi_register_controller() which will
2611 * automatically be unregistered and freed.
2612 *
2613 * Return: zero on success, else a negative error code.
2614 */
2615int devm_spi_register_controller(struct device *dev,
2616 struct spi_controller *ctlr)
2617{
2618 struct spi_controller **ptr;
2619 int ret;
2620
2621 ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2622 if (!ptr)
2623 return -ENOMEM;
2624
2625 ret = spi_register_controller(ctlr);
2626 if (!ret) {
2627 *ptr = ctlr;
2628 devres_add(dev, ptr);
2629 } else {
2630 devres_free(ptr);
2631 }
2632
2633 return ret;
2634}
2635EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2636
2637static int __unregister(struct device *dev, void *null)
2638{
2639 spi_unregister_device(to_spi_device(dev));
2640 return 0;
2641}
2642
2643/**
2644 * spi_unregister_controller - unregister SPI master or slave controller
2645 * @ctlr: the controller being unregistered
2646 * Context: can sleep
2647 *
2648 * This call is used only by SPI controller drivers, which are the
2649 * only ones directly touching chip registers.
2650 *
2651 * This must be called from context that can sleep.
2652 *
2653 * Note that this function also drops a reference to the controller.
2654 */
2655void spi_unregister_controller(struct spi_controller *ctlr)
2656{
2657 struct spi_controller *found;
2658 int id = ctlr->bus_num;
2659
2660 /* Prevent addition of new devices, unregister existing ones */
2661 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2662 mutex_lock(&ctlr->add_lock);
2663
2664 device_for_each_child(&ctlr->dev, NULL, __unregister);
2665
2666 /* First make sure that this controller was ever added */
2667 mutex_lock(&board_lock);
2668 found = idr_find(&spi_master_idr, id);
2669 mutex_unlock(&board_lock);
2670 if (ctlr->queued) {
2671 if (spi_destroy_queue(ctlr))
2672 dev_err(&ctlr->dev, "queue remove failed\n");
2673 }
2674 mutex_lock(&board_lock);
2675 list_del(&ctlr->list);
2676 mutex_unlock(&board_lock);
2677
2678 device_del(&ctlr->dev);
2679
2680 /* free bus id */
2681 mutex_lock(&board_lock);
2682 if (found == ctlr)
2683 idr_remove(&spi_master_idr, id);
2684 mutex_unlock(&board_lock);
2685
2686 if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2687 mutex_unlock(&ctlr->add_lock);
2688
2689 /* Release the last reference on the controller if its driver
2690 * has not yet been converted to devm_spi_alloc_master/slave().
2691 */
2692 if (!ctlr->devm_allocated)
2693 put_device(&ctlr->dev);
2694}
2695EXPORT_SYMBOL_GPL(spi_unregister_controller);
2696
2697int spi_controller_suspend(struct spi_controller *ctlr)
2698{
2699 int ret;
2700
2701 /* Basically no-ops for non-queued controllers */
2702 if (!ctlr->queued)
2703 return 0;
2704
2705 ret = spi_stop_queue(ctlr);
2706 if (ret)
2707 dev_err(&ctlr->dev, "queue stop failed\n");
2708
2709 return ret;
2710}
2711EXPORT_SYMBOL_GPL(spi_controller_suspend);
2712
2713int spi_controller_resume(struct spi_controller *ctlr)
2714{
2715 int ret;
2716
2717 if (!ctlr->queued)
2718 return 0;
2719
2720 ret = spi_start_queue(ctlr);
2721 if (ret)
2722 dev_err(&ctlr->dev, "queue restart failed\n");
2723
2724 return ret;
2725}
2726EXPORT_SYMBOL_GPL(spi_controller_resume);
2727
2728static int __spi_controller_match(struct device *dev, const void *data)
2729{
2730 struct spi_controller *ctlr;
2731 const u16 *bus_num = data;
2732
2733 ctlr = container_of(dev, struct spi_controller, dev);
2734 return ctlr->bus_num == *bus_num;
2735}
2736
2737/**
2738 * spi_busnum_to_master - look up master associated with bus_num
2739 * @bus_num: the master's bus number
2740 * Context: can sleep
2741 *
2742 * This call may be used with devices that are registered after
2743 * arch init time. It returns a refcounted pointer to the relevant
2744 * spi_controller (which the caller must release), or NULL if there is
2745 * no such master registered.
2746 *
2747 * Return: the SPI master structure on success, else NULL.
2748 */
2749struct spi_controller *spi_busnum_to_master(u16 bus_num)
2750{
2751 struct device *dev;
2752 struct spi_controller *ctlr = NULL;
2753
2754 dev = class_find_device(&spi_master_class, NULL, &bus_num,
2755 __spi_controller_match);
2756 if (dev)
2757 ctlr = container_of(dev, struct spi_controller, dev);
2758 /* reference got in class_find_device */
2759 return ctlr;
2760}
2761EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2762
2763/*-------------------------------------------------------------------------*/
2764
2765/* Core methods for SPI resource management */
2766
2767/**
2768 * spi_res_alloc - allocate a spi resource that is life-cycle managed
2769 * during the processing of a spi_message while using
2770 * spi_transfer_one
2771 * @spi: the spi device for which we allocate memory
2772 * @release: the release code to execute for this resource
2773 * @size: size to alloc and return
2774 * @gfp: GFP allocation flags
2775 *
2776 * Return: the pointer to the allocated data
2777 *
2778 * This may get enhanced in the future to allocate from a memory pool
2779 * of the @spi_device or @spi_controller to avoid repeated allocations.
2780 */
2781void *spi_res_alloc(struct spi_device *spi,
2782 spi_res_release_t release,
2783 size_t size, gfp_t gfp)
2784{
2785 struct spi_res *sres;
2786
2787 sres = kzalloc(sizeof(*sres) + size, gfp);
2788 if (!sres)
2789 return NULL;
2790
2791 INIT_LIST_HEAD(&sres->entry);
2792 sres->release = release;
2793
2794 return sres->data;
2795}
2796EXPORT_SYMBOL_GPL(spi_res_alloc);
2797
2798/**
2799 * spi_res_free - free an spi resource
2800 * @res: pointer to the custom data of a resource
2801 *
2802 */
2803void spi_res_free(void *res)
2804{
2805 struct spi_res *sres = container_of(res, struct spi_res, data);
2806
2807 if (!res)
2808 return;
2809
2810 WARN_ON(!list_empty(&sres->entry));
2811 kfree(sres);
2812}
2813EXPORT_SYMBOL_GPL(spi_res_free);
2814
2815/**
2816 * spi_res_add - add a spi_res to the spi_message
2817 * @message: the spi message
2818 * @res: the spi_resource
2819 */
2820void spi_res_add(struct spi_message *message, void *res)
2821{
2822 struct spi_res *sres = container_of(res, struct spi_res, data);
2823
2824 WARN_ON(!list_empty(&sres->entry));
2825 list_add_tail(&sres->entry, &message->resources);
2826}
2827EXPORT_SYMBOL_GPL(spi_res_add);
2828
2829/**
2830 * spi_res_release - release all spi resources for this message
2831 * @ctlr: the @spi_controller
2832 * @message: the @spi_message
2833 */
2834void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
2835{
2836 struct spi_res *res, *tmp;
2837
2838 list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
2839 if (res->release)
2840 res->release(ctlr, message, res->data);
2841
2842 list_del(&res->entry);
2843
2844 kfree(res);
2845 }
2846}
2847EXPORT_SYMBOL_GPL(spi_res_release);
2848
2849/*-------------------------------------------------------------------------*/
2850
2851/* Core methods for spi_message alterations */
2852
2853static void __spi_replace_transfers_release(struct spi_controller *ctlr,
2854 struct spi_message *msg,
2855 void *res)
2856{
2857 struct spi_replaced_transfers *rxfer = res;
2858 size_t i;
2859
2860 /* call extra callback if requested */
2861 if (rxfer->release)
2862 rxfer->release(ctlr, msg, res);
2863
2864 /* insert replaced transfers back into the message */
2865 list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
2866
2867 /* remove the formerly inserted entries */
2868 for (i = 0; i < rxfer->inserted; i++)
2869 list_del(&rxfer->inserted_transfers[i].transfer_list);
2870}
2871
2872/**
2873 * spi_replace_transfers - replace transfers with several transfers
2874 * and register change with spi_message.resources
2875 * @msg: the spi_message we work upon
2876 * @xfer_first: the first spi_transfer we want to replace
2877 * @remove: number of transfers to remove
2878 * @insert: the number of transfers we want to insert instead
2879 * @release: extra release code necessary in some circumstances
2880 * @extradatasize: extra data to allocate (with alignment guarantees
2881 * of struct @spi_transfer)
2882 * @gfp: gfp flags
2883 *
2884 * Returns: pointer to @spi_replaced_transfers,
2885 * PTR_ERR(...) in case of errors.
2886 */
2887struct spi_replaced_transfers *spi_replace_transfers(
2888 struct spi_message *msg,
2889 struct spi_transfer *xfer_first,
2890 size_t remove,
2891 size_t insert,
2892 spi_replaced_release_t release,
2893 size_t extradatasize,
2894 gfp_t gfp)
2895{
2896 struct spi_replaced_transfers *rxfer;
2897 struct spi_transfer *xfer;
2898 size_t i;
2899
2900 /* allocate the structure using spi_res */
2901 rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
2902 struct_size(rxfer, inserted_transfers, insert)
2903 + extradatasize,
2904 gfp);
2905 if (!rxfer)
2906 return ERR_PTR(-ENOMEM);
2907
2908 /* the release code to invoke before running the generic release */
2909 rxfer->release = release;
2910
2911 /* assign extradata */
2912 if (extradatasize)
2913 rxfer->extradata =
2914 &rxfer->inserted_transfers[insert];
2915
2916 /* init the replaced_transfers list */
2917 INIT_LIST_HEAD(&rxfer->replaced_transfers);
2918
2919 /* assign the list_entry after which we should reinsert
2920 * the @replaced_transfers - it may be spi_message.messages!
2921 */
2922 rxfer->replaced_after = xfer_first->transfer_list.prev;
2923
2924 /* remove the requested number of transfers */
2925 for (i = 0; i < remove; i++) {
2926 /* if the entry after replaced_after it is msg->transfers
2927 * then we have been requested to remove more transfers
2928 * than are in the list
2929 */
2930 if (rxfer->replaced_after->next == &msg->transfers) {
2931 dev_err(&msg->spi->dev,
2932 "requested to remove more spi_transfers than are available\n");
2933 /* insert replaced transfers back into the message */
2934 list_splice(&rxfer->replaced_transfers,
2935 rxfer->replaced_after);
2936
2937 /* free the spi_replace_transfer structure */
2938 spi_res_free(rxfer);
2939
2940 /* and return with an error */
2941 return ERR_PTR(-EINVAL);
2942 }
2943
2944 /* remove the entry after replaced_after from list of
2945 * transfers and add it to list of replaced_transfers
2946 */
2947 list_move_tail(rxfer->replaced_after->next,
2948 &rxfer->replaced_transfers);
2949 }
2950
2951 /* create copy of the given xfer with identical settings
2952 * based on the first transfer to get removed
2953 */
2954 for (i = 0; i < insert; i++) {
2955 /* we need to run in reverse order */
2956 xfer = &rxfer->inserted_transfers[insert - 1 - i];
2957
2958 /* copy all spi_transfer data */
2959 memcpy(xfer, xfer_first, sizeof(*xfer));
2960
2961 /* add to list */
2962 list_add(&xfer->transfer_list, rxfer->replaced_after);
2963
2964 /* clear cs_change and delay_usecs for all but the last */
2965 if (i) {
2966 xfer->cs_change = false;
2967 xfer->delay_usecs = 0;
2968 }
2969 }
2970
2971 /* set up inserted */
2972 rxfer->inserted = insert;
2973
2974 /* and register it with spi_res/spi_message */
2975 spi_res_add(msg, rxfer);
2976
2977 return rxfer;
2978}
2979EXPORT_SYMBOL_GPL(spi_replace_transfers);
2980
2981static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
2982 struct spi_message *msg,
2983 struct spi_transfer **xferp,
2984 size_t maxsize,
2985 gfp_t gfp)
2986{
2987 struct spi_transfer *xfer = *xferp, *xfers;
2988 struct spi_replaced_transfers *srt;
2989 size_t offset;
2990 size_t count, i;
2991
2992 /* calculate how many we have to replace */
2993 count = DIV_ROUND_UP(xfer->len, maxsize);
2994
2995 /* create replacement */
2996 srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
2997 if (IS_ERR(srt))
2998 return PTR_ERR(srt);
2999 xfers = srt->inserted_transfers;
3000
3001 /* now handle each of those newly inserted spi_transfers
3002 * note that the replacements spi_transfers all are preset
3003 * to the same values as *xferp, so tx_buf, rx_buf and len
3004 * are all identical (as well as most others)
3005 * so we just have to fix up len and the pointers.
3006 *
3007 * this also includes support for the depreciated
3008 * spi_message.is_dma_mapped interface
3009 */
3010
3011 /* the first transfer just needs the length modified, so we
3012 * run it outside the loop
3013 */
3014 xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3015
3016 /* all the others need rx_buf/tx_buf also set */
3017 for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3018 /* update rx_buf, tx_buf and dma */
3019 if (xfers[i].rx_buf)
3020 xfers[i].rx_buf += offset;
3021 if (xfers[i].rx_dma)
3022 xfers[i].rx_dma += offset;
3023 if (xfers[i].tx_buf)
3024 xfers[i].tx_buf += offset;
3025 if (xfers[i].tx_dma)
3026 xfers[i].tx_dma += offset;
3027
3028 /* update length */
3029 xfers[i].len = min(maxsize, xfers[i].len - offset);
3030 }
3031
3032 /* we set up xferp to the last entry we have inserted,
3033 * so that we skip those already split transfers
3034 */
3035 *xferp = &xfers[count - 1];
3036
3037 /* increment statistics counters */
3038 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3039 transfers_split_maxsize);
3040 SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3041 transfers_split_maxsize);
3042
3043 return 0;
3044}
3045
3046/**
3047 * spi_split_tranfers_maxsize - split spi transfers into multiple transfers
3048 * when an individual transfer exceeds a
3049 * certain size
3050 * @ctlr: the @spi_controller for this transfer
3051 * @msg: the @spi_message to transform
3052 * @maxsize: the maximum when to apply this
3053 * @gfp: GFP allocation flags
3054 *
3055 * Return: status of transformation
3056 */
3057int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3058 struct spi_message *msg,
3059 size_t maxsize,
3060 gfp_t gfp)
3061{
3062 struct spi_transfer *xfer;
3063 int ret;
3064
3065 /* iterate over the transfer_list,
3066 * but note that xfer is advanced to the last transfer inserted
3067 * to avoid checking sizes again unnecessarily (also xfer does
3068 * potentiall belong to a different list by the time the
3069 * replacement has happened
3070 */
3071 list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3072 if (xfer->len > maxsize) {
3073 ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3074 maxsize, gfp);
3075 if (ret)
3076 return ret;
3077 }
3078 }
3079
3080 return 0;
3081}
3082EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3083
3084/*-------------------------------------------------------------------------*/
3085
3086/* Core methods for SPI controller protocol drivers. Some of the
3087 * other core methods are currently defined as inline functions.
3088 */
3089
3090static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3091 u8 bits_per_word)
3092{
3093 if (ctlr->bits_per_word_mask) {
3094 /* Only 32 bits fit in the mask */
3095 if (bits_per_word > 32)
3096 return -EINVAL;
3097 if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3098 return -EINVAL;
3099 }
3100
3101 return 0;
3102}
3103
3104/**
3105 * spi_setup - setup SPI mode and clock rate
3106 * @spi: the device whose settings are being modified
3107 * Context: can sleep, and no requests are queued to the device
3108 *
3109 * SPI protocol drivers may need to update the transfer mode if the
3110 * device doesn't work with its default. They may likewise need
3111 * to update clock rates or word sizes from initial values. This function
3112 * changes those settings, and must be called from a context that can sleep.
3113 * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3114 * effect the next time the device is selected and data is transferred to
3115 * or from it. When this function returns, the spi device is deselected.
3116 *
3117 * Note that this call will fail if the protocol driver specifies an option
3118 * that the underlying controller or its driver does not support. For
3119 * example, not all hardware supports wire transfers using nine bit words,
3120 * LSB-first wire encoding, or active-high chipselects.
3121 *
3122 * Return: zero on success, else a negative error code.
3123 */
3124int spi_setup(struct spi_device *spi)
3125{
3126 unsigned bad_bits, ugly_bits;
3127 int status;
3128
3129 /* check mode to prevent that DUAL and QUAD set at the same time
3130 */
3131 if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
3132 ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
3133 dev_err(&spi->dev,
3134 "setup: can not select dual and quad at the same time\n");
3135 return -EINVAL;
3136 }
3137 /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3138 */
3139 if ((spi->mode & SPI_3WIRE) && (spi->mode &
3140 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3141 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3142 return -EINVAL;
3143 /* help drivers fail *cleanly* when they need options
3144 * that aren't supported with their current controller
3145 * SPI_CS_WORD has a fallback software implementation,
3146 * so it is ignored here.
3147 */
3148 bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD);
3149 /* nothing prevents from working with active-high CS in case if it
3150 * is driven by GPIO.
3151 */
3152 if (gpio_is_valid(spi->cs_gpio))
3153 bad_bits &= ~SPI_CS_HIGH;
3154 ugly_bits = bad_bits &
3155 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3156 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3157 if (ugly_bits) {
3158 dev_warn(&spi->dev,
3159 "setup: ignoring unsupported mode bits %x\n",
3160 ugly_bits);
3161 spi->mode &= ~ugly_bits;
3162 bad_bits &= ~ugly_bits;
3163 }
3164 if (bad_bits) {
3165 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3166 bad_bits);
3167 return -EINVAL;
3168 }
3169
3170 if (!spi->bits_per_word)
3171 spi->bits_per_word = 8;
3172
3173 status = __spi_validate_bits_per_word(spi->controller,
3174 spi->bits_per_word);
3175 if (status)
3176 return status;
3177
3178 if (!spi->max_speed_hz)
3179 spi->max_speed_hz = spi->controller->max_speed_hz;
3180
3181 if (spi->controller->setup)
3182 status = spi->controller->setup(spi);
3183
3184 if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3185 status = pm_runtime_get_sync(spi->controller->dev.parent);
3186 if (status < 0) {
3187 pm_runtime_put_noidle(spi->controller->dev.parent);
3188 dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3189 status);
3190 return status;
3191 }
3192
3193 /*
3194 * We do not want to return positive value from pm_runtime_get,
3195 * there are many instances of devices calling spi_setup() and
3196 * checking for a non-zero return value instead of a negative
3197 * return value.
3198 */
3199 status = 0;
3200
3201 spi_set_cs(spi, false);
3202 pm_runtime_mark_last_busy(spi->controller->dev.parent);
3203 pm_runtime_put_autosuspend(spi->controller->dev.parent);
3204 } else {
3205 spi_set_cs(spi, false);
3206 }
3207
3208 if (spi->rt && !spi->controller->rt) {
3209 spi->controller->rt = true;
3210 spi_set_thread_rt(spi->controller);
3211 }
3212
3213 dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3214 (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
3215 (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3216 (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3217 (spi->mode & SPI_3WIRE) ? "3wire, " : "",
3218 (spi->mode & SPI_LOOP) ? "loopback, " : "",
3219 spi->bits_per_word, spi->max_speed_hz,
3220 status);
3221
3222 return status;
3223}
3224EXPORT_SYMBOL_GPL(spi_setup);
3225
3226/**
3227 * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3228 * @spi: the device that requires specific CS timing configuration
3229 * @setup: CS setup time in terms of clock count
3230 * @hold: CS hold time in terms of clock count
3231 * @inactive_dly: CS inactive delay between transfers in terms of clock count
3232 */
3233void spi_set_cs_timing(struct spi_device *spi, u8 setup, u8 hold,
3234 u8 inactive_dly)
3235{
3236 if (spi->controller->set_cs_timing)
3237 spi->controller->set_cs_timing(spi, setup, hold, inactive_dly);
3238}
3239EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3240
3241static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3242{
3243 struct spi_controller *ctlr = spi->controller;
3244 struct spi_transfer *xfer;
3245 int w_size;
3246
3247 if (list_empty(&message->transfers))
3248 return -EINVAL;
3249
3250 /* If an SPI controller does not support toggling the CS line on each
3251 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3252 * for the CS line, we can emulate the CS-per-word hardware function by
3253 * splitting transfers into one-word transfers and ensuring that
3254 * cs_change is set for each transfer.
3255 */
3256 if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3257 spi->cs_gpiod ||
3258 gpio_is_valid(spi->cs_gpio))) {
3259 size_t maxsize;
3260 int ret;
3261
3262 maxsize = (spi->bits_per_word + 7) / 8;
3263
3264 /* spi_split_transfers_maxsize() requires message->spi */
3265 message->spi = spi;
3266
3267 ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3268 GFP_KERNEL);
3269 if (ret)
3270 return ret;
3271
3272 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3273 /* don't change cs_change on the last entry in the list */
3274 if (list_is_last(&xfer->transfer_list, &message->transfers))
3275 break;
3276 xfer->cs_change = 1;
3277 }
3278 }
3279
3280 /* Half-duplex links include original MicroWire, and ones with
3281 * only one data pin like SPI_3WIRE (switches direction) or where
3282 * either MOSI or MISO is missing. They can also be caused by
3283 * software limitations.
3284 */
3285 if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3286 (spi->mode & SPI_3WIRE)) {
3287 unsigned flags = ctlr->flags;
3288
3289 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3290 if (xfer->rx_buf && xfer->tx_buf)
3291 return -EINVAL;
3292 if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3293 return -EINVAL;
3294 if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3295 return -EINVAL;
3296 }
3297 }
3298
3299 /**
3300 * Set transfer bits_per_word and max speed as spi device default if
3301 * it is not set for this transfer.
3302 * Set transfer tx_nbits and rx_nbits as single transfer default
3303 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3304 * Ensure transfer word_delay is at least as long as that required by
3305 * device itself.
3306 */
3307 message->frame_length = 0;
3308 list_for_each_entry(xfer, &message->transfers, transfer_list) {
3309 xfer->effective_speed_hz = 0;
3310 message->frame_length += xfer->len;
3311 if (!xfer->bits_per_word)
3312 xfer->bits_per_word = spi->bits_per_word;
3313
3314 if (!xfer->speed_hz)
3315 xfer->speed_hz = spi->max_speed_hz;
3316
3317 if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3318 xfer->speed_hz = ctlr->max_speed_hz;
3319
3320 if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3321 return -EINVAL;
3322
3323 /*
3324 * SPI transfer length should be multiple of SPI word size
3325 * where SPI word size should be power-of-two multiple
3326 */
3327 if (xfer->bits_per_word <= 8)
3328 w_size = 1;
3329 else if (xfer->bits_per_word <= 16)
3330 w_size = 2;
3331 else
3332 w_size = 4;
3333
3334 /* No partial transfers accepted */
3335 if (xfer->len % w_size)
3336 return -EINVAL;
3337
3338 if (xfer->speed_hz && ctlr->min_speed_hz &&
3339 xfer->speed_hz < ctlr->min_speed_hz)
3340 return -EINVAL;
3341
3342 if (xfer->tx_buf && !xfer->tx_nbits)
3343 xfer->tx_nbits = SPI_NBITS_SINGLE;
3344 if (xfer->rx_buf && !xfer->rx_nbits)
3345 xfer->rx_nbits = SPI_NBITS_SINGLE;
3346 /* check transfer tx/rx_nbits:
3347 * 1. check the value matches one of single, dual and quad
3348 * 2. check tx/rx_nbits match the mode in spi_device
3349 */
3350 if (xfer->tx_buf) {
3351 if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3352 xfer->tx_nbits != SPI_NBITS_DUAL &&
3353 xfer->tx_nbits != SPI_NBITS_QUAD)
3354 return -EINVAL;
3355 if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3356 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3357 return -EINVAL;
3358 if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3359 !(spi->mode & SPI_TX_QUAD))
3360 return -EINVAL;
3361 }
3362 /* check transfer rx_nbits */
3363 if (xfer->rx_buf) {
3364 if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3365 xfer->rx_nbits != SPI_NBITS_DUAL &&
3366 xfer->rx_nbits != SPI_NBITS_QUAD)
3367 return -EINVAL;
3368 if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3369 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3370 return -EINVAL;
3371 if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3372 !(spi->mode & SPI_RX_QUAD))
3373 return -EINVAL;
3374 }
3375
3376 if (xfer->word_delay_usecs < spi->word_delay_usecs)
3377 xfer->word_delay_usecs = spi->word_delay_usecs;
3378 }
3379
3380 message->status = -EINPROGRESS;
3381
3382 return 0;
3383}
3384
3385static int __spi_async(struct spi_device *spi, struct spi_message *message)
3386{
3387 struct spi_controller *ctlr = spi->controller;
3388
3389 /*
3390 * Some controllers do not support doing regular SPI transfers. Return
3391 * ENOTSUPP when this is the case.
3392 */
3393 if (!ctlr->transfer)
3394 return -ENOTSUPP;
3395
3396 message->spi = spi;
3397
3398 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3399 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3400
3401 trace_spi_message_submit(message);
3402
3403 return ctlr->transfer(spi, message);
3404}
3405
3406/**
3407 * spi_async - asynchronous SPI transfer
3408 * @spi: device with which data will be exchanged
3409 * @message: describes the data transfers, including completion callback
3410 * Context: any (irqs may be blocked, etc)
3411 *
3412 * This call may be used in_irq and other contexts which can't sleep,
3413 * as well as from task contexts which can sleep.
3414 *
3415 * The completion callback is invoked in a context which can't sleep.
3416 * Before that invocation, the value of message->status is undefined.
3417 * When the callback is issued, message->status holds either zero (to
3418 * indicate complete success) or a negative error code. After that
3419 * callback returns, the driver which issued the transfer request may
3420 * deallocate the associated memory; it's no longer in use by any SPI
3421 * core or controller driver code.
3422 *
3423 * Note that although all messages to a spi_device are handled in
3424 * FIFO order, messages may go to different devices in other orders.
3425 * Some device might be higher priority, or have various "hard" access
3426 * time requirements, for example.
3427 *
3428 * On detection of any fault during the transfer, processing of
3429 * the entire message is aborted, and the device is deselected.
3430 * Until returning from the associated message completion callback,
3431 * no other spi_message queued to that device will be processed.
3432 * (This rule applies equally to all the synchronous transfer calls,
3433 * which are wrappers around this core asynchronous primitive.)
3434 *
3435 * Return: zero on success, else a negative error code.
3436 */
3437int spi_async(struct spi_device *spi, struct spi_message *message)
3438{
3439 struct spi_controller *ctlr = spi->controller;
3440 int ret;
3441 unsigned long flags;
3442
3443 ret = __spi_validate(spi, message);
3444 if (ret != 0)
3445 return ret;
3446
3447 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3448
3449 if (ctlr->bus_lock_flag)
3450 ret = -EBUSY;
3451 else
3452 ret = __spi_async(spi, message);
3453
3454 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3455
3456 return ret;
3457}
3458EXPORT_SYMBOL_GPL(spi_async);
3459
3460/**
3461 * spi_async_locked - version of spi_async with exclusive bus usage
3462 * @spi: device with which data will be exchanged
3463 * @message: describes the data transfers, including completion callback
3464 * Context: any (irqs may be blocked, etc)
3465 *
3466 * This call may be used in_irq and other contexts which can't sleep,
3467 * as well as from task contexts which can sleep.
3468 *
3469 * The completion callback is invoked in a context which can't sleep.
3470 * Before that invocation, the value of message->status is undefined.
3471 * When the callback is issued, message->status holds either zero (to
3472 * indicate complete success) or a negative error code. After that
3473 * callback returns, the driver which issued the transfer request may
3474 * deallocate the associated memory; it's no longer in use by any SPI
3475 * core or controller driver code.
3476 *
3477 * Note that although all messages to a spi_device are handled in
3478 * FIFO order, messages may go to different devices in other orders.
3479 * Some device might be higher priority, or have various "hard" access
3480 * time requirements, for example.
3481 *
3482 * On detection of any fault during the transfer, processing of
3483 * the entire message is aborted, and the device is deselected.
3484 * Until returning from the associated message completion callback,
3485 * no other spi_message queued to that device will be processed.
3486 * (This rule applies equally to all the synchronous transfer calls,
3487 * which are wrappers around this core asynchronous primitive.)
3488 *
3489 * Return: zero on success, else a negative error code.
3490 */
3491int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3492{
3493 struct spi_controller *ctlr = spi->controller;
3494 int ret;
3495 unsigned long flags;
3496
3497 ret = __spi_validate(spi, message);
3498 if (ret != 0)
3499 return ret;
3500
3501 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3502
3503 ret = __spi_async(spi, message);
3504
3505 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3506
3507 return ret;
3508
3509}
3510EXPORT_SYMBOL_GPL(spi_async_locked);
3511
3512/*-------------------------------------------------------------------------*/
3513
3514/* Utility methods for SPI protocol drivers, layered on
3515 * top of the core. Some other utility methods are defined as
3516 * inline functions.
3517 */
3518
3519static void spi_complete(void *arg)
3520{
3521 complete(arg);
3522}
3523
3524static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3525{
3526 DECLARE_COMPLETION_ONSTACK(done);
3527 int status;
3528 struct spi_controller *ctlr = spi->controller;
3529 unsigned long flags;
3530
3531 status = __spi_validate(spi, message);
3532 if (status != 0)
3533 return status;
3534
3535 message->complete = spi_complete;
3536 message->context = &done;
3537 message->spi = spi;
3538
3539 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3540 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3541
3542 /* If we're not using the legacy transfer method then we will
3543 * try to transfer in the calling context so special case.
3544 * This code would be less tricky if we could remove the
3545 * support for driver implemented message queues.
3546 */
3547 if (ctlr->transfer == spi_queued_transfer) {
3548 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3549
3550 trace_spi_message_submit(message);
3551
3552 status = __spi_queued_transfer(spi, message, false);
3553
3554 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3555 } else {
3556 status = spi_async_locked(spi, message);
3557 }
3558
3559 if (status == 0) {
3560 /* Push out the messages in the calling context if we
3561 * can.
3562 */
3563 if (ctlr->transfer == spi_queued_transfer) {
3564 SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3565 spi_sync_immediate);
3566 SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3567 spi_sync_immediate);
3568 __spi_pump_messages(ctlr, false);
3569 }
3570
3571 wait_for_completion(&done);
3572 status = message->status;
3573 }
3574 message->context = NULL;
3575 return status;
3576}
3577
3578/**
3579 * spi_sync - blocking/synchronous SPI data transfers
3580 * @spi: device with which data will be exchanged
3581 * @message: describes the data transfers
3582 * Context: can sleep
3583 *
3584 * This call may only be used from a context that may sleep. The sleep
3585 * is non-interruptible, and has no timeout. Low-overhead controller
3586 * drivers may DMA directly into and out of the message buffers.
3587 *
3588 * Note that the SPI device's chip select is active during the message,
3589 * and then is normally disabled between messages. Drivers for some
3590 * frequently-used devices may want to minimize costs of selecting a chip,
3591 * by leaving it selected in anticipation that the next message will go
3592 * to the same chip. (That may increase power usage.)
3593 *
3594 * Also, the caller is guaranteeing that the memory associated with the
3595 * message will not be freed before this call returns.
3596 *
3597 * Return: zero on success, else a negative error code.
3598 */
3599int spi_sync(struct spi_device *spi, struct spi_message *message)
3600{
3601 int ret;
3602
3603 mutex_lock(&spi->controller->bus_lock_mutex);
3604 ret = __spi_sync(spi, message);
3605 mutex_unlock(&spi->controller->bus_lock_mutex);
3606
3607 return ret;
3608}
3609EXPORT_SYMBOL_GPL(spi_sync);
3610
3611/**
3612 * spi_sync_locked - version of spi_sync with exclusive bus usage
3613 * @spi: device with which data will be exchanged
3614 * @message: describes the data transfers
3615 * Context: can sleep
3616 *
3617 * This call may only be used from a context that may sleep. The sleep
3618 * is non-interruptible, and has no timeout. Low-overhead controller
3619 * drivers may DMA directly into and out of the message buffers.
3620 *
3621 * This call should be used by drivers that require exclusive access to the
3622 * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3623 * be released by a spi_bus_unlock call when the exclusive access is over.
3624 *
3625 * Return: zero on success, else a negative error code.
3626 */
3627int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3628{
3629 return __spi_sync(spi, message);
3630}
3631EXPORT_SYMBOL_GPL(spi_sync_locked);
3632
3633/**
3634 * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3635 * @ctlr: SPI bus master that should be locked for exclusive bus access
3636 * Context: can sleep
3637 *
3638 * This call may only be used from a context that may sleep. The sleep
3639 * is non-interruptible, and has no timeout.
3640 *
3641 * This call should be used by drivers that require exclusive access to the
3642 * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3643 * exclusive access is over. Data transfer must be done by spi_sync_locked
3644 * and spi_async_locked calls when the SPI bus lock is held.
3645 *
3646 * Return: always zero.
3647 */
3648int spi_bus_lock(struct spi_controller *ctlr)
3649{
3650 unsigned long flags;
3651
3652 mutex_lock(&ctlr->bus_lock_mutex);
3653
3654 spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3655 ctlr->bus_lock_flag = 1;
3656 spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3657
3658 /* mutex remains locked until spi_bus_unlock is called */
3659
3660 return 0;
3661}
3662EXPORT_SYMBOL_GPL(spi_bus_lock);
3663
3664/**
3665 * spi_bus_unlock - release the lock for exclusive SPI bus usage
3666 * @ctlr: SPI bus master that was locked for exclusive bus access
3667 * Context: can sleep
3668 *
3669 * This call may only be used from a context that may sleep. The sleep
3670 * is non-interruptible, and has no timeout.
3671 *
3672 * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3673 * call.
3674 *
3675 * Return: always zero.
3676 */
3677int spi_bus_unlock(struct spi_controller *ctlr)
3678{
3679 ctlr->bus_lock_flag = 0;
3680
3681 mutex_unlock(&ctlr->bus_lock_mutex);
3682
3683 return 0;
3684}
3685EXPORT_SYMBOL_GPL(spi_bus_unlock);
3686
3687/* portable code must never pass more than 32 bytes */
3688#define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
3689
3690static u8 *buf;
3691
3692/**
3693 * spi_write_then_read - SPI synchronous write followed by read
3694 * @spi: device with which data will be exchanged
3695 * @txbuf: data to be written (need not be dma-safe)
3696 * @n_tx: size of txbuf, in bytes
3697 * @rxbuf: buffer into which data will be read (need not be dma-safe)
3698 * @n_rx: size of rxbuf, in bytes
3699 * Context: can sleep
3700 *
3701 * This performs a half duplex MicroWire style transaction with the
3702 * device, sending txbuf and then reading rxbuf. The return value
3703 * is zero for success, else a negative errno status code.
3704 * This call may only be used from a context that may sleep.
3705 *
3706 * Parameters to this routine are always copied using a small buffer;
3707 * portable code should never use this for more than 32 bytes.
3708 * Performance-sensitive or bulk transfer code should instead use
3709 * spi_{async,sync}() calls with dma-safe buffers.
3710 *
3711 * Return: zero on success, else a negative error code.
3712 */
3713int spi_write_then_read(struct spi_device *spi,
3714 const void *txbuf, unsigned n_tx,
3715 void *rxbuf, unsigned n_rx)
3716{
3717 static DEFINE_MUTEX(lock);
3718
3719 int status;
3720 struct spi_message message;
3721 struct spi_transfer x[2];
3722 u8 *local_buf;
3723
3724 /* Use preallocated DMA-safe buffer if we can. We can't avoid
3725 * copying here, (as a pure convenience thing), but we can
3726 * keep heap costs out of the hot path unless someone else is
3727 * using the pre-allocated buffer or the transfer is too large.
3728 */
3729 if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
3730 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
3731 GFP_KERNEL | GFP_DMA);
3732 if (!local_buf)
3733 return -ENOMEM;
3734 } else {
3735 local_buf = buf;
3736 }
3737
3738 spi_message_init(&message);
3739 memset(x, 0, sizeof(x));
3740 if (n_tx) {
3741 x[0].len = n_tx;
3742 spi_message_add_tail(&x[0], &message);
3743 }
3744 if (n_rx) {
3745 x[1].len = n_rx;
3746 spi_message_add_tail(&x[1], &message);
3747 }
3748
3749 memcpy(local_buf, txbuf, n_tx);
3750 x[0].tx_buf = local_buf;
3751 x[1].rx_buf = local_buf + n_tx;
3752
3753 /* do the i/o */
3754 status = spi_sync(spi, &message);
3755 if (status == 0)
3756 memcpy(rxbuf, x[1].rx_buf, n_rx);
3757
3758 if (x[0].tx_buf == buf)
3759 mutex_unlock(&lock);
3760 else
3761 kfree(local_buf);
3762
3763 return status;
3764}
3765EXPORT_SYMBOL_GPL(spi_write_then_read);
3766
3767/*-------------------------------------------------------------------------*/
3768
3769#if IS_ENABLED(CONFIG_OF)
3770/* must call put_device() when done with returned spi_device device */
3771struct spi_device *of_find_spi_device_by_node(struct device_node *node)
3772{
3773 struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
3774
3775 return dev ? to_spi_device(dev) : NULL;
3776}
3777EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
3778#endif /* IS_ENABLED(CONFIG_OF) */
3779
3780#if IS_ENABLED(CONFIG_OF_DYNAMIC)
3781/* the spi controllers are not using spi_bus, so we find it with another way */
3782static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
3783{
3784 struct device *dev;
3785
3786 dev = class_find_device_by_of_node(&spi_master_class, node);
3787 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3788 dev = class_find_device_by_of_node(&spi_slave_class, node);
3789 if (!dev)
3790 return NULL;
3791
3792 /* reference got in class_find_device */
3793 return container_of(dev, struct spi_controller, dev);
3794}
3795
3796static int of_spi_notify(struct notifier_block *nb, unsigned long action,
3797 void *arg)
3798{
3799 struct of_reconfig_data *rd = arg;
3800 struct spi_controller *ctlr;
3801 struct spi_device *spi;
3802
3803 switch (of_reconfig_get_state_change(action, arg)) {
3804 case OF_RECONFIG_CHANGE_ADD:
3805 ctlr = of_find_spi_controller_by_node(rd->dn->parent);
3806 if (ctlr == NULL)
3807 return NOTIFY_OK; /* not for us */
3808
3809 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
3810 put_device(&ctlr->dev);
3811 return NOTIFY_OK;
3812 }
3813
3814 spi = of_register_spi_device(ctlr, rd->dn);
3815 put_device(&ctlr->dev);
3816
3817 if (IS_ERR(spi)) {
3818 pr_err("%s: failed to create for '%pOF'\n",
3819 __func__, rd->dn);
3820 of_node_clear_flag(rd->dn, OF_POPULATED);
3821 return notifier_from_errno(PTR_ERR(spi));
3822 }
3823 break;
3824
3825 case OF_RECONFIG_CHANGE_REMOVE:
3826 /* already depopulated? */
3827 if (!of_node_check_flag(rd->dn, OF_POPULATED))
3828 return NOTIFY_OK;
3829
3830 /* find our device by node */
3831 spi = of_find_spi_device_by_node(rd->dn);
3832 if (spi == NULL)
3833 return NOTIFY_OK; /* no? not meant for us */
3834
3835 /* unregister takes one ref away */
3836 spi_unregister_device(spi);
3837
3838 /* and put the reference of the find */
3839 put_device(&spi->dev);
3840 break;
3841 }
3842
3843 return NOTIFY_OK;
3844}
3845
3846static struct notifier_block spi_of_notifier = {
3847 .notifier_call = of_spi_notify,
3848};
3849#else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3850extern struct notifier_block spi_of_notifier;
3851#endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3852
3853#if IS_ENABLED(CONFIG_ACPI)
3854static int spi_acpi_controller_match(struct device *dev, const void *data)
3855{
3856 return ACPI_COMPANION(dev->parent) == data;
3857}
3858
3859static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
3860{
3861 struct device *dev;
3862
3863 dev = class_find_device(&spi_master_class, NULL, adev,
3864 spi_acpi_controller_match);
3865 if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3866 dev = class_find_device(&spi_slave_class, NULL, adev,
3867 spi_acpi_controller_match);
3868 if (!dev)
3869 return NULL;
3870
3871 return container_of(dev, struct spi_controller, dev);
3872}
3873
3874static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
3875{
3876 struct device *dev;
3877
3878 dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
3879 return dev ? to_spi_device(dev) : NULL;
3880}
3881
3882static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
3883 void *arg)
3884{
3885 struct acpi_device *adev = arg;
3886 struct spi_controller *ctlr;
3887 struct spi_device *spi;
3888
3889 switch (value) {
3890 case ACPI_RECONFIG_DEVICE_ADD:
3891 ctlr = acpi_spi_find_controller_by_adev(adev->parent);
3892 if (!ctlr)
3893 break;
3894
3895 acpi_register_spi_device(ctlr, adev);
3896 put_device(&ctlr->dev);
3897 break;
3898 case ACPI_RECONFIG_DEVICE_REMOVE:
3899 if (!acpi_device_enumerated(adev))
3900 break;
3901
3902 spi = acpi_spi_find_device_by_adev(adev);
3903 if (!spi)
3904 break;
3905
3906 spi_unregister_device(spi);
3907 put_device(&spi->dev);
3908 break;
3909 }
3910
3911 return NOTIFY_OK;
3912}
3913
3914static struct notifier_block spi_acpi_notifier = {
3915 .notifier_call = acpi_spi_notify,
3916};
3917#else
3918extern struct notifier_block spi_acpi_notifier;
3919#endif
3920
3921static int __init spi_init(void)
3922{
3923 int status;
3924
3925 buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
3926 if (!buf) {
3927 status = -ENOMEM;
3928 goto err0;
3929 }
3930
3931 status = bus_register(&spi_bus_type);
3932 if (status < 0)
3933 goto err1;
3934
3935 status = class_register(&spi_master_class);
3936 if (status < 0)
3937 goto err2;
3938
3939 if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
3940 status = class_register(&spi_slave_class);
3941 if (status < 0)
3942 goto err3;
3943 }
3944
3945 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
3946 WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
3947 if (IS_ENABLED(CONFIG_ACPI))
3948 WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
3949
3950 return 0;
3951
3952err3:
3953 class_unregister(&spi_master_class);
3954err2:
3955 bus_unregister(&spi_bus_type);
3956err1:
3957 kfree(buf);
3958 buf = NULL;
3959err0:
3960 return status;
3961}
3962
3963/* board_info is normally registered in arch_initcall(),
3964 * but even essential drivers wait till later
3965 *
3966 * REVISIT only boardinfo really needs static linking. the rest (device and
3967 * driver registration) _could_ be dynamically linked (modular) ... costs
3968 * include needing to have boardinfo data structures be much more public.
3969 */
3970postcore_initcall(spi_init);