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