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