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