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