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