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