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