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