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