Debian Codegraph @

drivers/spi/spi.c

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