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