Merge tag 'for-v3.13/clock-fixes-a' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-drm-fsl-dcu.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  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 #include <linux/kernel.h>
23 #include <linux/kmod.h>
24 #include <linux/device.h>
25 #include <linux/init.h>
26 #include <linux/cache.h>
27 #include <linux/mutex.h>
28 #include <linux/of_device.h>
29 #include <linux/of_irq.h>
30 #include <linux/slab.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/spi/spi.h>
33 #include <linux/of_gpio.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/export.h>
36 #include <linux/sched/rt.h>
37 #include <linux/delay.h>
38 #include <linux/kthread.h>
39 #include <linux/ioport.h>
40 #include <linux/acpi.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
62         return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
63 }
64 static DEVICE_ATTR_RO(modalias);
65
66 static struct attribute *spi_dev_attrs[] = {
67         &dev_attr_modalias.attr,
68         NULL,
69 };
70 ATTRIBUTE_GROUPS(spi_dev);
71
72 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
73  * and the sysfs version makes coldplug work too.
74  */
75
76 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
77                                                 const struct spi_device *sdev)
78 {
79         while (id->name[0]) {
80                 if (!strcmp(sdev->modalias, id->name))
81                         return id;
82                 id++;
83         }
84         return NULL;
85 }
86
87 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
88 {
89         const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
90
91         return spi_match_id(sdrv->id_table, sdev);
92 }
93 EXPORT_SYMBOL_GPL(spi_get_device_id);
94
95 static int spi_match_device(struct device *dev, struct device_driver *drv)
96 {
97         const struct spi_device *spi = to_spi_device(dev);
98         const struct spi_driver *sdrv = to_spi_driver(drv);
99
100         /* Attempt an OF style match */
101         if (of_driver_match_device(dev, drv))
102                 return 1;
103
104         /* Then try ACPI */
105         if (acpi_driver_match_device(dev, drv))
106                 return 1;
107
108         if (sdrv->id_table)
109                 return !!spi_match_id(sdrv->id_table, spi);
110
111         return strcmp(spi->modalias, drv->name) == 0;
112 }
113
114 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
115 {
116         const struct spi_device         *spi = to_spi_device(dev);
117
118         add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
119         return 0;
120 }
121
122 #ifdef CONFIG_PM_SLEEP
123 static int spi_legacy_suspend(struct device *dev, pm_message_t message)
124 {
125         int                     value = 0;
126         struct spi_driver       *drv = to_spi_driver(dev->driver);
127
128         /* suspend will stop irqs and dma; no more i/o */
129         if (drv) {
130                 if (drv->suspend)
131                         value = drv->suspend(to_spi_device(dev), message);
132                 else
133                         dev_dbg(dev, "... can't suspend\n");
134         }
135         return value;
136 }
137
138 static int spi_legacy_resume(struct device *dev)
139 {
140         int                     value = 0;
141         struct spi_driver       *drv = to_spi_driver(dev->driver);
142
143         /* resume may restart the i/o queue */
144         if (drv) {
145                 if (drv->resume)
146                         value = drv->resume(to_spi_device(dev));
147                 else
148                         dev_dbg(dev, "... can't resume\n");
149         }
150         return value;
151 }
152
153 static int spi_pm_suspend(struct device *dev)
154 {
155         const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
156
157         if (pm)
158                 return pm_generic_suspend(dev);
159         else
160                 return spi_legacy_suspend(dev, PMSG_SUSPEND);
161 }
162
163 static int spi_pm_resume(struct device *dev)
164 {
165         const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
166
167         if (pm)
168                 return pm_generic_resume(dev);
169         else
170                 return spi_legacy_resume(dev);
171 }
172
173 static int spi_pm_freeze(struct device *dev)
174 {
175         const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
176
177         if (pm)
178                 return pm_generic_freeze(dev);
179         else
180                 return spi_legacy_suspend(dev, PMSG_FREEZE);
181 }
182
183 static int spi_pm_thaw(struct device *dev)
184 {
185         const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
186
187         if (pm)
188                 return pm_generic_thaw(dev);
189         else
190                 return spi_legacy_resume(dev);
191 }
192
193 static int spi_pm_poweroff(struct device *dev)
194 {
195         const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
196
197         if (pm)
198                 return pm_generic_poweroff(dev);
199         else
200                 return spi_legacy_suspend(dev, PMSG_HIBERNATE);
201 }
202
203 static int spi_pm_restore(struct device *dev)
204 {
205         const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
206
207         if (pm)
208                 return pm_generic_restore(dev);
209         else
210                 return spi_legacy_resume(dev);
211 }
212 #else
213 #define spi_pm_suspend  NULL
214 #define spi_pm_resume   NULL
215 #define spi_pm_freeze   NULL
216 #define spi_pm_thaw     NULL
217 #define spi_pm_poweroff NULL
218 #define spi_pm_restore  NULL
219 #endif
220
221 static const struct dev_pm_ops spi_pm = {
222         .suspend = spi_pm_suspend,
223         .resume = spi_pm_resume,
224         .freeze = spi_pm_freeze,
225         .thaw = spi_pm_thaw,
226         .poweroff = spi_pm_poweroff,
227         .restore = spi_pm_restore,
228         SET_RUNTIME_PM_OPS(
229                 pm_generic_runtime_suspend,
230                 pm_generic_runtime_resume,
231                 NULL
232         )
233 };
234
235 struct bus_type spi_bus_type = {
236         .name           = "spi",
237         .dev_groups     = spi_dev_groups,
238         .match          = spi_match_device,
239         .uevent         = spi_uevent,
240         .pm             = &spi_pm,
241 };
242 EXPORT_SYMBOL_GPL(spi_bus_type);
243
244
245 static int spi_drv_probe(struct device *dev)
246 {
247         const struct spi_driver         *sdrv = to_spi_driver(dev->driver);
248
249         return sdrv->probe(to_spi_device(dev));
250 }
251
252 static int spi_drv_remove(struct device *dev)
253 {
254         const struct spi_driver         *sdrv = to_spi_driver(dev->driver);
255
256         return sdrv->remove(to_spi_device(dev));
257 }
258
259 static void spi_drv_shutdown(struct device *dev)
260 {
261         const struct spi_driver         *sdrv = to_spi_driver(dev->driver);
262
263         sdrv->shutdown(to_spi_device(dev));
264 }
265
266 /**
267  * spi_register_driver - register a SPI driver
268  * @sdrv: the driver to register
269  * Context: can sleep
270  */
271 int spi_register_driver(struct spi_driver *sdrv)
272 {
273         sdrv->driver.bus = &spi_bus_type;
274         if (sdrv->probe)
275                 sdrv->driver.probe = spi_drv_probe;
276         if (sdrv->remove)
277                 sdrv->driver.remove = spi_drv_remove;
278         if (sdrv->shutdown)
279                 sdrv->driver.shutdown = spi_drv_shutdown;
280         return driver_register(&sdrv->driver);
281 }
282 EXPORT_SYMBOL_GPL(spi_register_driver);
283
284 /*-------------------------------------------------------------------------*/
285
286 /* SPI devices should normally not be created by SPI device drivers; that
287  * would make them board-specific.  Similarly with SPI master drivers.
288  * Device registration normally goes into like arch/.../mach.../board-YYY.c
289  * with other readonly (flashable) information about mainboard devices.
290  */
291
292 struct boardinfo {
293         struct list_head        list;
294         struct spi_board_info   board_info;
295 };
296
297 static LIST_HEAD(board_list);
298 static LIST_HEAD(spi_master_list);
299
300 /*
301  * Used to protect add/del opertion for board_info list and
302  * spi_master list, and their matching process
303  */
304 static DEFINE_MUTEX(board_lock);
305
306 /**
307  * spi_alloc_device - Allocate a new SPI device
308  * @master: Controller to which device is connected
309  * Context: can sleep
310  *
311  * Allows a driver to allocate and initialize a spi_device without
312  * registering it immediately.  This allows a driver to directly
313  * fill the spi_device with device parameters before calling
314  * spi_add_device() on it.
315  *
316  * Caller is responsible to call spi_add_device() on the returned
317  * spi_device structure to add it to the SPI master.  If the caller
318  * needs to discard the spi_device without adding it, then it should
319  * call spi_dev_put() on it.
320  *
321  * Returns a pointer to the new device, or NULL.
322  */
323 struct spi_device *spi_alloc_device(struct spi_master *master)
324 {
325         struct spi_device       *spi;
326         struct device           *dev = master->dev.parent;
327
328         if (!spi_master_get(master))
329                 return NULL;
330
331         spi = kzalloc(sizeof(*spi), GFP_KERNEL);
332         if (!spi) {
333                 dev_err(dev, "cannot alloc spi_device\n");
334                 spi_master_put(master);
335                 return NULL;
336         }
337
338         spi->master = master;
339         spi->dev.parent = &master->dev;
340         spi->dev.bus = &spi_bus_type;
341         spi->dev.release = spidev_release;
342         spi->cs_gpio = -ENOENT;
343         device_initialize(&spi->dev);
344         return spi;
345 }
346 EXPORT_SYMBOL_GPL(spi_alloc_device);
347
348 /**
349  * spi_add_device - Add spi_device allocated with spi_alloc_device
350  * @spi: spi_device to register
351  *
352  * Companion function to spi_alloc_device.  Devices allocated with
353  * spi_alloc_device can be added onto the spi bus with this function.
354  *
355  * Returns 0 on success; negative errno on failure
356  */
357 int spi_add_device(struct spi_device *spi)
358 {
359         static DEFINE_MUTEX(spi_add_lock);
360         struct spi_master *master = spi->master;
361         struct device *dev = master->dev.parent;
362         struct device *d;
363         int status;
364
365         /* Chipselects are numbered 0..max; validate. */
366         if (spi->chip_select >= master->num_chipselect) {
367                 dev_err(dev, "cs%d >= max %d\n",
368                         spi->chip_select,
369                         master->num_chipselect);
370                 return -EINVAL;
371         }
372
373         /* Set the bus ID string */
374         dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->master->dev),
375                         spi->chip_select);
376
377
378         /* We need to make sure there's no other device with this
379          * chipselect **BEFORE** we call setup(), else we'll trash
380          * its configuration.  Lock against concurrent add() calls.
381          */
382         mutex_lock(&spi_add_lock);
383
384         d = bus_find_device_by_name(&spi_bus_type, NULL, dev_name(&spi->dev));
385         if (d != NULL) {
386                 dev_err(dev, "chipselect %d already in use\n",
387                                 spi->chip_select);
388                 put_device(d);
389                 status = -EBUSY;
390                 goto done;
391         }
392
393         if (master->cs_gpios)
394                 spi->cs_gpio = master->cs_gpios[spi->chip_select];
395
396         /* Drivers may modify this initial i/o setup, but will
397          * normally rely on the device being setup.  Devices
398          * using SPI_CS_HIGH can't coexist well otherwise...
399          */
400         status = spi_setup(spi);
401         if (status < 0) {
402                 dev_err(dev, "can't setup %s, status %d\n",
403                                 dev_name(&spi->dev), status);
404                 goto done;
405         }
406
407         /* Device may be bound to an active driver when this returns */
408         status = device_add(&spi->dev);
409         if (status < 0)
410                 dev_err(dev, "can't add %s, status %d\n",
411                                 dev_name(&spi->dev), status);
412         else
413                 dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
414
415 done:
416         mutex_unlock(&spi_add_lock);
417         return status;
418 }
419 EXPORT_SYMBOL_GPL(spi_add_device);
420
421 /**
422  * spi_new_device - instantiate one new SPI device
423  * @master: Controller to which device is connected
424  * @chip: Describes the SPI device
425  * Context: can sleep
426  *
427  * On typical mainboards, this is purely internal; and it's not needed
428  * after board init creates the hard-wired devices.  Some development
429  * platforms may not be able to use spi_register_board_info though, and
430  * this is exported so that for example a USB or parport based adapter
431  * driver could add devices (which it would learn about out-of-band).
432  *
433  * Returns the new device, or NULL.
434  */
435 struct spi_device *spi_new_device(struct spi_master *master,
436                                   struct spi_board_info *chip)
437 {
438         struct spi_device       *proxy;
439         int                     status;
440
441         /* NOTE:  caller did any chip->bus_num checks necessary.
442          *
443          * Also, unless we change the return value convention to use
444          * error-or-pointer (not NULL-or-pointer), troubleshootability
445          * suggests syslogged diagnostics are best here (ugh).
446          */
447
448         proxy = spi_alloc_device(master);
449         if (!proxy)
450                 return NULL;
451
452         WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
453
454         proxy->chip_select = chip->chip_select;
455         proxy->max_speed_hz = chip->max_speed_hz;
456         proxy->mode = chip->mode;
457         proxy->irq = chip->irq;
458         strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
459         proxy->dev.platform_data = (void *) chip->platform_data;
460         proxy->controller_data = chip->controller_data;
461         proxy->controller_state = NULL;
462
463         status = spi_add_device(proxy);
464         if (status < 0) {
465                 spi_dev_put(proxy);
466                 return NULL;
467         }
468
469         return proxy;
470 }
471 EXPORT_SYMBOL_GPL(spi_new_device);
472
473 static void spi_match_master_to_boardinfo(struct spi_master *master,
474                                 struct spi_board_info *bi)
475 {
476         struct spi_device *dev;
477
478         if (master->bus_num != bi->bus_num)
479                 return;
480
481         dev = spi_new_device(master, bi);
482         if (!dev)
483                 dev_err(master->dev.parent, "can't create new device for %s\n",
484                         bi->modalias);
485 }
486
487 /**
488  * spi_register_board_info - register SPI devices for a given board
489  * @info: array of chip descriptors
490  * @n: how many descriptors are provided
491  * Context: can sleep
492  *
493  * Board-specific early init code calls this (probably during arch_initcall)
494  * with segments of the SPI device table.  Any device nodes are created later,
495  * after the relevant parent SPI controller (bus_num) is defined.  We keep
496  * this table of devices forever, so that reloading a controller driver will
497  * not make Linux forget about these hard-wired devices.
498  *
499  * Other code can also call this, e.g. a particular add-on board might provide
500  * SPI devices through its expansion connector, so code initializing that board
501  * would naturally declare its SPI devices.
502  *
503  * The board info passed can safely be __initdata ... but be careful of
504  * any embedded pointers (platform_data, etc), they're copied as-is.
505  */
506 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
507 {
508         struct boardinfo *bi;
509         int i;
510
511         bi = kzalloc(n * sizeof(*bi), GFP_KERNEL);
512         if (!bi)
513                 return -ENOMEM;
514
515         for (i = 0; i < n; i++, bi++, info++) {
516                 struct spi_master *master;
517
518                 memcpy(&bi->board_info, info, sizeof(*info));
519                 mutex_lock(&board_lock);
520                 list_add_tail(&bi->list, &board_list);
521                 list_for_each_entry(master, &spi_master_list, list)
522                         spi_match_master_to_boardinfo(master, &bi->board_info);
523                 mutex_unlock(&board_lock);
524         }
525
526         return 0;
527 }
528
529 /*-------------------------------------------------------------------------*/
530
531 static void spi_set_cs(struct spi_device *spi, bool enable)
532 {
533         if (spi->mode & SPI_CS_HIGH)
534                 enable = !enable;
535
536         if (spi->cs_gpio >= 0)
537                 gpio_set_value(spi->cs_gpio, !enable);
538         else if (spi->master->set_cs)
539                 spi->master->set_cs(spi, !enable);
540 }
541
542 /*
543  * spi_transfer_one_message - Default implementation of transfer_one_message()
544  *
545  * This is a standard implementation of transfer_one_message() for
546  * drivers which impelment a transfer_one() operation.  It provides
547  * standard handling of delays and chip select management.
548  */
549 static int spi_transfer_one_message(struct spi_master *master,
550                                     struct spi_message *msg)
551 {
552         struct spi_transfer *xfer;
553         bool cur_cs = true;
554         bool keep_cs = false;
555         int ret = 0;
556
557         spi_set_cs(msg->spi, true);
558
559         list_for_each_entry(xfer, &msg->transfers, transfer_list) {
560                 trace_spi_transfer_start(msg, xfer);
561
562                 INIT_COMPLETION(master->xfer_completion);
563
564                 ret = master->transfer_one(master, msg->spi, xfer);
565                 if (ret < 0) {
566                         dev_err(&msg->spi->dev,
567                                 "SPI transfer failed: %d\n", ret);
568                         goto out;
569                 }
570
571                 if (ret > 0)
572                         wait_for_completion(&master->xfer_completion);
573
574                 trace_spi_transfer_stop(msg, xfer);
575
576                 if (msg->status != -EINPROGRESS)
577                         goto out;
578
579                 if (xfer->delay_usecs)
580                         udelay(xfer->delay_usecs);
581
582                 if (xfer->cs_change) {
583                         if (list_is_last(&xfer->transfer_list,
584                                          &msg->transfers)) {
585                                 keep_cs = true;
586                         } else {
587                                 cur_cs = !cur_cs;
588                                 spi_set_cs(msg->spi, cur_cs);
589                         }
590                 }
591
592                 msg->actual_length += xfer->len;
593         }
594
595 out:
596         if (ret != 0 || !keep_cs)
597                 spi_set_cs(msg->spi, false);
598
599         if (msg->status == -EINPROGRESS)
600                 msg->status = ret;
601
602         spi_finalize_current_message(master);
603
604         return ret;
605 }
606
607 /**
608  * spi_finalize_current_transfer - report completion of a transfer
609  *
610  * Called by SPI drivers using the core transfer_one_message()
611  * implementation to notify it that the current interrupt driven
612  * transfer has finised and the next one may be scheduled.
613  */
614 void spi_finalize_current_transfer(struct spi_master *master)
615 {
616         complete(&master->xfer_completion);
617 }
618 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
619
620 /**
621  * spi_pump_messages - kthread work function which processes spi message queue
622  * @work: pointer to kthread work struct contained in the master struct
623  *
624  * This function checks if there is any spi message in the queue that
625  * needs processing and if so call out to the driver to initialize hardware
626  * and transfer each message.
627  *
628  */
629 static void spi_pump_messages(struct kthread_work *work)
630 {
631         struct spi_master *master =
632                 container_of(work, struct spi_master, pump_messages);
633         unsigned long flags;
634         bool was_busy = false;
635         int ret;
636
637         /* Lock queue and check for queue work */
638         spin_lock_irqsave(&master->queue_lock, flags);
639         if (list_empty(&master->queue) || !master->running) {
640                 if (!master->busy) {
641                         spin_unlock_irqrestore(&master->queue_lock, flags);
642                         return;
643                 }
644                 master->busy = false;
645                 spin_unlock_irqrestore(&master->queue_lock, flags);
646                 if (master->unprepare_transfer_hardware &&
647                     master->unprepare_transfer_hardware(master))
648                         dev_err(&master->dev,
649                                 "failed to unprepare transfer hardware\n");
650                 if (master->auto_runtime_pm) {
651                         pm_runtime_mark_last_busy(master->dev.parent);
652                         pm_runtime_put_autosuspend(master->dev.parent);
653                 }
654                 trace_spi_master_idle(master);
655                 return;
656         }
657
658         /* Make sure we are not already running a message */
659         if (master->cur_msg) {
660                 spin_unlock_irqrestore(&master->queue_lock, flags);
661                 return;
662         }
663         /* Extract head of queue */
664         master->cur_msg =
665             list_entry(master->queue.next, struct spi_message, queue);
666
667         list_del_init(&master->cur_msg->queue);
668         if (master->busy)
669                 was_busy = true;
670         else
671                 master->busy = true;
672         spin_unlock_irqrestore(&master->queue_lock, flags);
673
674         if (!was_busy && master->auto_runtime_pm) {
675                 ret = pm_runtime_get_sync(master->dev.parent);
676                 if (ret < 0) {
677                         dev_err(&master->dev, "Failed to power device: %d\n",
678                                 ret);
679                         return;
680                 }
681         }
682
683         if (!was_busy)
684                 trace_spi_master_busy(master);
685
686         if (!was_busy && master->prepare_transfer_hardware) {
687                 ret = master->prepare_transfer_hardware(master);
688                 if (ret) {
689                         dev_err(&master->dev,
690                                 "failed to prepare transfer hardware\n");
691
692                         if (master->auto_runtime_pm)
693                                 pm_runtime_put(master->dev.parent);
694                         return;
695                 }
696         }
697
698         trace_spi_message_start(master->cur_msg);
699
700         if (master->prepare_message) {
701                 ret = master->prepare_message(master, master->cur_msg);
702                 if (ret) {
703                         dev_err(&master->dev,
704                                 "failed to prepare message: %d\n", ret);
705                         master->cur_msg->status = ret;
706                         spi_finalize_current_message(master);
707                         return;
708                 }
709                 master->cur_msg_prepared = true;
710         }
711
712         ret = master->transfer_one_message(master, master->cur_msg);
713         if (ret) {
714                 dev_err(&master->dev,
715                         "failed to transfer one message from queue\n");
716                 return;
717         }
718 }
719
720 static int spi_init_queue(struct spi_master *master)
721 {
722         struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
723
724         INIT_LIST_HEAD(&master->queue);
725         spin_lock_init(&master->queue_lock);
726
727         master->running = false;
728         master->busy = false;
729
730         init_kthread_worker(&master->kworker);
731         master->kworker_task = kthread_run(kthread_worker_fn,
732                                            &master->kworker, "%s",
733                                            dev_name(&master->dev));
734         if (IS_ERR(master->kworker_task)) {
735                 dev_err(&master->dev, "failed to create message pump task\n");
736                 return -ENOMEM;
737         }
738         init_kthread_work(&master->pump_messages, spi_pump_messages);
739
740         /*
741          * Master config will indicate if this controller should run the
742          * message pump with high (realtime) priority to reduce the transfer
743          * latency on the bus by minimising the delay between a transfer
744          * request and the scheduling of the message pump thread. Without this
745          * setting the message pump thread will remain at default priority.
746          */
747         if (master->rt) {
748                 dev_info(&master->dev,
749                         "will run message pump with realtime priority\n");
750                 sched_setscheduler(master->kworker_task, SCHED_FIFO, &param);
751         }
752
753         return 0;
754 }
755
756 /**
757  * spi_get_next_queued_message() - called by driver to check for queued
758  * messages
759  * @master: the master to check for queued messages
760  *
761  * If there are more messages in the queue, the next message is returned from
762  * this call.
763  */
764 struct spi_message *spi_get_next_queued_message(struct spi_master *master)
765 {
766         struct spi_message *next;
767         unsigned long flags;
768
769         /* get a pointer to the next message, if any */
770         spin_lock_irqsave(&master->queue_lock, flags);
771         if (list_empty(&master->queue))
772                 next = NULL;
773         else
774                 next = list_entry(master->queue.next,
775                                   struct spi_message, queue);
776         spin_unlock_irqrestore(&master->queue_lock, flags);
777
778         return next;
779 }
780 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
781
782 /**
783  * spi_finalize_current_message() - the current message is complete
784  * @master: the master to return the message to
785  *
786  * Called by the driver to notify the core that the message in the front of the
787  * queue is complete and can be removed from the queue.
788  */
789 void spi_finalize_current_message(struct spi_master *master)
790 {
791         struct spi_message *mesg;
792         unsigned long flags;
793         int ret;
794
795         spin_lock_irqsave(&master->queue_lock, flags);
796         mesg = master->cur_msg;
797         master->cur_msg = NULL;
798
799         queue_kthread_work(&master->kworker, &master->pump_messages);
800         spin_unlock_irqrestore(&master->queue_lock, flags);
801
802         if (master->cur_msg_prepared && master->unprepare_message) {
803                 ret = master->unprepare_message(master, mesg);
804                 if (ret) {
805                         dev_err(&master->dev,
806                                 "failed to unprepare message: %d\n", ret);
807                 }
808         }
809         master->cur_msg_prepared = false;
810
811         mesg->state = NULL;
812         if (mesg->complete)
813                 mesg->complete(mesg->context);
814
815         trace_spi_message_done(mesg);
816 }
817 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
818
819 static int spi_start_queue(struct spi_master *master)
820 {
821         unsigned long flags;
822
823         spin_lock_irqsave(&master->queue_lock, flags);
824
825         if (master->running || master->busy) {
826                 spin_unlock_irqrestore(&master->queue_lock, flags);
827                 return -EBUSY;
828         }
829
830         master->running = true;
831         master->cur_msg = NULL;
832         spin_unlock_irqrestore(&master->queue_lock, flags);
833
834         queue_kthread_work(&master->kworker, &master->pump_messages);
835
836         return 0;
837 }
838
839 static int spi_stop_queue(struct spi_master *master)
840 {
841         unsigned long flags;
842         unsigned limit = 500;
843         int ret = 0;
844
845         spin_lock_irqsave(&master->queue_lock, flags);
846
847         /*
848          * This is a bit lame, but is optimized for the common execution path.
849          * A wait_queue on the master->busy could be used, but then the common
850          * execution path (pump_messages) would be required to call wake_up or
851          * friends on every SPI message. Do this instead.
852          */
853         while ((!list_empty(&master->queue) || master->busy) && limit--) {
854                 spin_unlock_irqrestore(&master->queue_lock, flags);
855                 msleep(10);
856                 spin_lock_irqsave(&master->queue_lock, flags);
857         }
858
859         if (!list_empty(&master->queue) || master->busy)
860                 ret = -EBUSY;
861         else
862                 master->running = false;
863
864         spin_unlock_irqrestore(&master->queue_lock, flags);
865
866         if (ret) {
867                 dev_warn(&master->dev,
868                          "could not stop message queue\n");
869                 return ret;
870         }
871         return ret;
872 }
873
874 static int spi_destroy_queue(struct spi_master *master)
875 {
876         int ret;
877
878         ret = spi_stop_queue(master);
879
880         /*
881          * flush_kthread_worker will block until all work is done.
882          * If the reason that stop_queue timed out is that the work will never
883          * finish, then it does no good to call flush/stop thread, so
884          * return anyway.
885          */
886         if (ret) {
887                 dev_err(&master->dev, "problem destroying queue\n");
888                 return ret;
889         }
890
891         flush_kthread_worker(&master->kworker);
892         kthread_stop(master->kworker_task);
893
894         return 0;
895 }
896
897 /**
898  * spi_queued_transfer - transfer function for queued transfers
899  * @spi: spi device which is requesting transfer
900  * @msg: spi message which is to handled is queued to driver queue
901  */
902 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
903 {
904         struct spi_master *master = spi->master;
905         unsigned long flags;
906
907         spin_lock_irqsave(&master->queue_lock, flags);
908
909         if (!master->running) {
910                 spin_unlock_irqrestore(&master->queue_lock, flags);
911                 return -ESHUTDOWN;
912         }
913         msg->actual_length = 0;
914         msg->status = -EINPROGRESS;
915
916         list_add_tail(&msg->queue, &master->queue);
917         if (!master->busy)
918                 queue_kthread_work(&master->kworker, &master->pump_messages);
919
920         spin_unlock_irqrestore(&master->queue_lock, flags);
921         return 0;
922 }
923
924 static int spi_master_initialize_queue(struct spi_master *master)
925 {
926         int ret;
927
928         master->queued = true;
929         master->transfer = spi_queued_transfer;
930         if (!master->transfer_one_message)
931                 master->transfer_one_message = spi_transfer_one_message;
932
933         /* Initialize and start queue */
934         ret = spi_init_queue(master);
935         if (ret) {
936                 dev_err(&master->dev, "problem initializing queue\n");
937                 goto err_init_queue;
938         }
939         ret = spi_start_queue(master);
940         if (ret) {
941                 dev_err(&master->dev, "problem starting queue\n");
942                 goto err_start_queue;
943         }
944
945         return 0;
946
947 err_start_queue:
948 err_init_queue:
949         spi_destroy_queue(master);
950         return ret;
951 }
952
953 /*-------------------------------------------------------------------------*/
954
955 #if defined(CONFIG_OF)
956 /**
957  * of_register_spi_devices() - Register child devices onto the SPI bus
958  * @master:     Pointer to spi_master device
959  *
960  * Registers an spi_device for each child node of master node which has a 'reg'
961  * property.
962  */
963 static void of_register_spi_devices(struct spi_master *master)
964 {
965         struct spi_device *spi;
966         struct device_node *nc;
967         int rc;
968         u32 value;
969
970         if (!master->dev.of_node)
971                 return;
972
973         for_each_available_child_of_node(master->dev.of_node, nc) {
974                 /* Alloc an spi_device */
975                 spi = spi_alloc_device(master);
976                 if (!spi) {
977                         dev_err(&master->dev, "spi_device alloc error for %s\n",
978                                 nc->full_name);
979                         spi_dev_put(spi);
980                         continue;
981                 }
982
983                 /* Select device driver */
984                 if (of_modalias_node(nc, spi->modalias,
985                                      sizeof(spi->modalias)) < 0) {
986                         dev_err(&master->dev, "cannot find modalias for %s\n",
987                                 nc->full_name);
988                         spi_dev_put(spi);
989                         continue;
990                 }
991
992                 /* Device address */
993                 rc = of_property_read_u32(nc, "reg", &value);
994                 if (rc) {
995                         dev_err(&master->dev, "%s has no valid 'reg' property (%d)\n",
996                                 nc->full_name, rc);
997                         spi_dev_put(spi);
998                         continue;
999                 }
1000                 spi->chip_select = value;
1001
1002                 /* Mode (clock phase/polarity/etc.) */
1003                 if (of_find_property(nc, "spi-cpha", NULL))
1004                         spi->mode |= SPI_CPHA;
1005                 if (of_find_property(nc, "spi-cpol", NULL))
1006                         spi->mode |= SPI_CPOL;
1007                 if (of_find_property(nc, "spi-cs-high", NULL))
1008                         spi->mode |= SPI_CS_HIGH;
1009                 if (of_find_property(nc, "spi-3wire", NULL))
1010                         spi->mode |= SPI_3WIRE;
1011
1012                 /* Device DUAL/QUAD mode */
1013                 if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1014                         switch (value) {
1015                         case 1:
1016                                 break;
1017                         case 2:
1018                                 spi->mode |= SPI_TX_DUAL;
1019                                 break;
1020                         case 4:
1021                                 spi->mode |= SPI_TX_QUAD;
1022                                 break;
1023                         default:
1024                                 dev_err(&master->dev,
1025                                         "spi-tx-bus-width %d not supported\n",
1026                                         value);
1027                                 spi_dev_put(spi);
1028                                 continue;
1029                         }
1030                 }
1031
1032                 if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1033                         switch (value) {
1034                         case 1:
1035                                 break;
1036                         case 2:
1037                                 spi->mode |= SPI_RX_DUAL;
1038                                 break;
1039                         case 4:
1040                                 spi->mode |= SPI_RX_QUAD;
1041                                 break;
1042                         default:
1043                                 dev_err(&master->dev,
1044                                         "spi-rx-bus-width %d not supported\n",
1045                                         value);
1046                                 spi_dev_put(spi);
1047                                 continue;
1048                         }
1049                 }
1050
1051                 /* Device speed */
1052                 rc = of_property_read_u32(nc, "spi-max-frequency", &value);
1053                 if (rc) {
1054                         dev_err(&master->dev, "%s has no valid 'spi-max-frequency' property (%d)\n",
1055                                 nc->full_name, rc);
1056                         spi_dev_put(spi);
1057                         continue;
1058                 }
1059                 spi->max_speed_hz = value;
1060
1061                 /* IRQ */
1062                 spi->irq = irq_of_parse_and_map(nc, 0);
1063
1064                 /* Store a pointer to the node in the device structure */
1065                 of_node_get(nc);
1066                 spi->dev.of_node = nc;
1067
1068                 /* Register the new device */
1069                 request_module("%s%s", SPI_MODULE_PREFIX, spi->modalias);
1070                 rc = spi_add_device(spi);
1071                 if (rc) {
1072                         dev_err(&master->dev, "spi_device register error %s\n",
1073                                 nc->full_name);
1074                         spi_dev_put(spi);
1075                 }
1076
1077         }
1078 }
1079 #else
1080 static void of_register_spi_devices(struct spi_master *master) { }
1081 #endif
1082
1083 #ifdef CONFIG_ACPI
1084 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
1085 {
1086         struct spi_device *spi = data;
1087
1088         if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
1089                 struct acpi_resource_spi_serialbus *sb;
1090
1091                 sb = &ares->data.spi_serial_bus;
1092                 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
1093                         spi->chip_select = sb->device_selection;
1094                         spi->max_speed_hz = sb->connection_speed;
1095
1096                         if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
1097                                 spi->mode |= SPI_CPHA;
1098                         if (sb->clock_polarity == ACPI_SPI_START_HIGH)
1099                                 spi->mode |= SPI_CPOL;
1100                         if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
1101                                 spi->mode |= SPI_CS_HIGH;
1102                 }
1103         } else if (spi->irq < 0) {
1104                 struct resource r;
1105
1106                 if (acpi_dev_resource_interrupt(ares, 0, &r))
1107                         spi->irq = r.start;
1108         }
1109
1110         /* Always tell the ACPI core to skip this resource */
1111         return 1;
1112 }
1113
1114 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
1115                                        void *data, void **return_value)
1116 {
1117         struct spi_master *master = data;
1118         struct list_head resource_list;
1119         struct acpi_device *adev;
1120         struct spi_device *spi;
1121         int ret;
1122
1123         if (acpi_bus_get_device(handle, &adev))
1124                 return AE_OK;
1125         if (acpi_bus_get_status(adev) || !adev->status.present)
1126                 return AE_OK;
1127
1128         spi = spi_alloc_device(master);
1129         if (!spi) {
1130                 dev_err(&master->dev, "failed to allocate SPI device for %s\n",
1131                         dev_name(&adev->dev));
1132                 return AE_NO_MEMORY;
1133         }
1134
1135         ACPI_HANDLE_SET(&spi->dev, handle);
1136         spi->irq = -1;
1137
1138         INIT_LIST_HEAD(&resource_list);
1139         ret = acpi_dev_get_resources(adev, &resource_list,
1140                                      acpi_spi_add_resource, spi);
1141         acpi_dev_free_resource_list(&resource_list);
1142
1143         if (ret < 0 || !spi->max_speed_hz) {
1144                 spi_dev_put(spi);
1145                 return AE_OK;
1146         }
1147
1148         strlcpy(spi->modalias, acpi_device_hid(adev), sizeof(spi->modalias));
1149         if (spi_add_device(spi)) {
1150                 dev_err(&master->dev, "failed to add SPI device %s from ACPI\n",
1151                         dev_name(&adev->dev));
1152                 spi_dev_put(spi);
1153         }
1154
1155         return AE_OK;
1156 }
1157
1158 static void acpi_register_spi_devices(struct spi_master *master)
1159 {
1160         acpi_status status;
1161         acpi_handle handle;
1162
1163         handle = ACPI_HANDLE(master->dev.parent);
1164         if (!handle)
1165                 return;
1166
1167         status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
1168                                      acpi_spi_add_device, NULL,
1169                                      master, NULL);
1170         if (ACPI_FAILURE(status))
1171                 dev_warn(&master->dev, "failed to enumerate SPI slaves\n");
1172 }
1173 #else
1174 static inline void acpi_register_spi_devices(struct spi_master *master) {}
1175 #endif /* CONFIG_ACPI */
1176
1177 static void spi_master_release(struct device *dev)
1178 {
1179         struct spi_master *master;
1180
1181         master = container_of(dev, struct spi_master, dev);
1182         kfree(master);
1183 }
1184
1185 static struct class spi_master_class = {
1186         .name           = "spi_master",
1187         .owner          = THIS_MODULE,
1188         .dev_release    = spi_master_release,
1189 };
1190
1191
1192
1193 /**
1194  * spi_alloc_master - allocate SPI master controller
1195  * @dev: the controller, possibly using the platform_bus
1196  * @size: how much zeroed driver-private data to allocate; the pointer to this
1197  *      memory is in the driver_data field of the returned device,
1198  *      accessible with spi_master_get_devdata().
1199  * Context: can sleep
1200  *
1201  * This call is used only by SPI master controller drivers, which are the
1202  * only ones directly touching chip registers.  It's how they allocate
1203  * an spi_master structure, prior to calling spi_register_master().
1204  *
1205  * This must be called from context that can sleep.  It returns the SPI
1206  * master structure on success, else NULL.
1207  *
1208  * The caller is responsible for assigning the bus number and initializing
1209  * the master's methods before calling spi_register_master(); and (after errors
1210  * adding the device) calling spi_master_put() and kfree() to prevent a memory
1211  * leak.
1212  */
1213 struct spi_master *spi_alloc_master(struct device *dev, unsigned size)
1214 {
1215         struct spi_master       *master;
1216
1217         if (!dev)
1218                 return NULL;
1219
1220         master = kzalloc(size + sizeof(*master), GFP_KERNEL);
1221         if (!master)
1222                 return NULL;
1223
1224         device_initialize(&master->dev);
1225         master->bus_num = -1;
1226         master->num_chipselect = 1;
1227         master->dev.class = &spi_master_class;
1228         master->dev.parent = get_device(dev);
1229         spi_master_set_devdata(master, &master[1]);
1230
1231         return master;
1232 }
1233 EXPORT_SYMBOL_GPL(spi_alloc_master);
1234
1235 #ifdef CONFIG_OF
1236 static int of_spi_register_master(struct spi_master *master)
1237 {
1238         int nb, i, *cs;
1239         struct device_node *np = master->dev.of_node;
1240
1241         if (!np)
1242                 return 0;
1243
1244         nb = of_gpio_named_count(np, "cs-gpios");
1245         master->num_chipselect = max_t(int, nb, master->num_chipselect);
1246
1247         /* Return error only for an incorrectly formed cs-gpios property */
1248         if (nb == 0 || nb == -ENOENT)
1249                 return 0;
1250         else if (nb < 0)
1251                 return nb;
1252
1253         cs = devm_kzalloc(&master->dev,
1254                           sizeof(int) * master->num_chipselect,
1255                           GFP_KERNEL);
1256         master->cs_gpios = cs;
1257
1258         if (!master->cs_gpios)
1259                 return -ENOMEM;
1260
1261         for (i = 0; i < master->num_chipselect; i++)
1262                 cs[i] = -ENOENT;
1263
1264         for (i = 0; i < nb; i++)
1265                 cs[i] = of_get_named_gpio(np, "cs-gpios", i);
1266
1267         return 0;
1268 }
1269 #else
1270 static int of_spi_register_master(struct spi_master *master)
1271 {
1272         return 0;
1273 }
1274 #endif
1275
1276 /**
1277  * spi_register_master - register SPI master controller
1278  * @master: initialized master, originally from spi_alloc_master()
1279  * Context: can sleep
1280  *
1281  * SPI master controllers connect to their drivers using some non-SPI bus,
1282  * such as the platform bus.  The final stage of probe() in that code
1283  * includes calling spi_register_master() to hook up to this SPI bus glue.
1284  *
1285  * SPI controllers use board specific (often SOC specific) bus numbers,
1286  * and board-specific addressing for SPI devices combines those numbers
1287  * with chip select numbers.  Since SPI does not directly support dynamic
1288  * device identification, boards need configuration tables telling which
1289  * chip is at which address.
1290  *
1291  * This must be called from context that can sleep.  It returns zero on
1292  * success, else a negative error code (dropping the master's refcount).
1293  * After a successful return, the caller is responsible for calling
1294  * spi_unregister_master().
1295  */
1296 int spi_register_master(struct spi_master *master)
1297 {
1298         static atomic_t         dyn_bus_id = ATOMIC_INIT((1<<15) - 1);
1299         struct device           *dev = master->dev.parent;
1300         struct boardinfo        *bi;
1301         int                     status = -ENODEV;
1302         int                     dynamic = 0;
1303
1304         if (!dev)
1305                 return -ENODEV;
1306
1307         status = of_spi_register_master(master);
1308         if (status)
1309                 return status;
1310
1311         /* even if it's just one always-selected device, there must
1312          * be at least one chipselect
1313          */
1314         if (master->num_chipselect == 0)
1315                 return -EINVAL;
1316
1317         if ((master->bus_num < 0) && master->dev.of_node)
1318                 master->bus_num = of_alias_get_id(master->dev.of_node, "spi");
1319
1320         /* convention:  dynamically assigned bus IDs count down from the max */
1321         if (master->bus_num < 0) {
1322                 /* FIXME switch to an IDR based scheme, something like
1323                  * I2C now uses, so we can't run out of "dynamic" IDs
1324                  */
1325                 master->bus_num = atomic_dec_return(&dyn_bus_id);
1326                 dynamic = 1;
1327         }
1328
1329         spin_lock_init(&master->bus_lock_spinlock);
1330         mutex_init(&master->bus_lock_mutex);
1331         master->bus_lock_flag = 0;
1332         init_completion(&master->xfer_completion);
1333
1334         /* register the device, then userspace will see it.
1335          * registration fails if the bus ID is in use.
1336          */
1337         dev_set_name(&master->dev, "spi%u", master->bus_num);
1338         status = device_add(&master->dev);
1339         if (status < 0)
1340                 goto done;
1341         dev_dbg(dev, "registered master %s%s\n", dev_name(&master->dev),
1342                         dynamic ? " (dynamic)" : "");
1343
1344         /* If we're using a queued driver, start the queue */
1345         if (master->transfer)
1346                 dev_info(dev, "master is unqueued, this is deprecated\n");
1347         else {
1348                 status = spi_master_initialize_queue(master);
1349                 if (status) {
1350                         device_del(&master->dev);
1351                         goto done;
1352                 }
1353         }
1354
1355         mutex_lock(&board_lock);
1356         list_add_tail(&master->list, &spi_master_list);
1357         list_for_each_entry(bi, &board_list, list)
1358                 spi_match_master_to_boardinfo(master, &bi->board_info);
1359         mutex_unlock(&board_lock);
1360
1361         /* Register devices from the device tree and ACPI */
1362         of_register_spi_devices(master);
1363         acpi_register_spi_devices(master);
1364 done:
1365         return status;
1366 }
1367 EXPORT_SYMBOL_GPL(spi_register_master);
1368
1369 static void devm_spi_unregister(struct device *dev, void *res)
1370 {
1371         spi_unregister_master(*(struct spi_master **)res);
1372 }
1373
1374 /**
1375  * dev_spi_register_master - register managed SPI master controller
1376  * @dev:    device managing SPI master
1377  * @master: initialized master, originally from spi_alloc_master()
1378  * Context: can sleep
1379  *
1380  * Register a SPI device as with spi_register_master() which will
1381  * automatically be unregister
1382  */
1383 int devm_spi_register_master(struct device *dev, struct spi_master *master)
1384 {
1385         struct spi_master **ptr;
1386         int ret;
1387
1388         ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
1389         if (!ptr)
1390                 return -ENOMEM;
1391
1392         ret = spi_register_master(master);
1393         if (ret != 0) {
1394                 *ptr = master;
1395                 devres_add(dev, ptr);
1396         } else {
1397                 devres_free(ptr);
1398         }
1399
1400         return ret;
1401 }
1402 EXPORT_SYMBOL_GPL(devm_spi_register_master);
1403
1404 static int __unregister(struct device *dev, void *null)
1405 {
1406         spi_unregister_device(to_spi_device(dev));
1407         return 0;
1408 }
1409
1410 /**
1411  * spi_unregister_master - unregister SPI master controller
1412  * @master: the master being unregistered
1413  * Context: can sleep
1414  *
1415  * This call is used only by SPI master controller drivers, which are the
1416  * only ones directly touching chip registers.
1417  *
1418  * This must be called from context that can sleep.
1419  */
1420 void spi_unregister_master(struct spi_master *master)
1421 {
1422         int dummy;
1423
1424         if (master->queued) {
1425                 if (spi_destroy_queue(master))
1426                         dev_err(&master->dev, "queue remove failed\n");
1427         }
1428
1429         mutex_lock(&board_lock);
1430         list_del(&master->list);
1431         mutex_unlock(&board_lock);
1432
1433         dummy = device_for_each_child(&master->dev, NULL, __unregister);
1434         device_unregister(&master->dev);
1435 }
1436 EXPORT_SYMBOL_GPL(spi_unregister_master);
1437
1438 int spi_master_suspend(struct spi_master *master)
1439 {
1440         int ret;
1441
1442         /* Basically no-ops for non-queued masters */
1443         if (!master->queued)
1444                 return 0;
1445
1446         ret = spi_stop_queue(master);
1447         if (ret)
1448                 dev_err(&master->dev, "queue stop failed\n");
1449
1450         return ret;
1451 }
1452 EXPORT_SYMBOL_GPL(spi_master_suspend);
1453
1454 int spi_master_resume(struct spi_master *master)
1455 {
1456         int ret;
1457
1458         if (!master->queued)
1459                 return 0;
1460
1461         ret = spi_start_queue(master);
1462         if (ret)
1463                 dev_err(&master->dev, "queue restart failed\n");
1464
1465         return ret;
1466 }
1467 EXPORT_SYMBOL_GPL(spi_master_resume);
1468
1469 static int __spi_master_match(struct device *dev, const void *data)
1470 {
1471         struct spi_master *m;
1472         const u16 *bus_num = data;
1473
1474         m = container_of(dev, struct spi_master, dev);
1475         return m->bus_num == *bus_num;
1476 }
1477
1478 /**
1479  * spi_busnum_to_master - look up master associated with bus_num
1480  * @bus_num: the master's bus number
1481  * Context: can sleep
1482  *
1483  * This call may be used with devices that are registered after
1484  * arch init time.  It returns a refcounted pointer to the relevant
1485  * spi_master (which the caller must release), or NULL if there is
1486  * no such master registered.
1487  */
1488 struct spi_master *spi_busnum_to_master(u16 bus_num)
1489 {
1490         struct device           *dev;
1491         struct spi_master       *master = NULL;
1492
1493         dev = class_find_device(&spi_master_class, NULL, &bus_num,
1494                                 __spi_master_match);
1495         if (dev)
1496                 master = container_of(dev, struct spi_master, dev);
1497         /* reference got in class_find_device */
1498         return master;
1499 }
1500 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
1501
1502
1503 /*-------------------------------------------------------------------------*/
1504
1505 /* Core methods for SPI master protocol drivers.  Some of the
1506  * other core methods are currently defined as inline functions.
1507  */
1508
1509 /**
1510  * spi_setup - setup SPI mode and clock rate
1511  * @spi: the device whose settings are being modified
1512  * Context: can sleep, and no requests are queued to the device
1513  *
1514  * SPI protocol drivers may need to update the transfer mode if the
1515  * device doesn't work with its default.  They may likewise need
1516  * to update clock rates or word sizes from initial values.  This function
1517  * changes those settings, and must be called from a context that can sleep.
1518  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
1519  * effect the next time the device is selected and data is transferred to
1520  * or from it.  When this function returns, the spi device is deselected.
1521  *
1522  * Note that this call will fail if the protocol driver specifies an option
1523  * that the underlying controller or its driver does not support.  For
1524  * example, not all hardware supports wire transfers using nine bit words,
1525  * LSB-first wire encoding, or active-high chipselects.
1526  */
1527 int spi_setup(struct spi_device *spi)
1528 {
1529         unsigned        bad_bits;
1530         int             status = 0;
1531
1532         /* check mode to prevent that DUAL and QUAD set at the same time
1533          */
1534         if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
1535                 ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
1536                 dev_err(&spi->dev,
1537                 "setup: can not select dual and quad at the same time\n");
1538                 return -EINVAL;
1539         }
1540         /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
1541          */
1542         if ((spi->mode & SPI_3WIRE) && (spi->mode &
1543                 (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
1544                 return -EINVAL;
1545         /* help drivers fail *cleanly* when they need options
1546          * that aren't supported with their current master
1547          */
1548         bad_bits = spi->mode & ~spi->master->mode_bits;
1549         if (bad_bits) {
1550                 dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
1551                         bad_bits);
1552                 return -EINVAL;
1553         }
1554
1555         if (!spi->bits_per_word)
1556                 spi->bits_per_word = 8;
1557
1558         if (spi->master->setup)
1559                 status = spi->master->setup(spi);
1560
1561         dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
1562                         (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
1563                         (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
1564                         (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
1565                         (spi->mode & SPI_3WIRE) ? "3wire, " : "",
1566                         (spi->mode & SPI_LOOP) ? "loopback, " : "",
1567                         spi->bits_per_word, spi->max_speed_hz,
1568                         status);
1569
1570         return status;
1571 }
1572 EXPORT_SYMBOL_GPL(spi_setup);
1573
1574 static int __spi_async(struct spi_device *spi, struct spi_message *message)
1575 {
1576         struct spi_master *master = spi->master;
1577         struct spi_transfer *xfer;
1578
1579         message->spi = spi;
1580
1581         trace_spi_message_submit(message);
1582
1583         if (list_empty(&message->transfers))
1584                 return -EINVAL;
1585         if (!message->complete)
1586                 return -EINVAL;
1587
1588         /* Half-duplex links include original MicroWire, and ones with
1589          * only one data pin like SPI_3WIRE (switches direction) or where
1590          * either MOSI or MISO is missing.  They can also be caused by
1591          * software limitations.
1592          */
1593         if ((master->flags & SPI_MASTER_HALF_DUPLEX)
1594                         || (spi->mode & SPI_3WIRE)) {
1595                 unsigned flags = master->flags;
1596
1597                 list_for_each_entry(xfer, &message->transfers, transfer_list) {
1598                         if (xfer->rx_buf && xfer->tx_buf)
1599                                 return -EINVAL;
1600                         if ((flags & SPI_MASTER_NO_TX) && xfer->tx_buf)
1601                                 return -EINVAL;
1602                         if ((flags & SPI_MASTER_NO_RX) && xfer->rx_buf)
1603                                 return -EINVAL;
1604                 }
1605         }
1606
1607         /**
1608          * Set transfer bits_per_word and max speed as spi device default if
1609          * it is not set for this transfer.
1610          * Set transfer tx_nbits and rx_nbits as single transfer default
1611          * (SPI_NBITS_SINGLE) if it is not set for this transfer.
1612          */
1613         list_for_each_entry(xfer, &message->transfers, transfer_list) {
1614                 message->frame_length += xfer->len;
1615                 if (!xfer->bits_per_word)
1616                         xfer->bits_per_word = spi->bits_per_word;
1617                 if (!xfer->speed_hz) {
1618                         xfer->speed_hz = spi->max_speed_hz;
1619                         if (master->max_speed_hz &&
1620                             xfer->speed_hz > master->max_speed_hz)
1621                                 xfer->speed_hz = master->max_speed_hz;
1622                 }
1623
1624                 if (master->bits_per_word_mask) {
1625                         /* Only 32 bits fit in the mask */
1626                         if (xfer->bits_per_word > 32)
1627                                 return -EINVAL;
1628                         if (!(master->bits_per_word_mask &
1629                                         BIT(xfer->bits_per_word - 1)))
1630                                 return -EINVAL;
1631                 }
1632
1633                 if (xfer->speed_hz && master->min_speed_hz &&
1634                     xfer->speed_hz < master->min_speed_hz)
1635                         return -EINVAL;
1636                 if (xfer->speed_hz && master->max_speed_hz &&
1637                     xfer->speed_hz > master->max_speed_hz)
1638                         return -EINVAL;
1639
1640                 if (xfer->tx_buf && !xfer->tx_nbits)
1641                         xfer->tx_nbits = SPI_NBITS_SINGLE;
1642                 if (xfer->rx_buf && !xfer->rx_nbits)
1643                         xfer->rx_nbits = SPI_NBITS_SINGLE;
1644                 /* check transfer tx/rx_nbits:
1645                  * 1. keep the value is not out of single, dual and quad
1646                  * 2. keep tx/rx_nbits is contained by mode in spi_device
1647                  * 3. if SPI_3WIRE, tx/rx_nbits should be in single
1648                  */
1649                 if (xfer->tx_buf) {
1650                         if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
1651                                 xfer->tx_nbits != SPI_NBITS_DUAL &&
1652                                 xfer->tx_nbits != SPI_NBITS_QUAD)
1653                                 return -EINVAL;
1654                         if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
1655                                 !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
1656                                 return -EINVAL;
1657                         if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
1658                                 !(spi->mode & SPI_TX_QUAD))
1659                                 return -EINVAL;
1660                         if ((spi->mode & SPI_3WIRE) &&
1661                                 (xfer->tx_nbits != SPI_NBITS_SINGLE))
1662                                 return -EINVAL;
1663                 }
1664                 /* check transfer rx_nbits */
1665                 if (xfer->rx_buf) {
1666                         if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
1667                                 xfer->rx_nbits != SPI_NBITS_DUAL &&
1668                                 xfer->rx_nbits != SPI_NBITS_QUAD)
1669                                 return -EINVAL;
1670                         if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
1671                                 !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
1672                                 return -EINVAL;
1673                         if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
1674                                 !(spi->mode & SPI_RX_QUAD))
1675                                 return -EINVAL;
1676                         if ((spi->mode & SPI_3WIRE) &&
1677                                 (xfer->rx_nbits != SPI_NBITS_SINGLE))
1678                                 return -EINVAL;
1679                 }
1680         }
1681
1682         message->status = -EINPROGRESS;
1683         return master->transfer(spi, message);
1684 }
1685
1686 /**
1687  * spi_async - asynchronous SPI transfer
1688  * @spi: device with which data will be exchanged
1689  * @message: describes the data transfers, including completion callback
1690  * Context: any (irqs may be blocked, etc)
1691  *
1692  * This call may be used in_irq and other contexts which can't sleep,
1693  * as well as from task contexts which can sleep.
1694  *
1695  * The completion callback is invoked in a context which can't sleep.
1696  * Before that invocation, the value of message->status is undefined.
1697  * When the callback is issued, message->status holds either zero (to
1698  * indicate complete success) or a negative error code.  After that
1699  * callback returns, the driver which issued the transfer request may
1700  * deallocate the associated memory; it's no longer in use by any SPI
1701  * core or controller driver code.
1702  *
1703  * Note that although all messages to a spi_device are handled in
1704  * FIFO order, messages may go to different devices in other orders.
1705  * Some device might be higher priority, or have various "hard" access
1706  * time requirements, for example.
1707  *
1708  * On detection of any fault during the transfer, processing of
1709  * the entire message is aborted, and the device is deselected.
1710  * Until returning from the associated message completion callback,
1711  * no other spi_message queued to that device will be processed.
1712  * (This rule applies equally to all the synchronous transfer calls,
1713  * which are wrappers around this core asynchronous primitive.)
1714  */
1715 int spi_async(struct spi_device *spi, struct spi_message *message)
1716 {
1717         struct spi_master *master = spi->master;
1718         int ret;
1719         unsigned long flags;
1720
1721         spin_lock_irqsave(&master->bus_lock_spinlock, flags);
1722
1723         if (master->bus_lock_flag)
1724                 ret = -EBUSY;
1725         else
1726                 ret = __spi_async(spi, message);
1727
1728         spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
1729
1730         return ret;
1731 }
1732 EXPORT_SYMBOL_GPL(spi_async);
1733
1734 /**
1735  * spi_async_locked - version of spi_async with exclusive bus usage
1736  * @spi: device with which data will be exchanged
1737  * @message: describes the data transfers, including completion callback
1738  * Context: any (irqs may be blocked, etc)
1739  *
1740  * This call may be used in_irq and other contexts which can't sleep,
1741  * as well as from task contexts which can sleep.
1742  *
1743  * The completion callback is invoked in a context which can't sleep.
1744  * Before that invocation, the value of message->status is undefined.
1745  * When the callback is issued, message->status holds either zero (to
1746  * indicate complete success) or a negative error code.  After that
1747  * callback returns, the driver which issued the transfer request may
1748  * deallocate the associated memory; it's no longer in use by any SPI
1749  * core or controller driver code.
1750  *
1751  * Note that although all messages to a spi_device are handled in
1752  * FIFO order, messages may go to different devices in other orders.
1753  * Some device might be higher priority, or have various "hard" access
1754  * time requirements, for example.
1755  *
1756  * On detection of any fault during the transfer, processing of
1757  * the entire message is aborted, and the device is deselected.
1758  * Until returning from the associated message completion callback,
1759  * no other spi_message queued to that device will be processed.
1760  * (This rule applies equally to all the synchronous transfer calls,
1761  * which are wrappers around this core asynchronous primitive.)
1762  */
1763 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
1764 {
1765         struct spi_master *master = spi->master;
1766         int ret;
1767         unsigned long flags;
1768
1769         spin_lock_irqsave(&master->bus_lock_spinlock, flags);
1770
1771         ret = __spi_async(spi, message);
1772
1773         spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
1774
1775         return ret;
1776
1777 }
1778 EXPORT_SYMBOL_GPL(spi_async_locked);
1779
1780
1781 /*-------------------------------------------------------------------------*/
1782
1783 /* Utility methods for SPI master protocol drivers, layered on
1784  * top of the core.  Some other utility methods are defined as
1785  * inline functions.
1786  */
1787
1788 static void spi_complete(void *arg)
1789 {
1790         complete(arg);
1791 }
1792
1793 static int __spi_sync(struct spi_device *spi, struct spi_message *message,
1794                       int bus_locked)
1795 {
1796         DECLARE_COMPLETION_ONSTACK(done);
1797         int status;
1798         struct spi_master *master = spi->master;
1799
1800         message->complete = spi_complete;
1801         message->context = &done;
1802
1803         if (!bus_locked)
1804                 mutex_lock(&master->bus_lock_mutex);
1805
1806         status = spi_async_locked(spi, message);
1807
1808         if (!bus_locked)
1809                 mutex_unlock(&master->bus_lock_mutex);
1810
1811         if (status == 0) {
1812                 wait_for_completion(&done);
1813                 status = message->status;
1814         }
1815         message->context = NULL;
1816         return status;
1817 }
1818
1819 /**
1820  * spi_sync - blocking/synchronous SPI data transfers
1821  * @spi: device with which data will be exchanged
1822  * @message: describes the data transfers
1823  * Context: can sleep
1824  *
1825  * This call may only be used from a context that may sleep.  The sleep
1826  * is non-interruptible, and has no timeout.  Low-overhead controller
1827  * drivers may DMA directly into and out of the message buffers.
1828  *
1829  * Note that the SPI device's chip select is active during the message,
1830  * and then is normally disabled between messages.  Drivers for some
1831  * frequently-used devices may want to minimize costs of selecting a chip,
1832  * by leaving it selected in anticipation that the next message will go
1833  * to the same chip.  (That may increase power usage.)
1834  *
1835  * Also, the caller is guaranteeing that the memory associated with the
1836  * message will not be freed before this call returns.
1837  *
1838  * It returns zero on success, else a negative error code.
1839  */
1840 int spi_sync(struct spi_device *spi, struct spi_message *message)
1841 {
1842         return __spi_sync(spi, message, 0);
1843 }
1844 EXPORT_SYMBOL_GPL(spi_sync);
1845
1846 /**
1847  * spi_sync_locked - version of spi_sync with exclusive bus usage
1848  * @spi: device with which data will be exchanged
1849  * @message: describes the data transfers
1850  * Context: can sleep
1851  *
1852  * This call may only be used from a context that may sleep.  The sleep
1853  * is non-interruptible, and has no timeout.  Low-overhead controller
1854  * drivers may DMA directly into and out of the message buffers.
1855  *
1856  * This call should be used by drivers that require exclusive access to the
1857  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
1858  * be released by a spi_bus_unlock call when the exclusive access is over.
1859  *
1860  * It returns zero on success, else a negative error code.
1861  */
1862 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
1863 {
1864         return __spi_sync(spi, message, 1);
1865 }
1866 EXPORT_SYMBOL_GPL(spi_sync_locked);
1867
1868 /**
1869  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
1870  * @master: SPI bus master that should be locked for exclusive bus access
1871  * Context: can sleep
1872  *
1873  * This call may only be used from a context that may sleep.  The sleep
1874  * is non-interruptible, and has no timeout.
1875  *
1876  * This call should be used by drivers that require exclusive access to the
1877  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
1878  * exclusive access is over. Data transfer must be done by spi_sync_locked
1879  * and spi_async_locked calls when the SPI bus lock is held.
1880  *
1881  * It returns zero on success, else a negative error code.
1882  */
1883 int spi_bus_lock(struct spi_master *master)
1884 {
1885         unsigned long flags;
1886
1887         mutex_lock(&master->bus_lock_mutex);
1888
1889         spin_lock_irqsave(&master->bus_lock_spinlock, flags);
1890         master->bus_lock_flag = 1;
1891         spin_unlock_irqrestore(&master->bus_lock_spinlock, flags);
1892
1893         /* mutex remains locked until spi_bus_unlock is called */
1894
1895         return 0;
1896 }
1897 EXPORT_SYMBOL_GPL(spi_bus_lock);
1898
1899 /**
1900  * spi_bus_unlock - release the lock for exclusive SPI bus usage
1901  * @master: SPI bus master that was locked for exclusive bus access
1902  * Context: can sleep
1903  *
1904  * This call may only be used from a context that may sleep.  The sleep
1905  * is non-interruptible, and has no timeout.
1906  *
1907  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
1908  * call.
1909  *
1910  * It returns zero on success, else a negative error code.
1911  */
1912 int spi_bus_unlock(struct spi_master *master)
1913 {
1914         master->bus_lock_flag = 0;
1915
1916         mutex_unlock(&master->bus_lock_mutex);
1917
1918         return 0;
1919 }
1920 EXPORT_SYMBOL_GPL(spi_bus_unlock);
1921
1922 /* portable code must never pass more than 32 bytes */
1923 #define SPI_BUFSIZ      max(32, SMP_CACHE_BYTES)
1924
1925 static u8       *buf;
1926
1927 /**
1928  * spi_write_then_read - SPI synchronous write followed by read
1929  * @spi: device with which data will be exchanged
1930  * @txbuf: data to be written (need not be dma-safe)
1931  * @n_tx: size of txbuf, in bytes
1932  * @rxbuf: buffer into which data will be read (need not be dma-safe)
1933  * @n_rx: size of rxbuf, in bytes
1934  * Context: can sleep
1935  *
1936  * This performs a half duplex MicroWire style transaction with the
1937  * device, sending txbuf and then reading rxbuf.  The return value
1938  * is zero for success, else a negative errno status code.
1939  * This call may only be used from a context that may sleep.
1940  *
1941  * Parameters to this routine are always copied using a small buffer;
1942  * portable code should never use this for more than 32 bytes.
1943  * Performance-sensitive or bulk transfer code should instead use
1944  * spi_{async,sync}() calls with dma-safe buffers.
1945  */
1946 int spi_write_then_read(struct spi_device *spi,
1947                 const void *txbuf, unsigned n_tx,
1948                 void *rxbuf, unsigned n_rx)
1949 {
1950         static DEFINE_MUTEX(lock);
1951
1952         int                     status;
1953         struct spi_message      message;
1954         struct spi_transfer     x[2];
1955         u8                      *local_buf;
1956
1957         /* Use preallocated DMA-safe buffer if we can.  We can't avoid
1958          * copying here, (as a pure convenience thing), but we can
1959          * keep heap costs out of the hot path unless someone else is
1960          * using the pre-allocated buffer or the transfer is too large.
1961          */
1962         if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
1963                 local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
1964                                     GFP_KERNEL | GFP_DMA);
1965                 if (!local_buf)
1966                         return -ENOMEM;
1967         } else {
1968                 local_buf = buf;
1969         }
1970
1971         spi_message_init(&message);
1972         memset(x, 0, sizeof(x));
1973         if (n_tx) {
1974                 x[0].len = n_tx;
1975                 spi_message_add_tail(&x[0], &message);
1976         }
1977         if (n_rx) {
1978                 x[1].len = n_rx;
1979                 spi_message_add_tail(&x[1], &message);
1980         }
1981
1982         memcpy(local_buf, txbuf, n_tx);
1983         x[0].tx_buf = local_buf;
1984         x[1].rx_buf = local_buf + n_tx;
1985
1986         /* do the i/o */
1987         status = spi_sync(spi, &message);
1988         if (status == 0)
1989                 memcpy(rxbuf, x[1].rx_buf, n_rx);
1990
1991         if (x[0].tx_buf == buf)
1992                 mutex_unlock(&lock);
1993         else
1994                 kfree(local_buf);
1995
1996         return status;
1997 }
1998 EXPORT_SYMBOL_GPL(spi_write_then_read);
1999
2000 /*-------------------------------------------------------------------------*/
2001
2002 static int __init spi_init(void)
2003 {
2004         int     status;
2005
2006         buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
2007         if (!buf) {
2008                 status = -ENOMEM;
2009                 goto err0;
2010         }
2011
2012         status = bus_register(&spi_bus_type);
2013         if (status < 0)
2014                 goto err1;
2015
2016         status = class_register(&spi_master_class);
2017         if (status < 0)
2018                 goto err2;
2019         return 0;
2020
2021 err2:
2022         bus_unregister(&spi_bus_type);
2023 err1:
2024         kfree(buf);
2025         buf = NULL;
2026 err0:
2027         return status;
2028 }
2029
2030 /* board_info is normally registered in arch_initcall(),
2031  * but even essential drivers wait till later
2032  *
2033  * REVISIT only boardinfo really needs static linking. the rest (device and
2034  * driver registration) _could_ be dynamically linked (modular) ... costs
2035  * include needing to have boardinfo data structures be much more public.
2036  */
2037 postcore_initcall(spi_init);
2038