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