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