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