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