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