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