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