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