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