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