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