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