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