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