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