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