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