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