xref: /linux/drivers/spi/spi.c (revision ac2a3feefad549814f5e7cca30be07a255c8494a)
1b445bfcbSMarco Felsch // SPDX-License-Identifier: GPL-2.0-or-later
2787f4889SMark Brown // SPI init/core code
3787f4889SMark Brown //
4787f4889SMark Brown // Copyright (C) 2005 David Brownell
5787f4889SMark Brown // Copyright (C) 2008 Secret Lab Technologies Ltd.
68ae12a0dSDavid Brownell 
78ae12a0dSDavid Brownell #include <linux/kernel.h>
88ae12a0dSDavid Brownell #include <linux/device.h>
98ae12a0dSDavid Brownell #include <linux/init.h>
108ae12a0dSDavid Brownell #include <linux/cache.h>
1199adef31SMark Brown #include <linux/dma-mapping.h>
1299adef31SMark Brown #include <linux/dmaengine.h>
1394040828SMatthias Kaehlcke #include <linux/mutex.h>
142b7a32f7SSinan Akman #include <linux/of_device.h>
15d57a4282SGrant Likely #include <linux/of_irq.h>
1686be408bSSylwester Nawrocki #include <linux/clk/clk-conf.h>
175a0e3ad6STejun Heo #include <linux/slab.h>
18e0626e38SAnton Vorontsov #include <linux/mod_devicetable.h>
198ae12a0dSDavid Brownell #include <linux/spi/spi.h>
20b5932f5cSBoris Brezillon #include <linux/spi/spi-mem.h>
21f3186dd8SLinus Walleij #include <linux/gpio/consumer.h>
223ae22e8cSMark Brown #include <linux/pm_runtime.h>
23f48c767cSUlf Hansson #include <linux/pm_domain.h>
24826cf175SDmitry Torokhov #include <linux/property.h>
25025ed130SPaul Gortmaker #include <linux/export.h>
268bd75c77SClark Williams #include <linux/sched/rt.h>
27ae7e81c0SIngo Molnar #include <uapi/linux/sched/types.h>
28ffbbdd21SLinus Walleij #include <linux/delay.h>
29ffbbdd21SLinus Walleij #include <linux/kthread.h>
3064bee4d2SMika Westerberg #include <linux/ioport.h>
3164bee4d2SMika Westerberg #include <linux/acpi.h>
32b1b8153cSVignesh R #include <linux/highmem.h>
339b61e302SSuniel Mahesh #include <linux/idr.h>
348a2e487eSLukas Wunner #include <linux/platform_data/x86/apple.h>
3544ea6281SJakub Kicinski #include <linux/ptp_clock_kernel.h>
368ae12a0dSDavid Brownell 
3756ec1978SMark Brown #define CREATE_TRACE_POINTS
3856ec1978SMark Brown #include <trace/events/spi.h>
39ca1438dcSArnd Bergmann EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40ca1438dcSArnd Bergmann EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
419b61e302SSuniel Mahesh 
4246336966SBoris Brezillon #include "internals.h"
4346336966SBoris Brezillon 
449b61e302SSuniel Mahesh static DEFINE_IDR(spi_master_idr);
4556ec1978SMark Brown 
468ae12a0dSDavid Brownell static void spidev_release(struct device *dev)
478ae12a0dSDavid Brownell {
480ffa0285SHans-Peter Nilsson 	struct spi_device	*spi = to_spi_device(dev);
498ae12a0dSDavid Brownell 
508caab75fSGeert Uytterhoeven 	spi_controller_put(spi->controller);
515039563eSTrent Piepho 	kfree(spi->driver_override);
5207a389feSRoman Tereshonkov 	kfree(spi);
538ae12a0dSDavid Brownell }
548ae12a0dSDavid Brownell 
558ae12a0dSDavid Brownell static ssize_t
568ae12a0dSDavid Brownell modalias_show(struct device *dev, struct device_attribute *a, char *buf)
578ae12a0dSDavid Brownell {
588ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
598c4ff6d0SZhang Rui 	int len;
608c4ff6d0SZhang Rui 
618c4ff6d0SZhang Rui 	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
628c4ff6d0SZhang Rui 	if (len != -ENODEV)
638c4ff6d0SZhang Rui 		return len;
648ae12a0dSDavid Brownell 
65d8e328b3SGrant Likely 	return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
668ae12a0dSDavid Brownell }
67aa7da564SGreg Kroah-Hartman static DEVICE_ATTR_RO(modalias);
688ae12a0dSDavid Brownell 
695039563eSTrent Piepho static ssize_t driver_override_store(struct device *dev,
705039563eSTrent Piepho 				     struct device_attribute *a,
715039563eSTrent Piepho 				     const char *buf, size_t count)
725039563eSTrent Piepho {
735039563eSTrent Piepho 	struct spi_device *spi = to_spi_device(dev);
745039563eSTrent Piepho 	const char *end = memchr(buf, '\n', count);
755039563eSTrent Piepho 	const size_t len = end ? end - buf : count;
765039563eSTrent Piepho 	const char *driver_override, *old;
775039563eSTrent Piepho 
785039563eSTrent Piepho 	/* We need to keep extra room for a newline when displaying value */
795039563eSTrent Piepho 	if (len >= (PAGE_SIZE - 1))
805039563eSTrent Piepho 		return -EINVAL;
815039563eSTrent Piepho 
825039563eSTrent Piepho 	driver_override = kstrndup(buf, len, GFP_KERNEL);
835039563eSTrent Piepho 	if (!driver_override)
845039563eSTrent Piepho 		return -ENOMEM;
855039563eSTrent Piepho 
865039563eSTrent Piepho 	device_lock(dev);
875039563eSTrent Piepho 	old = spi->driver_override;
885039563eSTrent Piepho 	if (len) {
895039563eSTrent Piepho 		spi->driver_override = driver_override;
905039563eSTrent Piepho 	} else {
91be73e323SAndy Shevchenko 		/* Empty string, disable driver override */
925039563eSTrent Piepho 		spi->driver_override = NULL;
935039563eSTrent Piepho 		kfree(driver_override);
945039563eSTrent Piepho 	}
955039563eSTrent Piepho 	device_unlock(dev);
965039563eSTrent Piepho 	kfree(old);
975039563eSTrent Piepho 
985039563eSTrent Piepho 	return count;
995039563eSTrent Piepho }
1005039563eSTrent Piepho 
1015039563eSTrent Piepho static ssize_t driver_override_show(struct device *dev,
1025039563eSTrent Piepho 				    struct device_attribute *a, char *buf)
1035039563eSTrent Piepho {
1045039563eSTrent Piepho 	const struct spi_device *spi = to_spi_device(dev);
1055039563eSTrent Piepho 	ssize_t len;
1065039563eSTrent Piepho 
1075039563eSTrent Piepho 	device_lock(dev);
1085039563eSTrent Piepho 	len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
1095039563eSTrent Piepho 	device_unlock(dev);
1105039563eSTrent Piepho 	return len;
1115039563eSTrent Piepho }
1125039563eSTrent Piepho static DEVICE_ATTR_RW(driver_override);
1135039563eSTrent Piepho 
114eca2ebc7SMartin Sperl #define SPI_STATISTICS_ATTRS(field, file)				\
1158caab75fSGeert Uytterhoeven static ssize_t spi_controller_##field##_show(struct device *dev,	\
116eca2ebc7SMartin Sperl 					     struct device_attribute *attr, \
117eca2ebc7SMartin Sperl 					     char *buf)			\
118eca2ebc7SMartin Sperl {									\
1198caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev,			\
1208caab75fSGeert Uytterhoeven 					 struct spi_controller, dev);	\
1218caab75fSGeert Uytterhoeven 	return spi_statistics_##field##_show(&ctlr->statistics, buf);	\
122eca2ebc7SMartin Sperl }									\
1238caab75fSGeert Uytterhoeven static struct device_attribute dev_attr_spi_controller_##field = {	\
124ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
1258caab75fSGeert Uytterhoeven 	.show = spi_controller_##field##_show,				\
126eca2ebc7SMartin Sperl };									\
127eca2ebc7SMartin Sperl static ssize_t spi_device_##field##_show(struct device *dev,		\
128eca2ebc7SMartin Sperl 					 struct device_attribute *attr,	\
129eca2ebc7SMartin Sperl 					char *buf)			\
130eca2ebc7SMartin Sperl {									\
131d1eba93bSGeliang Tang 	struct spi_device *spi = to_spi_device(dev);			\
132eca2ebc7SMartin Sperl 	return spi_statistics_##field##_show(&spi->statistics, buf);	\
133eca2ebc7SMartin Sperl }									\
134eca2ebc7SMartin Sperl static struct device_attribute dev_attr_spi_device_##field = {		\
135ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
136eca2ebc7SMartin Sperl 	.show = spi_device_##field##_show,				\
137eca2ebc7SMartin Sperl }
138eca2ebc7SMartin Sperl 
139eca2ebc7SMartin Sperl #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string)	\
140eca2ebc7SMartin Sperl static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
141eca2ebc7SMartin Sperl 					    char *buf)			\
142eca2ebc7SMartin Sperl {									\
143eca2ebc7SMartin Sperl 	unsigned long flags;						\
144eca2ebc7SMartin Sperl 	ssize_t len;							\
145eca2ebc7SMartin Sperl 	spin_lock_irqsave(&stat->lock, flags);				\
14604378630SHeiner Kallweit 	len = sysfs_emit(buf, format_string "\n", stat->field);		\
147eca2ebc7SMartin Sperl 	spin_unlock_irqrestore(&stat->lock, flags);			\
148eca2ebc7SMartin Sperl 	return len;							\
149eca2ebc7SMartin Sperl }									\
150eca2ebc7SMartin Sperl SPI_STATISTICS_ATTRS(name, file)
151eca2ebc7SMartin Sperl 
152eca2ebc7SMartin Sperl #define SPI_STATISTICS_SHOW(field, format_string)			\
153eca2ebc7SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(field, __stringify(field),		\
154eca2ebc7SMartin Sperl 				 field, format_string)
155eca2ebc7SMartin Sperl 
156eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(messages, "%lu");
157eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(transfers, "%lu");
158eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(errors, "%lu");
159eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(timedout, "%lu");
160eca2ebc7SMartin Sperl 
161eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(spi_sync, "%lu");
162eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
163eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(spi_async, "%lu");
164eca2ebc7SMartin Sperl 
165eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(bytes, "%llu");
166eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(bytes_rx, "%llu");
167eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(bytes_tx, "%llu");
168eca2ebc7SMartin Sperl 
1696b7bc061SMartin Sperl #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number)		\
1706b7bc061SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index,		\
1716b7bc061SMartin Sperl 				 "transfer_bytes_histo_" number,	\
1726b7bc061SMartin Sperl 				 transfer_bytes_histo[index],  "%lu")
1736b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(0,  "0-1");
1746b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(1,  "2-3");
1756b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(2,  "4-7");
1766b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(3,  "8-15");
1776b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(4,  "16-31");
1786b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(5,  "32-63");
1796b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(6,  "64-127");
1806b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(7,  "128-255");
1816b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(8,  "256-511");
1826b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(9,  "512-1023");
1836b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
1846b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
1856b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
1866b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
1876b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
1886b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
1896b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
1906b7bc061SMartin Sperl 
191d9f12122SMartin Sperl SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
192d9f12122SMartin Sperl 
193aa7da564SGreg Kroah-Hartman static struct attribute *spi_dev_attrs[] = {
194aa7da564SGreg Kroah-Hartman 	&dev_attr_modalias.attr,
1955039563eSTrent Piepho 	&dev_attr_driver_override.attr,
196aa7da564SGreg Kroah-Hartman 	NULL,
1978ae12a0dSDavid Brownell };
198eca2ebc7SMartin Sperl 
199eca2ebc7SMartin Sperl static const struct attribute_group spi_dev_group = {
200eca2ebc7SMartin Sperl 	.attrs  = spi_dev_attrs,
201eca2ebc7SMartin Sperl };
202eca2ebc7SMartin Sperl 
203eca2ebc7SMartin Sperl static struct attribute *spi_device_statistics_attrs[] = {
204eca2ebc7SMartin Sperl 	&dev_attr_spi_device_messages.attr,
205eca2ebc7SMartin Sperl 	&dev_attr_spi_device_transfers.attr,
206eca2ebc7SMartin Sperl 	&dev_attr_spi_device_errors.attr,
207eca2ebc7SMartin Sperl 	&dev_attr_spi_device_timedout.attr,
208eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync.attr,
209eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync_immediate.attr,
210eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_async.attr,
211eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes.attr,
212eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_rx.attr,
213eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_tx.attr,
2146b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo0.attr,
2156b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo1.attr,
2166b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo2.attr,
2176b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo3.attr,
2186b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo4.attr,
2196b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo5.attr,
2206b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo6.attr,
2216b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo7.attr,
2226b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo8.attr,
2236b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo9.attr,
2246b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo10.attr,
2256b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo11.attr,
2266b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo12.attr,
2276b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo13.attr,
2286b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo14.attr,
2296b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo15.attr,
2306b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo16.attr,
231d9f12122SMartin Sperl 	&dev_attr_spi_device_transfers_split_maxsize.attr,
232eca2ebc7SMartin Sperl 	NULL,
233eca2ebc7SMartin Sperl };
234eca2ebc7SMartin Sperl 
235eca2ebc7SMartin Sperl static const struct attribute_group spi_device_statistics_group = {
236eca2ebc7SMartin Sperl 	.name  = "statistics",
237eca2ebc7SMartin Sperl 	.attrs  = spi_device_statistics_attrs,
238eca2ebc7SMartin Sperl };
239eca2ebc7SMartin Sperl 
240eca2ebc7SMartin Sperl static const struct attribute_group *spi_dev_groups[] = {
241eca2ebc7SMartin Sperl 	&spi_dev_group,
242eca2ebc7SMartin Sperl 	&spi_device_statistics_group,
243eca2ebc7SMartin Sperl 	NULL,
244eca2ebc7SMartin Sperl };
245eca2ebc7SMartin Sperl 
2468caab75fSGeert Uytterhoeven static struct attribute *spi_controller_statistics_attrs[] = {
2478caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_messages.attr,
2488caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers.attr,
2498caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_errors.attr,
2508caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_timedout.attr,
2518caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync.attr,
2528caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync_immediate.attr,
2538caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_async.attr,
2548caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes.attr,
2558caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_rx.attr,
2568caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_tx.attr,
2578caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo0.attr,
2588caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo1.attr,
2598caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo2.attr,
2608caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo3.attr,
2618caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo4.attr,
2628caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo5.attr,
2638caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo6.attr,
2648caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo7.attr,
2658caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo8.attr,
2668caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo9.attr,
2678caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo10.attr,
2688caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo11.attr,
2698caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo12.attr,
2708caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo13.attr,
2718caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo14.attr,
2728caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo15.attr,
2738caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo16.attr,
2748caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers_split_maxsize.attr,
275eca2ebc7SMartin Sperl 	NULL,
276eca2ebc7SMartin Sperl };
277eca2ebc7SMartin Sperl 
2788caab75fSGeert Uytterhoeven static const struct attribute_group spi_controller_statistics_group = {
279eca2ebc7SMartin Sperl 	.name  = "statistics",
2808caab75fSGeert Uytterhoeven 	.attrs  = spi_controller_statistics_attrs,
281eca2ebc7SMartin Sperl };
282eca2ebc7SMartin Sperl 
283eca2ebc7SMartin Sperl static const struct attribute_group *spi_master_groups[] = {
2848caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
285eca2ebc7SMartin Sperl 	NULL,
286eca2ebc7SMartin Sperl };
287eca2ebc7SMartin Sperl 
288da21fde0SUwe Kleine-König static void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
289eca2ebc7SMartin Sperl 					      struct spi_transfer *xfer,
2908caab75fSGeert Uytterhoeven 					      struct spi_controller *ctlr)
291eca2ebc7SMartin Sperl {
292eca2ebc7SMartin Sperl 	unsigned long flags;
2936b7bc061SMartin Sperl 	int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
2946b7bc061SMartin Sperl 
2956b7bc061SMartin Sperl 	if (l2len < 0)
2966b7bc061SMartin Sperl 		l2len = 0;
297eca2ebc7SMartin Sperl 
298eca2ebc7SMartin Sperl 	spin_lock_irqsave(&stats->lock, flags);
299eca2ebc7SMartin Sperl 
300eca2ebc7SMartin Sperl 	stats->transfers++;
3016b7bc061SMartin Sperl 	stats->transfer_bytes_histo[l2len]++;
302eca2ebc7SMartin Sperl 
303eca2ebc7SMartin Sperl 	stats->bytes += xfer->len;
304eca2ebc7SMartin Sperl 	if ((xfer->tx_buf) &&
3058caab75fSGeert Uytterhoeven 	    (xfer->tx_buf != ctlr->dummy_tx))
306eca2ebc7SMartin Sperl 		stats->bytes_tx += xfer->len;
307eca2ebc7SMartin Sperl 	if ((xfer->rx_buf) &&
3088caab75fSGeert Uytterhoeven 	    (xfer->rx_buf != ctlr->dummy_rx))
309eca2ebc7SMartin Sperl 		stats->bytes_rx += xfer->len;
310eca2ebc7SMartin Sperl 
311eca2ebc7SMartin Sperl 	spin_unlock_irqrestore(&stats->lock, flags);
312eca2ebc7SMartin Sperl }
3138ae12a0dSDavid Brownell 
314350de7ceSAndy Shevchenko /*
315350de7ceSAndy Shevchenko  * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
3168ae12a0dSDavid Brownell  * and the sysfs version makes coldplug work too.
3178ae12a0dSDavid Brownell  */
3183f076575SAndy Shevchenko static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
31975368bf6SAnton Vorontsov {
32075368bf6SAnton Vorontsov 	while (id->name[0]) {
3213f076575SAndy Shevchenko 		if (!strcmp(name, id->name))
32275368bf6SAnton Vorontsov 			return id;
32375368bf6SAnton Vorontsov 		id++;
32475368bf6SAnton Vorontsov 	}
32575368bf6SAnton Vorontsov 	return NULL;
32675368bf6SAnton Vorontsov }
32775368bf6SAnton Vorontsov 
32875368bf6SAnton Vorontsov const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
32975368bf6SAnton Vorontsov {
33075368bf6SAnton Vorontsov 	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
33175368bf6SAnton Vorontsov 
3323f076575SAndy Shevchenko 	return spi_match_id(sdrv->id_table, sdev->modalias);
33375368bf6SAnton Vorontsov }
33475368bf6SAnton Vorontsov EXPORT_SYMBOL_GPL(spi_get_device_id);
33575368bf6SAnton Vorontsov 
3368ae12a0dSDavid Brownell static int spi_match_device(struct device *dev, struct device_driver *drv)
3378ae12a0dSDavid Brownell {
3388ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
33975368bf6SAnton Vorontsov 	const struct spi_driver	*sdrv = to_spi_driver(drv);
34075368bf6SAnton Vorontsov 
3415039563eSTrent Piepho 	/* Check override first, and if set, only use the named driver */
3425039563eSTrent Piepho 	if (spi->driver_override)
3435039563eSTrent Piepho 		return strcmp(spi->driver_override, drv->name) == 0;
3445039563eSTrent Piepho 
3452b7a32f7SSinan Akman 	/* Attempt an OF style match */
3462b7a32f7SSinan Akman 	if (of_driver_match_device(dev, drv))
3472b7a32f7SSinan Akman 		return 1;
3482b7a32f7SSinan Akman 
34964bee4d2SMika Westerberg 	/* Then try ACPI */
35064bee4d2SMika Westerberg 	if (acpi_driver_match_device(dev, drv))
35164bee4d2SMika Westerberg 		return 1;
35264bee4d2SMika Westerberg 
35375368bf6SAnton Vorontsov 	if (sdrv->id_table)
3543f076575SAndy Shevchenko 		return !!spi_match_id(sdrv->id_table, spi->modalias);
3558ae12a0dSDavid Brownell 
35635f74fcaSKay Sievers 	return strcmp(spi->modalias, drv->name) == 0;
3578ae12a0dSDavid Brownell }
3588ae12a0dSDavid Brownell 
3597eff2e7aSKay Sievers static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
3608ae12a0dSDavid Brownell {
3618ae12a0dSDavid Brownell 	const struct spi_device		*spi = to_spi_device(dev);
3628c4ff6d0SZhang Rui 	int rc;
3638c4ff6d0SZhang Rui 
3648c4ff6d0SZhang Rui 	rc = acpi_device_uevent_modalias(dev, env);
3658c4ff6d0SZhang Rui 	if (rc != -ENODEV)
3668c4ff6d0SZhang Rui 		return rc;
3678ae12a0dSDavid Brownell 
3682856670fSAndy Shevchenko 	return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
3698ae12a0dSDavid Brownell }
3708ae12a0dSDavid Brownell 
3719db34ee6SUwe Kleine-König static int spi_probe(struct device *dev)
372b885244eSDavid Brownell {
373b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
37444af7927SJon Hunter 	struct spi_device		*spi = to_spi_device(dev);
37533cf00e5SMika Westerberg 	int ret;
376b885244eSDavid Brownell 
37786be408bSSylwester Nawrocki 	ret = of_clk_set_defaults(dev->of_node, false);
37886be408bSSylwester Nawrocki 	if (ret)
37986be408bSSylwester Nawrocki 		return ret;
38086be408bSSylwester Nawrocki 
38144af7927SJon Hunter 	if (dev->of_node) {
38244af7927SJon Hunter 		spi->irq = of_irq_get(dev->of_node, 0);
38344af7927SJon Hunter 		if (spi->irq == -EPROBE_DEFER)
38444af7927SJon Hunter 			return -EPROBE_DEFER;
38544af7927SJon Hunter 		if (spi->irq < 0)
38644af7927SJon Hunter 			spi->irq = 0;
38744af7927SJon Hunter 	}
38844af7927SJon Hunter 
389676e7c25SUlf Hansson 	ret = dev_pm_domain_attach(dev, true);
39071f277a7SUlf Hansson 	if (ret)
39171f277a7SUlf Hansson 		return ret;
39271f277a7SUlf Hansson 
393440408dbSUwe Kleine-König 	if (sdrv->probe) {
39444af7927SJon Hunter 		ret = sdrv->probe(spi);
39533cf00e5SMika Westerberg 		if (ret)
396676e7c25SUlf Hansson 			dev_pm_domain_detach(dev, true);
397440408dbSUwe Kleine-König 	}
39833cf00e5SMika Westerberg 
39933cf00e5SMika Westerberg 	return ret;
400b885244eSDavid Brownell }
401b885244eSDavid Brownell 
402fc7a6209SUwe Kleine-König static void spi_remove(struct device *dev)
403b885244eSDavid Brownell {
404b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
405b885244eSDavid Brownell 
406a0386bbaSUwe Kleine-König 	if (sdrv->remove)
407a0386bbaSUwe Kleine-König 		sdrv->remove(to_spi_device(dev));
4087795d475SUwe Kleine-König 
409676e7c25SUlf Hansson 	dev_pm_domain_detach(dev, true);
410b885244eSDavid Brownell }
411b885244eSDavid Brownell 
4129db34ee6SUwe Kleine-König static void spi_shutdown(struct device *dev)
413b885244eSDavid Brownell {
414a6f483b2SMarek Szyprowski 	if (dev->driver) {
415b885244eSDavid Brownell 		const struct spi_driver	*sdrv = to_spi_driver(dev->driver);
416b885244eSDavid Brownell 
4179db34ee6SUwe Kleine-König 		if (sdrv->shutdown)
418b885244eSDavid Brownell 			sdrv->shutdown(to_spi_device(dev));
419b885244eSDavid Brownell 	}
420a6f483b2SMarek Szyprowski }
421b885244eSDavid Brownell 
4229db34ee6SUwe Kleine-König struct bus_type spi_bus_type = {
4239db34ee6SUwe Kleine-König 	.name		= "spi",
4249db34ee6SUwe Kleine-König 	.dev_groups	= spi_dev_groups,
4259db34ee6SUwe Kleine-König 	.match		= spi_match_device,
4269db34ee6SUwe Kleine-König 	.uevent		= spi_uevent,
4279db34ee6SUwe Kleine-König 	.probe		= spi_probe,
4289db34ee6SUwe Kleine-König 	.remove		= spi_remove,
4299db34ee6SUwe Kleine-König 	.shutdown	= spi_shutdown,
4309db34ee6SUwe Kleine-König };
4319db34ee6SUwe Kleine-König EXPORT_SYMBOL_GPL(spi_bus_type);
4329db34ee6SUwe Kleine-König 
43333e34dc6SDavid Brownell /**
434ca5d2485SAndrew F. Davis  * __spi_register_driver - register a SPI driver
43588c9321dSThierry Reding  * @owner: owner module of the driver to register
43633e34dc6SDavid Brownell  * @sdrv: the driver to register
43733e34dc6SDavid Brownell  * Context: can sleep
43897d56dc6SJavier Martinez Canillas  *
43997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
44033e34dc6SDavid Brownell  */
441ca5d2485SAndrew F. Davis int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
442b885244eSDavid Brownell {
443ca5d2485SAndrew F. Davis 	sdrv->driver.owner = owner;
444b885244eSDavid Brownell 	sdrv->driver.bus = &spi_bus_type;
4455fa6863bSMark Brown 
4465fa6863bSMark Brown 	/*
4475fa6863bSMark Brown 	 * For Really Good Reasons we use spi: modaliases not of:
4485fa6863bSMark Brown 	 * modaliases for DT so module autoloading won't work if we
4495fa6863bSMark Brown 	 * don't have a spi_device_id as well as a compatible string.
4505fa6863bSMark Brown 	 */
4515fa6863bSMark Brown 	if (sdrv->driver.of_match_table) {
4525fa6863bSMark Brown 		const struct of_device_id *of_id;
4535fa6863bSMark Brown 
4545fa6863bSMark Brown 		for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
4555fa6863bSMark Brown 		     of_id++) {
4565fa6863bSMark Brown 			const char *of_name;
4575fa6863bSMark Brown 
4585fa6863bSMark Brown 			/* Strip off any vendor prefix */
4595fa6863bSMark Brown 			of_name = strnchr(of_id->compatible,
4605fa6863bSMark Brown 					  sizeof(of_id->compatible), ',');
4615fa6863bSMark Brown 			if (of_name)
4625fa6863bSMark Brown 				of_name++;
4635fa6863bSMark Brown 			else
4645fa6863bSMark Brown 				of_name = of_id->compatible;
4655fa6863bSMark Brown 
4665fa6863bSMark Brown 			if (sdrv->id_table) {
4675fa6863bSMark Brown 				const struct spi_device_id *spi_id;
4685fa6863bSMark Brown 
4693f076575SAndy Shevchenko 				spi_id = spi_match_id(sdrv->id_table, of_name);
470b79332efSAndy Shevchenko 				if (spi_id)
4715fa6863bSMark Brown 					continue;
4725fa6863bSMark Brown 			} else {
4735fa6863bSMark Brown 				if (strcmp(sdrv->driver.name, of_name) == 0)
4745fa6863bSMark Brown 					continue;
4755fa6863bSMark Brown 			}
4765fa6863bSMark Brown 
4775fa6863bSMark Brown 			pr_warn("SPI driver %s has no spi_device_id for %s\n",
4785fa6863bSMark Brown 				sdrv->driver.name, of_id->compatible);
4795fa6863bSMark Brown 		}
4805fa6863bSMark Brown 	}
4815fa6863bSMark Brown 
482b885244eSDavid Brownell 	return driver_register(&sdrv->driver);
483b885244eSDavid Brownell }
484ca5d2485SAndrew F. Davis EXPORT_SYMBOL_GPL(__spi_register_driver);
485b885244eSDavid Brownell 
4868ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
4878ae12a0dSDavid Brownell 
488350de7ceSAndy Shevchenko /*
489350de7ceSAndy Shevchenko  * SPI devices should normally not be created by SPI device drivers; that
4908caab75fSGeert Uytterhoeven  * would make them board-specific.  Similarly with SPI controller drivers.
4918ae12a0dSDavid Brownell  * Device registration normally goes into like arch/.../mach.../board-YYY.c
4928ae12a0dSDavid Brownell  * with other readonly (flashable) information about mainboard devices.
4938ae12a0dSDavid Brownell  */
4948ae12a0dSDavid Brownell 
4958ae12a0dSDavid Brownell struct boardinfo {
4968ae12a0dSDavid Brownell 	struct list_head	list;
4972b9603a0SFeng Tang 	struct spi_board_info	board_info;
4988ae12a0dSDavid Brownell };
4998ae12a0dSDavid Brownell 
5008ae12a0dSDavid Brownell static LIST_HEAD(board_list);
5018caab75fSGeert Uytterhoeven static LIST_HEAD(spi_controller_list);
5022b9603a0SFeng Tang 
5032b9603a0SFeng Tang /*
504be73e323SAndy Shevchenko  * Used to protect add/del operation for board_info list and
505350de7ceSAndy Shevchenko  * spi_controller list, and their matching process also used
506350de7ceSAndy Shevchenko  * to protect object of type struct idr.
5072b9603a0SFeng Tang  */
50894040828SMatthias Kaehlcke static DEFINE_MUTEX(board_lock);
5098ae12a0dSDavid Brownell 
510dc87c98eSGrant Likely /**
511dc87c98eSGrant Likely  * spi_alloc_device - Allocate a new SPI device
5128caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
513dc87c98eSGrant Likely  * Context: can sleep
514dc87c98eSGrant Likely  *
515dc87c98eSGrant Likely  * Allows a driver to allocate and initialize a spi_device without
516dc87c98eSGrant Likely  * registering it immediately.  This allows a driver to directly
517dc87c98eSGrant Likely  * fill the spi_device with device parameters before calling
518dc87c98eSGrant Likely  * spi_add_device() on it.
519dc87c98eSGrant Likely  *
520dc87c98eSGrant Likely  * Caller is responsible to call spi_add_device() on the returned
5218caab75fSGeert Uytterhoeven  * spi_device structure to add it to the SPI controller.  If the caller
522dc87c98eSGrant Likely  * needs to discard the spi_device without adding it, then it should
523dc87c98eSGrant Likely  * call spi_dev_put() on it.
524dc87c98eSGrant Likely  *
52597d56dc6SJavier Martinez Canillas  * Return: a pointer to the new device, or NULL.
526dc87c98eSGrant Likely  */
527e3dc1399SStefan Binding struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
528dc87c98eSGrant Likely {
529dc87c98eSGrant Likely 	struct spi_device	*spi;
530dc87c98eSGrant Likely 
5318caab75fSGeert Uytterhoeven 	if (!spi_controller_get(ctlr))
532dc87c98eSGrant Likely 		return NULL;
533dc87c98eSGrant Likely 
5345fe5f05eSJingoo Han 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
535dc87c98eSGrant Likely 	if (!spi) {
5368caab75fSGeert Uytterhoeven 		spi_controller_put(ctlr);
537dc87c98eSGrant Likely 		return NULL;
538dc87c98eSGrant Likely 	}
539dc87c98eSGrant Likely 
5408caab75fSGeert Uytterhoeven 	spi->master = spi->controller = ctlr;
5418caab75fSGeert Uytterhoeven 	spi->dev.parent = &ctlr->dev;
542dc87c98eSGrant Likely 	spi->dev.bus = &spi_bus_type;
543dc87c98eSGrant Likely 	spi->dev.release = spidev_release;
544ea235786SJohn Garry 	spi->mode = ctlr->buswidth_override_bits;
545eca2ebc7SMartin Sperl 
546eca2ebc7SMartin Sperl 	spin_lock_init(&spi->statistics.lock);
547eca2ebc7SMartin Sperl 
548dc87c98eSGrant Likely 	device_initialize(&spi->dev);
549dc87c98eSGrant Likely 	return spi;
550dc87c98eSGrant Likely }
551e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_alloc_device);
552dc87c98eSGrant Likely 
553e13ac47bSJarkko Nikula static void spi_dev_set_name(struct spi_device *spi)
554e13ac47bSJarkko Nikula {
555e13ac47bSJarkko Nikula 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
556e13ac47bSJarkko Nikula 
557e13ac47bSJarkko Nikula 	if (adev) {
558e13ac47bSJarkko Nikula 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
559e13ac47bSJarkko Nikula 		return;
560e13ac47bSJarkko Nikula 	}
561e13ac47bSJarkko Nikula 
5628caab75fSGeert Uytterhoeven 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
563e13ac47bSJarkko Nikula 		     spi->chip_select);
564e13ac47bSJarkko Nikula }
565e13ac47bSJarkko Nikula 
566b6fb8d3aSMika Westerberg static int spi_dev_check(struct device *dev, void *data)
567b6fb8d3aSMika Westerberg {
568b6fb8d3aSMika Westerberg 	struct spi_device *spi = to_spi_device(dev);
569b6fb8d3aSMika Westerberg 	struct spi_device *new_spi = data;
570b6fb8d3aSMika Westerberg 
5718caab75fSGeert Uytterhoeven 	if (spi->controller == new_spi->controller &&
572b6fb8d3aSMika Westerberg 	    spi->chip_select == new_spi->chip_select)
573b6fb8d3aSMika Westerberg 		return -EBUSY;
574b6fb8d3aSMika Westerberg 	return 0;
575b6fb8d3aSMika Westerberg }
576b6fb8d3aSMika Westerberg 
577c7299feaSSaravana Kannan static void spi_cleanup(struct spi_device *spi)
578c7299feaSSaravana Kannan {
579c7299feaSSaravana Kannan 	if (spi->controller->cleanup)
580c7299feaSSaravana Kannan 		spi->controller->cleanup(spi);
581c7299feaSSaravana Kannan }
582c7299feaSSaravana Kannan 
5830c79378cSSebastian Reichel static int __spi_add_device(struct spi_device *spi)
5840c79378cSSebastian Reichel {
5850c79378cSSebastian Reichel 	struct spi_controller *ctlr = spi->controller;
5860c79378cSSebastian Reichel 	struct device *dev = ctlr->dev.parent;
5870c79378cSSebastian Reichel 	int status;
5880c79378cSSebastian Reichel 
5896bfb15f3SUwe Kleine-König 	/*
5906bfb15f3SUwe Kleine-König 	 * We need to make sure there's no other device with this
5916bfb15f3SUwe Kleine-König 	 * chipselect **BEFORE** we call setup(), else we'll trash
5926bfb15f3SUwe Kleine-König 	 * its configuration.
5936bfb15f3SUwe Kleine-König 	 */
5940c79378cSSebastian Reichel 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
5950c79378cSSebastian Reichel 	if (status) {
5960c79378cSSebastian Reichel 		dev_err(dev, "chipselect %d already in use\n",
5970c79378cSSebastian Reichel 				spi->chip_select);
5980c79378cSSebastian Reichel 		return status;
5990c79378cSSebastian Reichel 	}
6000c79378cSSebastian Reichel 
6010c79378cSSebastian Reichel 	/* Controller may unregister concurrently */
6020c79378cSSebastian Reichel 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
6030c79378cSSebastian Reichel 	    !device_is_registered(&ctlr->dev)) {
6040c79378cSSebastian Reichel 		return -ENODEV;
6050c79378cSSebastian Reichel 	}
6060c79378cSSebastian Reichel 
6070c79378cSSebastian Reichel 	if (ctlr->cs_gpiods)
6080c79378cSSebastian Reichel 		spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
6090c79378cSSebastian Reichel 
610350de7ceSAndy Shevchenko 	/*
611350de7ceSAndy Shevchenko 	 * Drivers may modify this initial i/o setup, but will
6120c79378cSSebastian Reichel 	 * normally rely on the device being setup.  Devices
6130c79378cSSebastian Reichel 	 * using SPI_CS_HIGH can't coexist well otherwise...
6140c79378cSSebastian Reichel 	 */
6150c79378cSSebastian Reichel 	status = spi_setup(spi);
6160c79378cSSebastian Reichel 	if (status < 0) {
6170c79378cSSebastian Reichel 		dev_err(dev, "can't setup %s, status %d\n",
6180c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
6190c79378cSSebastian Reichel 		return status;
6200c79378cSSebastian Reichel 	}
6210c79378cSSebastian Reichel 
6220c79378cSSebastian Reichel 	/* Device may be bound to an active driver when this returns */
6230c79378cSSebastian Reichel 	status = device_add(&spi->dev);
6240c79378cSSebastian Reichel 	if (status < 0) {
6250c79378cSSebastian Reichel 		dev_err(dev, "can't add %s, status %d\n",
6260c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
6270c79378cSSebastian Reichel 		spi_cleanup(spi);
6280c79378cSSebastian Reichel 	} else {
6290c79378cSSebastian Reichel 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
6300c79378cSSebastian Reichel 	}
6310c79378cSSebastian Reichel 
6320c79378cSSebastian Reichel 	return status;
6330c79378cSSebastian Reichel }
6340c79378cSSebastian Reichel 
635dc87c98eSGrant Likely /**
636dc87c98eSGrant Likely  * spi_add_device - Add spi_device allocated with spi_alloc_device
637dc87c98eSGrant Likely  * @spi: spi_device to register
638dc87c98eSGrant Likely  *
639dc87c98eSGrant Likely  * Companion function to spi_alloc_device.  Devices allocated with
640dc87c98eSGrant Likely  * spi_alloc_device can be added onto the spi bus with this function.
641dc87c98eSGrant Likely  *
64297d56dc6SJavier Martinez Canillas  * Return: 0 on success; negative errno on failure
643dc87c98eSGrant Likely  */
644e3dc1399SStefan Binding int spi_add_device(struct spi_device *spi)
645dc87c98eSGrant Likely {
6468caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
6478caab75fSGeert Uytterhoeven 	struct device *dev = ctlr->dev.parent;
648dc87c98eSGrant Likely 	int status;
649dc87c98eSGrant Likely 
650dc87c98eSGrant Likely 	/* Chipselects are numbered 0..max; validate. */
6518caab75fSGeert Uytterhoeven 	if (spi->chip_select >= ctlr->num_chipselect) {
6528caab75fSGeert Uytterhoeven 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
6538caab75fSGeert Uytterhoeven 			ctlr->num_chipselect);
654dc87c98eSGrant Likely 		return -EINVAL;
655dc87c98eSGrant Likely 	}
656dc87c98eSGrant Likely 
657dc87c98eSGrant Likely 	/* Set the bus ID string */
658e13ac47bSJarkko Nikula 	spi_dev_set_name(spi);
659e48880e0SDavid Brownell 
6606098475dSMark Brown 	mutex_lock(&ctlr->add_lock);
6610c79378cSSebastian Reichel 	status = __spi_add_device(spi);
6626098475dSMark Brown 	mutex_unlock(&ctlr->add_lock);
663e48880e0SDavid Brownell 	return status;
664dc87c98eSGrant Likely }
665e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_add_device);
6668ae12a0dSDavid Brownell 
6670c79378cSSebastian Reichel static int spi_add_device_locked(struct spi_device *spi)
6680c79378cSSebastian Reichel {
6690c79378cSSebastian Reichel 	struct spi_controller *ctlr = spi->controller;
6700c79378cSSebastian Reichel 	struct device *dev = ctlr->dev.parent;
6710c79378cSSebastian Reichel 
6720c79378cSSebastian Reichel 	/* Chipselects are numbered 0..max; validate. */
6730c79378cSSebastian Reichel 	if (spi->chip_select >= ctlr->num_chipselect) {
6740c79378cSSebastian Reichel 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
6750c79378cSSebastian Reichel 			ctlr->num_chipselect);
6760c79378cSSebastian Reichel 		return -EINVAL;
6770c79378cSSebastian Reichel 	}
6780c79378cSSebastian Reichel 
6790c79378cSSebastian Reichel 	/* Set the bus ID string */
6800c79378cSSebastian Reichel 	spi_dev_set_name(spi);
6810c79378cSSebastian Reichel 
6826098475dSMark Brown 	WARN_ON(!mutex_is_locked(&ctlr->add_lock));
6830c79378cSSebastian Reichel 	return __spi_add_device(spi);
6840c79378cSSebastian Reichel }
6850c79378cSSebastian Reichel 
68633e34dc6SDavid Brownell /**
68733e34dc6SDavid Brownell  * spi_new_device - instantiate one new SPI device
6888caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
68933e34dc6SDavid Brownell  * @chip: Describes the SPI device
69033e34dc6SDavid Brownell  * Context: can sleep
69133e34dc6SDavid Brownell  *
69233e34dc6SDavid Brownell  * On typical mainboards, this is purely internal; and it's not needed
6938ae12a0dSDavid Brownell  * after board init creates the hard-wired devices.  Some development
6948ae12a0dSDavid Brownell  * platforms may not be able to use spi_register_board_info though, and
6958ae12a0dSDavid Brownell  * this is exported so that for example a USB or parport based adapter
6968ae12a0dSDavid Brownell  * driver could add devices (which it would learn about out-of-band).
697082c8cb4SDavid Brownell  *
69897d56dc6SJavier Martinez Canillas  * Return: the new device, or NULL.
6998ae12a0dSDavid Brownell  */
7008caab75fSGeert Uytterhoeven struct spi_device *spi_new_device(struct spi_controller *ctlr,
701e9d5a461SAdrian Bunk 				  struct spi_board_info *chip)
7028ae12a0dSDavid Brownell {
7038ae12a0dSDavid Brownell 	struct spi_device	*proxy;
7048ae12a0dSDavid Brownell 	int			status;
7058ae12a0dSDavid Brownell 
706350de7ceSAndy Shevchenko 	/*
707350de7ceSAndy Shevchenko 	 * NOTE:  caller did any chip->bus_num checks necessary.
708082c8cb4SDavid Brownell 	 *
709082c8cb4SDavid Brownell 	 * Also, unless we change the return value convention to use
710082c8cb4SDavid Brownell 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
711082c8cb4SDavid Brownell 	 * suggests syslogged diagnostics are best here (ugh).
712082c8cb4SDavid Brownell 	 */
713082c8cb4SDavid Brownell 
7148caab75fSGeert Uytterhoeven 	proxy = spi_alloc_device(ctlr);
715dc87c98eSGrant Likely 	if (!proxy)
7168ae12a0dSDavid Brownell 		return NULL;
7178ae12a0dSDavid Brownell 
718102eb975SGrant Likely 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
719102eb975SGrant Likely 
7208ae12a0dSDavid Brownell 	proxy->chip_select = chip->chip_select;
7218ae12a0dSDavid Brownell 	proxy->max_speed_hz = chip->max_speed_hz;
722980a01c9SDavid Brownell 	proxy->mode = chip->mode;
7238ae12a0dSDavid Brownell 	proxy->irq = chip->irq;
724102eb975SGrant Likely 	strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
7258ae12a0dSDavid Brownell 	proxy->dev.platform_data = (void *) chip->platform_data;
7268ae12a0dSDavid Brownell 	proxy->controller_data = chip->controller_data;
7278ae12a0dSDavid Brownell 	proxy->controller_state = NULL;
7288ae12a0dSDavid Brownell 
72947afc77bSHeikki Krogerus 	if (chip->swnode) {
73047afc77bSHeikki Krogerus 		status = device_add_software_node(&proxy->dev, chip->swnode);
731826cf175SDmitry Torokhov 		if (status) {
7329d902c2aSColin Ian King 			dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
733826cf175SDmitry Torokhov 				chip->modalias, status);
734826cf175SDmitry Torokhov 			goto err_dev_put;
735826cf175SDmitry Torokhov 		}
7368ae12a0dSDavid Brownell 	}
737dc87c98eSGrant Likely 
738826cf175SDmitry Torokhov 	status = spi_add_device(proxy);
739826cf175SDmitry Torokhov 	if (status < 0)
740df41a5daSHeikki Krogerus 		goto err_dev_put;
741826cf175SDmitry Torokhov 
742dc87c98eSGrant Likely 	return proxy;
743826cf175SDmitry Torokhov 
744826cf175SDmitry Torokhov err_dev_put:
745df41a5daSHeikki Krogerus 	device_remove_software_node(&proxy->dev);
746826cf175SDmitry Torokhov 	spi_dev_put(proxy);
747826cf175SDmitry Torokhov 	return NULL;
748dc87c98eSGrant Likely }
7498ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_new_device);
7508ae12a0dSDavid Brownell 
7513b1884c2SGeert Uytterhoeven /**
7523b1884c2SGeert Uytterhoeven  * spi_unregister_device - unregister a single SPI device
7533b1884c2SGeert Uytterhoeven  * @spi: spi_device to unregister
7543b1884c2SGeert Uytterhoeven  *
7553b1884c2SGeert Uytterhoeven  * Start making the passed SPI device vanish. Normally this would be handled
7568caab75fSGeert Uytterhoeven  * by spi_unregister_controller().
7573b1884c2SGeert Uytterhoeven  */
7583b1884c2SGeert Uytterhoeven void spi_unregister_device(struct spi_device *spi)
7593b1884c2SGeert Uytterhoeven {
760bd6c1644SGeert Uytterhoeven 	if (!spi)
761bd6c1644SGeert Uytterhoeven 		return;
762bd6c1644SGeert Uytterhoeven 
7638324147fSJohan Hovold 	if (spi->dev.of_node) {
764bd6c1644SGeert Uytterhoeven 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
7658324147fSJohan Hovold 		of_node_put(spi->dev.of_node);
7668324147fSJohan Hovold 	}
7677f24467fSOctavian Purdila 	if (ACPI_COMPANION(&spi->dev))
7687f24467fSOctavian Purdila 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
76947afc77bSHeikki Krogerus 	device_remove_software_node(&spi->dev);
77027e7db56SSaravana Kannan 	device_del(&spi->dev);
77127e7db56SSaravana Kannan 	spi_cleanup(spi);
77227e7db56SSaravana Kannan 	put_device(&spi->dev);
7733b1884c2SGeert Uytterhoeven }
7743b1884c2SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_device);
7753b1884c2SGeert Uytterhoeven 
7768caab75fSGeert Uytterhoeven static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
7772b9603a0SFeng Tang 					      struct spi_board_info *bi)
7782b9603a0SFeng Tang {
7792b9603a0SFeng Tang 	struct spi_device *dev;
7802b9603a0SFeng Tang 
7818caab75fSGeert Uytterhoeven 	if (ctlr->bus_num != bi->bus_num)
7822b9603a0SFeng Tang 		return;
7832b9603a0SFeng Tang 
7848caab75fSGeert Uytterhoeven 	dev = spi_new_device(ctlr, bi);
7852b9603a0SFeng Tang 	if (!dev)
7868caab75fSGeert Uytterhoeven 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
7872b9603a0SFeng Tang 			bi->modalias);
7882b9603a0SFeng Tang }
7892b9603a0SFeng Tang 
79033e34dc6SDavid Brownell /**
79133e34dc6SDavid Brownell  * spi_register_board_info - register SPI devices for a given board
79233e34dc6SDavid Brownell  * @info: array of chip descriptors
79333e34dc6SDavid Brownell  * @n: how many descriptors are provided
79433e34dc6SDavid Brownell  * Context: can sleep
79533e34dc6SDavid Brownell  *
7968ae12a0dSDavid Brownell  * Board-specific early init code calls this (probably during arch_initcall)
7978ae12a0dSDavid Brownell  * with segments of the SPI device table.  Any device nodes are created later,
7988ae12a0dSDavid Brownell  * after the relevant parent SPI controller (bus_num) is defined.  We keep
7998ae12a0dSDavid Brownell  * this table of devices forever, so that reloading a controller driver will
8008ae12a0dSDavid Brownell  * not make Linux forget about these hard-wired devices.
8018ae12a0dSDavid Brownell  *
8028ae12a0dSDavid Brownell  * Other code can also call this, e.g. a particular add-on board might provide
8038ae12a0dSDavid Brownell  * SPI devices through its expansion connector, so code initializing that board
8048ae12a0dSDavid Brownell  * would naturally declare its SPI devices.
8058ae12a0dSDavid Brownell  *
8068ae12a0dSDavid Brownell  * The board info passed can safely be __initdata ... but be careful of
8078ae12a0dSDavid Brownell  * any embedded pointers (platform_data, etc), they're copied as-is.
80897d56dc6SJavier Martinez Canillas  *
80997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
8108ae12a0dSDavid Brownell  */
811fd4a319bSGrant Likely int spi_register_board_info(struct spi_board_info const *info, unsigned n)
8128ae12a0dSDavid Brownell {
8138ae12a0dSDavid Brownell 	struct boardinfo *bi;
8142b9603a0SFeng Tang 	int i;
8158ae12a0dSDavid Brownell 
816c7908a37SXiubo Li 	if (!n)
817f974cf57SDmitry Torokhov 		return 0;
818c7908a37SXiubo Li 
819f9bdb7fdSMarkus Elfring 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
8208ae12a0dSDavid Brownell 	if (!bi)
8218ae12a0dSDavid Brownell 		return -ENOMEM;
8228ae12a0dSDavid Brownell 
8232b9603a0SFeng Tang 	for (i = 0; i < n; i++, bi++, info++) {
8248caab75fSGeert Uytterhoeven 		struct spi_controller *ctlr;
8252b9603a0SFeng Tang 
8262b9603a0SFeng Tang 		memcpy(&bi->board_info, info, sizeof(*info));
827826cf175SDmitry Torokhov 
82894040828SMatthias Kaehlcke 		mutex_lock(&board_lock);
8298ae12a0dSDavid Brownell 		list_add_tail(&bi->list, &board_list);
8308caab75fSGeert Uytterhoeven 		list_for_each_entry(ctlr, &spi_controller_list, list)
8318caab75fSGeert Uytterhoeven 			spi_match_controller_to_boardinfo(ctlr,
8328caab75fSGeert Uytterhoeven 							  &bi->board_info);
83394040828SMatthias Kaehlcke 		mutex_unlock(&board_lock);
8342b9603a0SFeng Tang 	}
8352b9603a0SFeng Tang 
8368ae12a0dSDavid Brownell 	return 0;
8378ae12a0dSDavid Brownell }
8388ae12a0dSDavid Brownell 
8398ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
8408ae12a0dSDavid Brownell 
841fb51601bSUwe Kleine-König /* Core methods for SPI resource management */
842fb51601bSUwe Kleine-König 
843fb51601bSUwe Kleine-König /**
844fb51601bSUwe Kleine-König  * spi_res_alloc - allocate a spi resource that is life-cycle managed
845fb51601bSUwe Kleine-König  *                 during the processing of a spi_message while using
846fb51601bSUwe Kleine-König  *                 spi_transfer_one
847fb51601bSUwe Kleine-König  * @spi:     the spi device for which we allocate memory
848fb51601bSUwe Kleine-König  * @release: the release code to execute for this resource
849fb51601bSUwe Kleine-König  * @size:    size to alloc and return
850fb51601bSUwe Kleine-König  * @gfp:     GFP allocation flags
851fb51601bSUwe Kleine-König  *
852fb51601bSUwe Kleine-König  * Return: the pointer to the allocated data
853fb51601bSUwe Kleine-König  *
854fb51601bSUwe Kleine-König  * This may get enhanced in the future to allocate from a memory pool
855fb51601bSUwe Kleine-König  * of the @spi_device or @spi_controller to avoid repeated allocations.
856fb51601bSUwe Kleine-König  */
857da21fde0SUwe Kleine-König static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
858fb51601bSUwe Kleine-König 			   size_t size, gfp_t gfp)
859fb51601bSUwe Kleine-König {
860fb51601bSUwe Kleine-König 	struct spi_res *sres;
861fb51601bSUwe Kleine-König 
862fb51601bSUwe Kleine-König 	sres = kzalloc(sizeof(*sres) + size, gfp);
863fb51601bSUwe Kleine-König 	if (!sres)
864fb51601bSUwe Kleine-König 		return NULL;
865fb51601bSUwe Kleine-König 
866fb51601bSUwe Kleine-König 	INIT_LIST_HEAD(&sres->entry);
867fb51601bSUwe Kleine-König 	sres->release = release;
868fb51601bSUwe Kleine-König 
869fb51601bSUwe Kleine-König 	return sres->data;
870fb51601bSUwe Kleine-König }
871fb51601bSUwe Kleine-König 
872fb51601bSUwe Kleine-König /**
873fb51601bSUwe Kleine-König  * spi_res_free - free an spi resource
874fb51601bSUwe Kleine-König  * @res: pointer to the custom data of a resource
875fb51601bSUwe Kleine-König  */
876da21fde0SUwe Kleine-König static void spi_res_free(void *res)
877fb51601bSUwe Kleine-König {
878fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
879fb51601bSUwe Kleine-König 
880fb51601bSUwe Kleine-König 	if (!res)
881fb51601bSUwe Kleine-König 		return;
882fb51601bSUwe Kleine-König 
883fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
884fb51601bSUwe Kleine-König 	kfree(sres);
885fb51601bSUwe Kleine-König }
886fb51601bSUwe Kleine-König 
887fb51601bSUwe Kleine-König /**
888fb51601bSUwe Kleine-König  * spi_res_add - add a spi_res to the spi_message
889fb51601bSUwe Kleine-König  * @message: the spi message
890fb51601bSUwe Kleine-König  * @res:     the spi_resource
891fb51601bSUwe Kleine-König  */
892da21fde0SUwe Kleine-König static void spi_res_add(struct spi_message *message, void *res)
893fb51601bSUwe Kleine-König {
894fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
895fb51601bSUwe Kleine-König 
896fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
897fb51601bSUwe Kleine-König 	list_add_tail(&sres->entry, &message->resources);
898fb51601bSUwe Kleine-König }
899fb51601bSUwe Kleine-König 
900fb51601bSUwe Kleine-König /**
901fb51601bSUwe Kleine-König  * spi_res_release - release all spi resources for this message
902fb51601bSUwe Kleine-König  * @ctlr:  the @spi_controller
903fb51601bSUwe Kleine-König  * @message: the @spi_message
904fb51601bSUwe Kleine-König  */
905da21fde0SUwe Kleine-König static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
906fb51601bSUwe Kleine-König {
907fb51601bSUwe Kleine-König 	struct spi_res *res, *tmp;
908fb51601bSUwe Kleine-König 
909fb51601bSUwe Kleine-König 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
910fb51601bSUwe Kleine-König 		if (res->release)
911fb51601bSUwe Kleine-König 			res->release(ctlr, message, res->data);
912fb51601bSUwe Kleine-König 
913fb51601bSUwe Kleine-König 		list_del(&res->entry);
914fb51601bSUwe Kleine-König 
915fb51601bSUwe Kleine-König 		kfree(res);
916fb51601bSUwe Kleine-König 	}
917fb51601bSUwe Kleine-König }
918fb51601bSUwe Kleine-König 
919fb51601bSUwe Kleine-König /*-------------------------------------------------------------------------*/
920fb51601bSUwe Kleine-König 
921d347b4aaSDavid Bauer static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
922b158935fSMark Brown {
92386527bcbSAndy Shevchenko 	bool activate = enable;
92425093bdeSAlexandru Ardelean 
925d40f0b6fSDouglas Anderson 	/*
926d40f0b6fSDouglas Anderson 	 * Avoid calling into the driver (or doing delays) if the chip select
927d40f0b6fSDouglas Anderson 	 * isn't actually changing from the last time this was called.
928d40f0b6fSDouglas Anderson 	 */
9296bb477dfSYun Zhou 	if (!force && ((enable && spi->controller->last_cs == spi->chip_select) ||
9306bb477dfSYun Zhou 				(!enable && spi->controller->last_cs != spi->chip_select)) &&
931d40f0b6fSDouglas Anderson 	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
932d40f0b6fSDouglas Anderson 		return;
933d40f0b6fSDouglas Anderson 
9345cb4e1f3SAndy Shevchenko 	trace_spi_set_cs(spi, activate);
9355cb4e1f3SAndy Shevchenko 
9366bb477dfSYun Zhou 	spi->controller->last_cs = enable ? spi->chip_select : -1;
937d40f0b6fSDouglas Anderson 	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
938d40f0b6fSDouglas Anderson 
939f48dc6b9SLinus Walleij 	if ((spi->cs_gpiod || !spi->controller->set_cs_timing) && !activate) {
9408c33ebfeSMason Zhang 		spi_delay_exec(&spi->cs_hold, NULL);
94125093bdeSAlexandru Ardelean 	}
94225093bdeSAlexandru Ardelean 
943b158935fSMark Brown 	if (spi->mode & SPI_CS_HIGH)
944b158935fSMark Brown 		enable = !enable;
945b158935fSMark Brown 
9466b695469SAndy Shevchenko 	if (spi->cs_gpiod) {
947f48dc6b9SLinus Walleij 		if (!(spi->mode & SPI_NO_CS)) {
9486b695469SAndy Shevchenko 			/*
9496b695469SAndy Shevchenko 			 * Historically ACPI has no means of the GPIO polarity and
9506b695469SAndy Shevchenko 			 * thus the SPISerialBus() resource defines it on the per-chip
9516b695469SAndy Shevchenko 			 * basis. In order to avoid a chain of negations, the GPIO
9526b695469SAndy Shevchenko 			 * polarity is considered being Active High. Even for the cases
9536b695469SAndy Shevchenko 			 * when _DSD() is involved (in the updated versions of ACPI)
9546b695469SAndy Shevchenko 			 * the GPIO CS polarity must be defined Active High to avoid
9556b695469SAndy Shevchenko 			 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
9566b695469SAndy Shevchenko 			 * into account.
9576b695469SAndy Shevchenko 			 */
9586b695469SAndy Shevchenko 			if (has_acpi_companion(&spi->dev))
9596b695469SAndy Shevchenko 				gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
960f3186dd8SLinus Walleij 			else
9616b695469SAndy Shevchenko 				/* Polarity handled by GPIO library */
9626b695469SAndy Shevchenko 				gpiod_set_value_cansleep(spi->cs_gpiod, activate);
9636b695469SAndy Shevchenko 		}
9648eee6b9dSThor Thayer 		/* Some SPI masters need both GPIO CS & slave_select */
9658caab75fSGeert Uytterhoeven 		if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
9668caab75fSGeert Uytterhoeven 		    spi->controller->set_cs)
9678caab75fSGeert Uytterhoeven 			spi->controller->set_cs(spi, !enable);
9688caab75fSGeert Uytterhoeven 	} else if (spi->controller->set_cs) {
9698caab75fSGeert Uytterhoeven 		spi->controller->set_cs(spi, !enable);
9708eee6b9dSThor Thayer 	}
97125093bdeSAlexandru Ardelean 
972f48dc6b9SLinus Walleij 	if (spi->cs_gpiod || !spi->controller->set_cs_timing) {
97395c07247SHector Martin 		if (activate)
97495c07247SHector Martin 			spi_delay_exec(&spi->cs_setup, NULL);
97595c07247SHector Martin 		else
9768c33ebfeSMason Zhang 			spi_delay_exec(&spi->cs_inactive, NULL);
97725093bdeSAlexandru Ardelean 	}
978b158935fSMark Brown }
979b158935fSMark Brown 
9802de440f5SGeert Uytterhoeven #ifdef CONFIG_HAS_DMA
98146336966SBoris Brezillon int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
9826ad45a27SMark Brown 		struct sg_table *sgt, void *buf, size_t len,
9836ad45a27SMark Brown 		enum dma_data_direction dir)
9846ad45a27SMark Brown {
9856ad45a27SMark Brown 	const bool vmalloced_buf = is_vmalloc_addr(buf);
986df88e91bSAndy Shevchenko 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
987b1b8153cSVignesh R #ifdef CONFIG_HIGHMEM
988b1b8153cSVignesh R 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
989b1b8153cSVignesh R 				(unsigned long)buf < (PKMAP_BASE +
990b1b8153cSVignesh R 					(LAST_PKMAP * PAGE_SIZE)));
991b1b8153cSVignesh R #else
992b1b8153cSVignesh R 	const bool kmap_buf = false;
993b1b8153cSVignesh R #endif
99465598c13SAndrew Gabbasov 	int desc_len;
99565598c13SAndrew Gabbasov 	int sgs;
9966ad45a27SMark Brown 	struct page *vm_page;
9978dd4a016SJuan Gutierrez 	struct scatterlist *sg;
9986ad45a27SMark Brown 	void *sg_buf;
9996ad45a27SMark Brown 	size_t min;
10006ad45a27SMark Brown 	int i, ret;
10016ad45a27SMark Brown 
1002b1b8153cSVignesh R 	if (vmalloced_buf || kmap_buf) {
1003ebc4cb43SBiju Das 		desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
100465598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
10050569a88fSVignesh R 	} else if (virt_addr_valid(buf)) {
1006ebc4cb43SBiju Das 		desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
100765598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len, desc_len);
10080569a88fSVignesh R 	} else {
10090569a88fSVignesh R 		return -EINVAL;
101065598c13SAndrew Gabbasov 	}
101165598c13SAndrew Gabbasov 
10126ad45a27SMark Brown 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
10136ad45a27SMark Brown 	if (ret != 0)
10146ad45a27SMark Brown 		return ret;
10156ad45a27SMark Brown 
10168dd4a016SJuan Gutierrez 	sg = &sgt->sgl[0];
10176ad45a27SMark Brown 	for (i = 0; i < sgs; i++) {
10186ad45a27SMark Brown 
1019b1b8153cSVignesh R 		if (vmalloced_buf || kmap_buf) {
1020ce99319aSMaxime Chevallier 			/*
1021ce99319aSMaxime Chevallier 			 * Next scatterlist entry size is the minimum between
1022ce99319aSMaxime Chevallier 			 * the desc_len and the remaining buffer length that
1023ce99319aSMaxime Chevallier 			 * fits in a page.
1024ce99319aSMaxime Chevallier 			 */
1025ce99319aSMaxime Chevallier 			min = min_t(size_t, desc_len,
1026ce99319aSMaxime Chevallier 				    min_t(size_t, len,
1027ce99319aSMaxime Chevallier 					  PAGE_SIZE - offset_in_page(buf)));
1028b1b8153cSVignesh R 			if (vmalloced_buf)
10296ad45a27SMark Brown 				vm_page = vmalloc_to_page(buf);
1030b1b8153cSVignesh R 			else
1031b1b8153cSVignesh R 				vm_page = kmap_to_page(buf);
10326ad45a27SMark Brown 			if (!vm_page) {
10336ad45a27SMark Brown 				sg_free_table(sgt);
10346ad45a27SMark Brown 				return -ENOMEM;
10356ad45a27SMark Brown 			}
10368dd4a016SJuan Gutierrez 			sg_set_page(sg, vm_page,
1037c1aefbddSCharles Keepax 				    min, offset_in_page(buf));
10386ad45a27SMark Brown 		} else {
103965598c13SAndrew Gabbasov 			min = min_t(size_t, len, desc_len);
10406ad45a27SMark Brown 			sg_buf = buf;
10418dd4a016SJuan Gutierrez 			sg_set_buf(sg, sg_buf, min);
10426ad45a27SMark Brown 		}
10436ad45a27SMark Brown 
10446ad45a27SMark Brown 		buf += min;
10456ad45a27SMark Brown 		len -= min;
10468dd4a016SJuan Gutierrez 		sg = sg_next(sg);
10476ad45a27SMark Brown 	}
10486ad45a27SMark Brown 
10496ad45a27SMark Brown 	ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
105089e4b66aSGeert Uytterhoeven 	if (!ret)
105189e4b66aSGeert Uytterhoeven 		ret = -ENOMEM;
10526ad45a27SMark Brown 	if (ret < 0) {
10536ad45a27SMark Brown 		sg_free_table(sgt);
10546ad45a27SMark Brown 		return ret;
10556ad45a27SMark Brown 	}
10566ad45a27SMark Brown 
10576ad45a27SMark Brown 	sgt->nents = ret;
10586ad45a27SMark Brown 
10596ad45a27SMark Brown 	return 0;
10606ad45a27SMark Brown }
10616ad45a27SMark Brown 
106246336966SBoris Brezillon void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
10636ad45a27SMark Brown 		   struct sg_table *sgt, enum dma_data_direction dir)
10646ad45a27SMark Brown {
10656ad45a27SMark Brown 	if (sgt->orig_nents) {
10666ad45a27SMark Brown 		dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
10676ad45a27SMark Brown 		sg_free_table(sgt);
10686ad45a27SMark Brown 	}
10696ad45a27SMark Brown }
10706ad45a27SMark Brown 
10718caab75fSGeert Uytterhoeven static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
107299adef31SMark Brown {
107399adef31SMark Brown 	struct device *tx_dev, *rx_dev;
107499adef31SMark Brown 	struct spi_transfer *xfer;
10756ad45a27SMark Brown 	int ret;
10763a2eba9bSMark Brown 
10778caab75fSGeert Uytterhoeven 	if (!ctlr->can_dma)
107899adef31SMark Brown 		return 0;
107999adef31SMark Brown 
10808caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
10818caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
1082b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1083b470e10eSVinod Koul 		tx_dev = ctlr->dma_map_dev;
1084c37f45b5SLeilk Liu 	else
10858caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
1086c37f45b5SLeilk Liu 
10878caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
10888caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
1089b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1090b470e10eSVinod Koul 		rx_dev = ctlr->dma_map_dev;
1091c37f45b5SLeilk Liu 	else
10928caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
109399adef31SMark Brown 
109499adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
10958caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
109699adef31SMark Brown 			continue;
109799adef31SMark Brown 
109899adef31SMark Brown 		if (xfer->tx_buf != NULL) {
10998caab75fSGeert Uytterhoeven 			ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
11006ad45a27SMark Brown 					  (void *)xfer->tx_buf, xfer->len,
110199adef31SMark Brown 					  DMA_TO_DEVICE);
11026ad45a27SMark Brown 			if (ret != 0)
11036ad45a27SMark Brown 				return ret;
110499adef31SMark Brown 		}
110599adef31SMark Brown 
110699adef31SMark Brown 		if (xfer->rx_buf != NULL) {
11078caab75fSGeert Uytterhoeven 			ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
110899adef31SMark Brown 					  xfer->rx_buf, xfer->len,
110999adef31SMark Brown 					  DMA_FROM_DEVICE);
11106ad45a27SMark Brown 			if (ret != 0) {
11118caab75fSGeert Uytterhoeven 				spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
11126ad45a27SMark Brown 					      DMA_TO_DEVICE);
11136ad45a27SMark Brown 				return ret;
111499adef31SMark Brown 			}
111599adef31SMark Brown 		}
111699adef31SMark Brown 	}
111799adef31SMark Brown 
11188caab75fSGeert Uytterhoeven 	ctlr->cur_msg_mapped = true;
111999adef31SMark Brown 
112099adef31SMark Brown 	return 0;
112199adef31SMark Brown }
112299adef31SMark Brown 
11238caab75fSGeert Uytterhoeven static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
112499adef31SMark Brown {
112599adef31SMark Brown 	struct spi_transfer *xfer;
112699adef31SMark Brown 	struct device *tx_dev, *rx_dev;
112799adef31SMark Brown 
11288caab75fSGeert Uytterhoeven 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
112999adef31SMark Brown 		return 0;
113099adef31SMark Brown 
11318caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
11328caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
1133c37f45b5SLeilk Liu 	else
11348caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
1135c37f45b5SLeilk Liu 
11368caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
11378caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
1138c37f45b5SLeilk Liu 	else
11398caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
114099adef31SMark Brown 
114199adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11428caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
114399adef31SMark Brown 			continue;
114499adef31SMark Brown 
11458caab75fSGeert Uytterhoeven 		spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
11468caab75fSGeert Uytterhoeven 		spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
114799adef31SMark Brown 	}
114899adef31SMark Brown 
1149809b1b04SRobin Gong 	ctlr->cur_msg_mapped = false;
1150809b1b04SRobin Gong 
115199adef31SMark Brown 	return 0;
115299adef31SMark Brown }
11532de440f5SGeert Uytterhoeven #else /* !CONFIG_HAS_DMA */
11548caab75fSGeert Uytterhoeven static inline int __spi_map_msg(struct spi_controller *ctlr,
11552de440f5SGeert Uytterhoeven 				struct spi_message *msg)
11562de440f5SGeert Uytterhoeven {
11572de440f5SGeert Uytterhoeven 	return 0;
11582de440f5SGeert Uytterhoeven }
11592de440f5SGeert Uytterhoeven 
11608caab75fSGeert Uytterhoeven static inline int __spi_unmap_msg(struct spi_controller *ctlr,
11612de440f5SGeert Uytterhoeven 				  struct spi_message *msg)
11622de440f5SGeert Uytterhoeven {
11632de440f5SGeert Uytterhoeven 	return 0;
11642de440f5SGeert Uytterhoeven }
11652de440f5SGeert Uytterhoeven #endif /* !CONFIG_HAS_DMA */
11662de440f5SGeert Uytterhoeven 
11678caab75fSGeert Uytterhoeven static inline int spi_unmap_msg(struct spi_controller *ctlr,
11684b786458SMartin Sperl 				struct spi_message *msg)
11694b786458SMartin Sperl {
11704b786458SMartin Sperl 	struct spi_transfer *xfer;
11714b786458SMartin Sperl 
11724b786458SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11734b786458SMartin Sperl 		/*
11744b786458SMartin Sperl 		 * Restore the original value of tx_buf or rx_buf if they are
11754b786458SMartin Sperl 		 * NULL.
11764b786458SMartin Sperl 		 */
11778caab75fSGeert Uytterhoeven 		if (xfer->tx_buf == ctlr->dummy_tx)
11784b786458SMartin Sperl 			xfer->tx_buf = NULL;
11798caab75fSGeert Uytterhoeven 		if (xfer->rx_buf == ctlr->dummy_rx)
11804b786458SMartin Sperl 			xfer->rx_buf = NULL;
11814b786458SMartin Sperl 	}
11824b786458SMartin Sperl 
11838caab75fSGeert Uytterhoeven 	return __spi_unmap_msg(ctlr, msg);
11844b786458SMartin Sperl }
11854b786458SMartin Sperl 
11868caab75fSGeert Uytterhoeven static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
11872de440f5SGeert Uytterhoeven {
11882de440f5SGeert Uytterhoeven 	struct spi_transfer *xfer;
11892de440f5SGeert Uytterhoeven 	void *tmp;
11902de440f5SGeert Uytterhoeven 	unsigned int max_tx, max_rx;
11912de440f5SGeert Uytterhoeven 
1192aee67fe8Sdillon min 	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1193aee67fe8Sdillon min 		&& !(msg->spi->mode & SPI_3WIRE)) {
11942de440f5SGeert Uytterhoeven 		max_tx = 0;
11952de440f5SGeert Uytterhoeven 		max_rx = 0;
11962de440f5SGeert Uytterhoeven 
11972de440f5SGeert Uytterhoeven 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11988caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
11992de440f5SGeert Uytterhoeven 			    !xfer->tx_buf)
12002de440f5SGeert Uytterhoeven 				max_tx = max(xfer->len, max_tx);
12018caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
12022de440f5SGeert Uytterhoeven 			    !xfer->rx_buf)
12032de440f5SGeert Uytterhoeven 				max_rx = max(xfer->len, max_rx);
12042de440f5SGeert Uytterhoeven 		}
12052de440f5SGeert Uytterhoeven 
12062de440f5SGeert Uytterhoeven 		if (max_tx) {
12078caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_tx, max_tx,
1208b00bab9dSAndy Shevchenko 				       GFP_KERNEL | GFP_DMA | __GFP_ZERO);
12092de440f5SGeert Uytterhoeven 			if (!tmp)
12102de440f5SGeert Uytterhoeven 				return -ENOMEM;
12118caab75fSGeert Uytterhoeven 			ctlr->dummy_tx = tmp;
12122de440f5SGeert Uytterhoeven 		}
12132de440f5SGeert Uytterhoeven 
12142de440f5SGeert Uytterhoeven 		if (max_rx) {
12158caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_rx, max_rx,
12162de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
12172de440f5SGeert Uytterhoeven 			if (!tmp)
12182de440f5SGeert Uytterhoeven 				return -ENOMEM;
12198caab75fSGeert Uytterhoeven 			ctlr->dummy_rx = tmp;
12202de440f5SGeert Uytterhoeven 		}
12212de440f5SGeert Uytterhoeven 
12222de440f5SGeert Uytterhoeven 		if (max_tx || max_rx) {
12232de440f5SGeert Uytterhoeven 			list_for_each_entry(xfer, &msg->transfers,
12242de440f5SGeert Uytterhoeven 					    transfer_list) {
12255442dcaaSChris Lesiak 				if (!xfer->len)
12265442dcaaSChris Lesiak 					continue;
12272de440f5SGeert Uytterhoeven 				if (!xfer->tx_buf)
12288caab75fSGeert Uytterhoeven 					xfer->tx_buf = ctlr->dummy_tx;
12292de440f5SGeert Uytterhoeven 				if (!xfer->rx_buf)
12308caab75fSGeert Uytterhoeven 					xfer->rx_buf = ctlr->dummy_rx;
12312de440f5SGeert Uytterhoeven 			}
12322de440f5SGeert Uytterhoeven 		}
12332de440f5SGeert Uytterhoeven 	}
12342de440f5SGeert Uytterhoeven 
12358caab75fSGeert Uytterhoeven 	return __spi_map_msg(ctlr, msg);
12362de440f5SGeert Uytterhoeven }
123799adef31SMark Brown 
1238810923f3SLubomir Rintel static int spi_transfer_wait(struct spi_controller *ctlr,
1239810923f3SLubomir Rintel 			     struct spi_message *msg,
1240810923f3SLubomir Rintel 			     struct spi_transfer *xfer)
1241810923f3SLubomir Rintel {
1242810923f3SLubomir Rintel 	struct spi_statistics *statm = &ctlr->statistics;
1243810923f3SLubomir Rintel 	struct spi_statistics *stats = &msg->spi->statistics;
12446170d077SXu Yilun 	u32 speed_hz = xfer->speed_hz;
124549686df5SColin Ian King 	unsigned long long ms;
1246810923f3SLubomir Rintel 
1247810923f3SLubomir Rintel 	if (spi_controller_is_slave(ctlr)) {
1248810923f3SLubomir Rintel 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1249810923f3SLubomir Rintel 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1250810923f3SLubomir Rintel 			return -EINTR;
1251810923f3SLubomir Rintel 		}
1252810923f3SLubomir Rintel 	} else {
12536170d077SXu Yilun 		if (!speed_hz)
12546170d077SXu Yilun 			speed_hz = 100000;
12556170d077SXu Yilun 
125686b8bff7SAndy Shevchenko 		/*
125786b8bff7SAndy Shevchenko 		 * For each byte we wait for 8 cycles of the SPI clock.
125886b8bff7SAndy Shevchenko 		 * Since speed is defined in Hz and we want milliseconds,
125986b8bff7SAndy Shevchenko 		 * use respective multiplier, but before the division,
126086b8bff7SAndy Shevchenko 		 * otherwise we may get 0 for short transfers.
126186b8bff7SAndy Shevchenko 		 */
126286b8bff7SAndy Shevchenko 		ms = 8LL * MSEC_PER_SEC * xfer->len;
12636170d077SXu Yilun 		do_div(ms, speed_hz);
1264810923f3SLubomir Rintel 
126586b8bff7SAndy Shevchenko 		/*
126686b8bff7SAndy Shevchenko 		 * Increase it twice and add 200 ms tolerance, use
126786b8bff7SAndy Shevchenko 		 * predefined maximum in case of overflow.
126886b8bff7SAndy Shevchenko 		 */
126986b8bff7SAndy Shevchenko 		ms += ms + 200;
1270810923f3SLubomir Rintel 		if (ms > UINT_MAX)
1271810923f3SLubomir Rintel 			ms = UINT_MAX;
1272810923f3SLubomir Rintel 
1273810923f3SLubomir Rintel 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1274810923f3SLubomir Rintel 						 msecs_to_jiffies(ms));
1275810923f3SLubomir Rintel 
1276810923f3SLubomir Rintel 		if (ms == 0) {
1277810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1278810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1279810923f3SLubomir Rintel 			dev_err(&msg->spi->dev,
1280810923f3SLubomir Rintel 				"SPI transfer timed out\n");
1281810923f3SLubomir Rintel 			return -ETIMEDOUT;
1282810923f3SLubomir Rintel 		}
1283810923f3SLubomir Rintel 	}
1284810923f3SLubomir Rintel 
1285810923f3SLubomir Rintel 	return 0;
1286810923f3SLubomir Rintel }
1287810923f3SLubomir Rintel 
12880ff2de8bSMartin Sperl static void _spi_transfer_delay_ns(u32 ns)
12890ff2de8bSMartin Sperl {
12900ff2de8bSMartin Sperl 	if (!ns)
12910ff2de8bSMartin Sperl 		return;
129286b8bff7SAndy Shevchenko 	if (ns <= NSEC_PER_USEC) {
12930ff2de8bSMartin Sperl 		ndelay(ns);
12940ff2de8bSMartin Sperl 	} else {
129586b8bff7SAndy Shevchenko 		u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
12960ff2de8bSMartin Sperl 
12970ff2de8bSMartin Sperl 		if (us <= 10)
12980ff2de8bSMartin Sperl 			udelay(us);
12990ff2de8bSMartin Sperl 		else
13000ff2de8bSMartin Sperl 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
13010ff2de8bSMartin Sperl 	}
13020ff2de8bSMartin Sperl }
13030ff2de8bSMartin Sperl 
13043984d39bSAlexandru Ardelean int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
13050ff2de8bSMartin Sperl {
1306b2c98153SAlexandru Ardelean 	u32 delay = _delay->value;
1307b2c98153SAlexandru Ardelean 	u32 unit = _delay->unit;
1308d5864e5bSMartin Sperl 	u32 hz;
13090ff2de8bSMartin Sperl 
1310b2c98153SAlexandru Ardelean 	if (!delay)
1311b2c98153SAlexandru Ardelean 		return 0;
13120ff2de8bSMartin Sperl 
13130ff2de8bSMartin Sperl 	switch (unit) {
13140ff2de8bSMartin Sperl 	case SPI_DELAY_UNIT_USECS:
131586b8bff7SAndy Shevchenko 		delay *= NSEC_PER_USEC;
13160ff2de8bSMartin Sperl 		break;
131786b8bff7SAndy Shevchenko 	case SPI_DELAY_UNIT_NSECS:
131886b8bff7SAndy Shevchenko 		/* Nothing to do here */
13190ff2de8bSMartin Sperl 		break;
1320d5864e5bSMartin Sperl 	case SPI_DELAY_UNIT_SCK:
1321b2c98153SAlexandru Ardelean 		/* clock cycles need to be obtained from spi_transfer */
1322b2c98153SAlexandru Ardelean 		if (!xfer)
1323b2c98153SAlexandru Ardelean 			return -EINVAL;
132486b8bff7SAndy Shevchenko 		/*
132586b8bff7SAndy Shevchenko 		 * If there is unknown effective speed, approximate it
132686b8bff7SAndy Shevchenko 		 * by underestimating with half of the requested hz.
1327d5864e5bSMartin Sperl 		 */
1328d5864e5bSMartin Sperl 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1329b2c98153SAlexandru Ardelean 		if (!hz)
1330b2c98153SAlexandru Ardelean 			return -EINVAL;
133186b8bff7SAndy Shevchenko 
133286b8bff7SAndy Shevchenko 		/* Convert delay to nanoseconds */
133386b8bff7SAndy Shevchenko 		delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1334d5864e5bSMartin Sperl 		break;
13350ff2de8bSMartin Sperl 	default:
1336b2c98153SAlexandru Ardelean 		return -EINVAL;
1337b2c98153SAlexandru Ardelean 	}
1338b2c98153SAlexandru Ardelean 
1339b2c98153SAlexandru Ardelean 	return delay;
1340b2c98153SAlexandru Ardelean }
13413984d39bSAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1342b2c98153SAlexandru Ardelean 
1343b2c98153SAlexandru Ardelean int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1344b2c98153SAlexandru Ardelean {
1345b2c98153SAlexandru Ardelean 	int delay;
1346b2c98153SAlexandru Ardelean 
13478fede89fSMark Brown 	might_sleep();
13488fede89fSMark Brown 
1349b2c98153SAlexandru Ardelean 	if (!_delay)
1350b2c98153SAlexandru Ardelean 		return -EINVAL;
1351b2c98153SAlexandru Ardelean 
13523984d39bSAlexandru Ardelean 	delay = spi_delay_to_ns(_delay, xfer);
1353b2c98153SAlexandru Ardelean 	if (delay < 0)
1354b2c98153SAlexandru Ardelean 		return delay;
1355b2c98153SAlexandru Ardelean 
1356b2c98153SAlexandru Ardelean 	_spi_transfer_delay_ns(delay);
1357b2c98153SAlexandru Ardelean 
1358b2c98153SAlexandru Ardelean 	return 0;
1359b2c98153SAlexandru Ardelean }
1360b2c98153SAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_exec);
1361b2c98153SAlexandru Ardelean 
13620ff2de8bSMartin Sperl static void _spi_transfer_cs_change_delay(struct spi_message *msg,
13630ff2de8bSMartin Sperl 					  struct spi_transfer *xfer)
13640ff2de8bSMartin Sperl {
136586b8bff7SAndy Shevchenko 	u32 default_delay_ns = 10 * NSEC_PER_USEC;
1366329f0dacSAlexandru Ardelean 	u32 delay = xfer->cs_change_delay.value;
1367329f0dacSAlexandru Ardelean 	u32 unit = xfer->cs_change_delay.unit;
1368329f0dacSAlexandru Ardelean 	int ret;
13690ff2de8bSMartin Sperl 
13700ff2de8bSMartin Sperl 	/* return early on "fast" mode - for everything but USECS */
13716b3f236aSAlexandru Ardelean 	if (!delay) {
13726b3f236aSAlexandru Ardelean 		if (unit == SPI_DELAY_UNIT_USECS)
137386b8bff7SAndy Shevchenko 			_spi_transfer_delay_ns(default_delay_ns);
13740ff2de8bSMartin Sperl 		return;
13756b3f236aSAlexandru Ardelean 	}
13760ff2de8bSMartin Sperl 
1377329f0dacSAlexandru Ardelean 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1378329f0dacSAlexandru Ardelean 	if (ret) {
13790ff2de8bSMartin Sperl 		dev_err_once(&msg->spi->dev,
138086b8bff7SAndy Shevchenko 			     "Use of unsupported delay unit %i, using default of %luus\n",
138186b8bff7SAndy Shevchenko 			     unit, default_delay_ns / NSEC_PER_USEC);
138286b8bff7SAndy Shevchenko 		_spi_transfer_delay_ns(default_delay_ns);
13830ff2de8bSMartin Sperl 	}
13840ff2de8bSMartin Sperl }
13850ff2de8bSMartin Sperl 
1386b158935fSMark Brown /*
1387b158935fSMark Brown  * spi_transfer_one_message - Default implementation of transfer_one_message()
1388b158935fSMark Brown  *
1389b158935fSMark Brown  * This is a standard implementation of transfer_one_message() for
13908ba811a7SMoritz Fischer  * drivers which implement a transfer_one() operation.  It provides
1391b158935fSMark Brown  * standard handling of delays and chip select management.
1392b158935fSMark Brown  */
13938caab75fSGeert Uytterhoeven static int spi_transfer_one_message(struct spi_controller *ctlr,
1394b158935fSMark Brown 				    struct spi_message *msg)
1395b158935fSMark Brown {
1396b158935fSMark Brown 	struct spi_transfer *xfer;
1397b158935fSMark Brown 	bool keep_cs = false;
1398b158935fSMark Brown 	int ret = 0;
13998caab75fSGeert Uytterhoeven 	struct spi_statistics *statm = &ctlr->statistics;
1400eca2ebc7SMartin Sperl 	struct spi_statistics *stats = &msg->spi->statistics;
1401b158935fSMark Brown 
1402d347b4aaSDavid Bauer 	spi_set_cs(msg->spi, true, false);
1403b158935fSMark Brown 
1404eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1405eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1406eca2ebc7SMartin Sperl 
1407b158935fSMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1408b158935fSMark Brown 		trace_spi_transfer_start(msg, xfer);
1409b158935fSMark Brown 
14108caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
14118caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1412eca2ebc7SMartin Sperl 
1413b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1414b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1415b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1416b42faeeeSVladimir Oltean 		}
1417b42faeeeSVladimir Oltean 
1418b3063203SNicolas Saenz Julienne 		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
14198caab75fSGeert Uytterhoeven 			reinit_completion(&ctlr->xfer_completion);
1420b158935fSMark Brown 
1421809b1b04SRobin Gong fallback_pio:
14228caab75fSGeert Uytterhoeven 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1423b158935fSMark Brown 			if (ret < 0) {
1424809b1b04SRobin Gong 				if (ctlr->cur_msg_mapped &&
1425809b1b04SRobin Gong 				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1426809b1b04SRobin Gong 					__spi_unmap_msg(ctlr, msg);
1427809b1b04SRobin Gong 					ctlr->fallback = true;
1428809b1b04SRobin Gong 					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1429809b1b04SRobin Gong 					goto fallback_pio;
1430809b1b04SRobin Gong 				}
1431809b1b04SRobin Gong 
1432eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1433eca2ebc7SMartin Sperl 							       errors);
1434eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1435eca2ebc7SMartin Sperl 							       errors);
1436b158935fSMark Brown 				dev_err(&msg->spi->dev,
1437b158935fSMark Brown 					"SPI transfer failed: %d\n", ret);
1438b158935fSMark Brown 				goto out;
1439b158935fSMark Brown 			}
1440b158935fSMark Brown 
1441d57e7960SMark Brown 			if (ret > 0) {
1442810923f3SLubomir Rintel 				ret = spi_transfer_wait(ctlr, msg, xfer);
1443810923f3SLubomir Rintel 				if (ret < 0)
1444810923f3SLubomir Rintel 					msg->status = ret;
1445d57e7960SMark Brown 			}
144638ec10f6SMark Brown 		} else {
144738ec10f6SMark Brown 			if (xfer->len)
144838ec10f6SMark Brown 				dev_err(&msg->spi->dev,
144938ec10f6SMark Brown 					"Bufferless transfer has length %u\n",
145038ec10f6SMark Brown 					xfer->len);
145138ec10f6SMark Brown 		}
1452b158935fSMark Brown 
1453b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1454b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1455b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1456b42faeeeSVladimir Oltean 		}
1457b42faeeeSVladimir Oltean 
1458b158935fSMark Brown 		trace_spi_transfer_stop(msg, xfer);
1459b158935fSMark Brown 
1460b158935fSMark Brown 		if (msg->status != -EINPROGRESS)
1461b158935fSMark Brown 			goto out;
1462b158935fSMark Brown 
1463bebcfd27SAlexandru Ardelean 		spi_transfer_delay_exec(xfer);
1464b158935fSMark Brown 
1465b158935fSMark Brown 		if (xfer->cs_change) {
1466b158935fSMark Brown 			if (list_is_last(&xfer->transfer_list,
1467b158935fSMark Brown 					 &msg->transfers)) {
1468b158935fSMark Brown 				keep_cs = true;
1469b158935fSMark Brown 			} else {
1470d347b4aaSDavid Bauer 				spi_set_cs(msg->spi, false, false);
14710ff2de8bSMartin Sperl 				_spi_transfer_cs_change_delay(msg, xfer);
1472d347b4aaSDavid Bauer 				spi_set_cs(msg->spi, true, false);
1473b158935fSMark Brown 			}
1474b158935fSMark Brown 		}
1475b158935fSMark Brown 
1476b158935fSMark Brown 		msg->actual_length += xfer->len;
1477b158935fSMark Brown 	}
1478b158935fSMark Brown 
1479b158935fSMark Brown out:
1480b158935fSMark Brown 	if (ret != 0 || !keep_cs)
1481d347b4aaSDavid Bauer 		spi_set_cs(msg->spi, false, false);
1482b158935fSMark Brown 
1483b158935fSMark Brown 	if (msg->status == -EINPROGRESS)
1484b158935fSMark Brown 		msg->status = ret;
1485b158935fSMark Brown 
14868caab75fSGeert Uytterhoeven 	if (msg->status && ctlr->handle_err)
14878caab75fSGeert Uytterhoeven 		ctlr->handle_err(ctlr, msg);
1488b716c4ffSAndy Shevchenko 
14890ed56252SMark Brown 	spi_finalize_current_message(ctlr);
14900ed56252SMark Brown 
1491b158935fSMark Brown 	return ret;
1492b158935fSMark Brown }
1493b158935fSMark Brown 
1494b158935fSMark Brown /**
1495b158935fSMark Brown  * spi_finalize_current_transfer - report completion of a transfer
14968caab75fSGeert Uytterhoeven  * @ctlr: the controller reporting completion
1497b158935fSMark Brown  *
1498b158935fSMark Brown  * Called by SPI drivers using the core transfer_one_message()
1499b158935fSMark Brown  * implementation to notify it that the current interrupt driven
15009e8f4882SGeert Uytterhoeven  * transfer has finished and the next one may be scheduled.
1501b158935fSMark Brown  */
15028caab75fSGeert Uytterhoeven void spi_finalize_current_transfer(struct spi_controller *ctlr)
1503b158935fSMark Brown {
15048caab75fSGeert Uytterhoeven 	complete(&ctlr->xfer_completion);
1505b158935fSMark Brown }
1506b158935fSMark Brown EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1507b158935fSMark Brown 
1508e1268597SMark Brown static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1509e1268597SMark Brown {
1510e1268597SMark Brown 	if (ctlr->auto_runtime_pm) {
1511e1268597SMark Brown 		pm_runtime_mark_last_busy(ctlr->dev.parent);
1512e1268597SMark Brown 		pm_runtime_put_autosuspend(ctlr->dev.parent);
1513e1268597SMark Brown 	}
1514e1268597SMark Brown }
1515e1268597SMark Brown 
1516ffbbdd21SLinus Walleij /**
1517fc9e0f71SMark Brown  * __spi_pump_messages - function which processes spi message queue
15188caab75fSGeert Uytterhoeven  * @ctlr: controller to process queue for
1519fc9e0f71SMark Brown  * @in_kthread: true if we are in the context of the message pump thread
1520ffbbdd21SLinus Walleij  *
1521ffbbdd21SLinus Walleij  * This function checks if there is any spi message in the queue that
1522ffbbdd21SLinus Walleij  * needs processing and if so call out to the driver to initialize hardware
1523ffbbdd21SLinus Walleij  * and transfer each message.
1524ffbbdd21SLinus Walleij  *
15250461a414SMark Brown  * Note that it is called both from the kthread itself and also from
15260461a414SMark Brown  * inside spi_sync(); the queue extraction handling at the top of the
15270461a414SMark Brown  * function should deal with this safely.
1528ffbbdd21SLinus Walleij  */
15298caab75fSGeert Uytterhoeven static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1530ffbbdd21SLinus Walleij {
1531b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
1532d1c44c93SVladimir Oltean 	struct spi_message *msg;
1533ffbbdd21SLinus Walleij 	bool was_busy = false;
1534d1c44c93SVladimir Oltean 	unsigned long flags;
1535ffbbdd21SLinus Walleij 	int ret;
1536ffbbdd21SLinus Walleij 
1537983aee5dSMark Brown 	/* Lock queue */
15388caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1539983aee5dSMark Brown 
1540983aee5dSMark Brown 	/* Make sure we are not already running a message */
15418caab75fSGeert Uytterhoeven 	if (ctlr->cur_msg) {
15428caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1543983aee5dSMark Brown 		return;
1544983aee5dSMark Brown 	}
1545983aee5dSMark Brown 
1546f0125f1aSMark Brown 	/* If another context is idling the device then defer */
15478caab75fSGeert Uytterhoeven 	if (ctlr->idling) {
154860a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
15498caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
15500461a414SMark Brown 		return;
15510461a414SMark Brown 	}
15520461a414SMark Brown 
1553983aee5dSMark Brown 	/* Check if the queue is idle */
15548caab75fSGeert Uytterhoeven 	if (list_empty(&ctlr->queue) || !ctlr->running) {
15558caab75fSGeert Uytterhoeven 		if (!ctlr->busy) {
15568caab75fSGeert Uytterhoeven 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1557ffbbdd21SLinus Walleij 			return;
1558ffbbdd21SLinus Walleij 		}
1559fc9e0f71SMark Brown 
1560e1268597SMark Brown 		/* Defer any non-atomic teardown to the thread */
1561f0125f1aSMark Brown 		if (!in_kthread) {
1562e1268597SMark Brown 			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1563e1268597SMark Brown 			    !ctlr->unprepare_transfer_hardware) {
1564e1268597SMark Brown 				spi_idle_runtime_pm(ctlr);
1565e1268597SMark Brown 				ctlr->busy = false;
1566e1268597SMark Brown 				trace_spi_controller_idle(ctlr);
1567e1268597SMark Brown 			} else {
156860a883d1SMarek Szyprowski 				kthread_queue_work(ctlr->kworker,
1569f0125f1aSMark Brown 						   &ctlr->pump_messages);
1570e1268597SMark Brown 			}
1571f0125f1aSMark Brown 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1572f0125f1aSMark Brown 			return;
1573f0125f1aSMark Brown 		}
1574f0125f1aSMark Brown 
1575f0125f1aSMark Brown 		ctlr->busy = false;
1576f0125f1aSMark Brown 		ctlr->idling = true;
1577f0125f1aSMark Brown 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1578f0125f1aSMark Brown 
1579f0125f1aSMark Brown 		kfree(ctlr->dummy_rx);
1580f0125f1aSMark Brown 		ctlr->dummy_rx = NULL;
1581f0125f1aSMark Brown 		kfree(ctlr->dummy_tx);
1582f0125f1aSMark Brown 		ctlr->dummy_tx = NULL;
1583f0125f1aSMark Brown 		if (ctlr->unprepare_transfer_hardware &&
1584f0125f1aSMark Brown 		    ctlr->unprepare_transfer_hardware(ctlr))
1585f0125f1aSMark Brown 			dev_err(&ctlr->dev,
1586f0125f1aSMark Brown 				"failed to unprepare transfer hardware\n");
1587e1268597SMark Brown 		spi_idle_runtime_pm(ctlr);
1588f0125f1aSMark Brown 		trace_spi_controller_idle(ctlr);
1589f0125f1aSMark Brown 
1590f0125f1aSMark Brown 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1591f0125f1aSMark Brown 		ctlr->idling = false;
15928caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1593ffbbdd21SLinus Walleij 		return;
1594ffbbdd21SLinus Walleij 	}
1595ffbbdd21SLinus Walleij 
1596ffbbdd21SLinus Walleij 	/* Extract head of queue */
1597d1c44c93SVladimir Oltean 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1598d1c44c93SVladimir Oltean 	ctlr->cur_msg = msg;
1599ffbbdd21SLinus Walleij 
1600d1c44c93SVladimir Oltean 	list_del_init(&msg->queue);
16018caab75fSGeert Uytterhoeven 	if (ctlr->busy)
1602ffbbdd21SLinus Walleij 		was_busy = true;
1603ffbbdd21SLinus Walleij 	else
16048caab75fSGeert Uytterhoeven 		ctlr->busy = true;
16058caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1606ffbbdd21SLinus Walleij 
16078caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->io_mutex);
1608ef4d96ecSMark Brown 
16098caab75fSGeert Uytterhoeven 	if (!was_busy && ctlr->auto_runtime_pm) {
16108caab75fSGeert Uytterhoeven 		ret = pm_runtime_get_sync(ctlr->dev.parent);
161149834de2SMark Brown 		if (ret < 0) {
16127e48e23aSTony Lindgren 			pm_runtime_put_noidle(ctlr->dev.parent);
16138caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
161449834de2SMark Brown 				ret);
16158caab75fSGeert Uytterhoeven 			mutex_unlock(&ctlr->io_mutex);
161649834de2SMark Brown 			return;
161749834de2SMark Brown 		}
161849834de2SMark Brown 	}
161949834de2SMark Brown 
162056ec1978SMark Brown 	if (!was_busy)
16218caab75fSGeert Uytterhoeven 		trace_spi_controller_busy(ctlr);
162256ec1978SMark Brown 
16238caab75fSGeert Uytterhoeven 	if (!was_busy && ctlr->prepare_transfer_hardware) {
16248caab75fSGeert Uytterhoeven 		ret = ctlr->prepare_transfer_hardware(ctlr);
1625ffbbdd21SLinus Walleij 		if (ret) {
16268caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev,
1627f3440d9aSSuper Liu 				"failed to prepare transfer hardware: %d\n",
1628f3440d9aSSuper Liu 				ret);
162949834de2SMark Brown 
16308caab75fSGeert Uytterhoeven 			if (ctlr->auto_runtime_pm)
16318caab75fSGeert Uytterhoeven 				pm_runtime_put(ctlr->dev.parent);
1632f3440d9aSSuper Liu 
1633d1c44c93SVladimir Oltean 			msg->status = ret;
1634f3440d9aSSuper Liu 			spi_finalize_current_message(ctlr);
1635f3440d9aSSuper Liu 
16368caab75fSGeert Uytterhoeven 			mutex_unlock(&ctlr->io_mutex);
1637ffbbdd21SLinus Walleij 			return;
1638ffbbdd21SLinus Walleij 		}
1639ffbbdd21SLinus Walleij 	}
1640ffbbdd21SLinus Walleij 
1641d1c44c93SVladimir Oltean 	trace_spi_message_start(msg);
164256ec1978SMark Brown 
16438caab75fSGeert Uytterhoeven 	if (ctlr->prepare_message) {
1644d1c44c93SVladimir Oltean 		ret = ctlr->prepare_message(ctlr, msg);
16452841a5fcSMark Brown 		if (ret) {
16468caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
16478caab75fSGeert Uytterhoeven 				ret);
1648d1c44c93SVladimir Oltean 			msg->status = ret;
16498caab75fSGeert Uytterhoeven 			spi_finalize_current_message(ctlr);
165049023d2eSJon Hunter 			goto out;
16512841a5fcSMark Brown 		}
16528caab75fSGeert Uytterhoeven 		ctlr->cur_msg_prepared = true;
16532841a5fcSMark Brown 	}
16542841a5fcSMark Brown 
1655d1c44c93SVladimir Oltean 	ret = spi_map_msg(ctlr, msg);
165699adef31SMark Brown 	if (ret) {
1657d1c44c93SVladimir Oltean 		msg->status = ret;
16588caab75fSGeert Uytterhoeven 		spi_finalize_current_message(ctlr);
165949023d2eSJon Hunter 		goto out;
166099adef31SMark Brown 	}
166199adef31SMark Brown 
1662b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1663b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1664b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1665b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1666b42faeeeSVladimir Oltean 		}
1667b42faeeeSVladimir Oltean 	}
1668b42faeeeSVladimir Oltean 
1669d1c44c93SVladimir Oltean 	ret = ctlr->transfer_one_message(ctlr, msg);
1670ffbbdd21SLinus Walleij 	if (ret) {
16718caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev,
16721f802f82SGeert Uytterhoeven 			"failed to transfer one message from queue\n");
167349023d2eSJon Hunter 		goto out;
1674ffbbdd21SLinus Walleij 	}
167549023d2eSJon Hunter 
167649023d2eSJon Hunter out:
16778caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->io_mutex);
167862826970SMark Brown 
167962826970SMark Brown 	/* Prod the scheduler in case transfer_one() was busy waiting */
168049023d2eSJon Hunter 	if (!ret)
168162826970SMark Brown 		cond_resched();
1682ffbbdd21SLinus Walleij }
1683ffbbdd21SLinus Walleij 
1684fc9e0f71SMark Brown /**
1685fc9e0f71SMark Brown  * spi_pump_messages - kthread work function which processes spi message queue
16868caab75fSGeert Uytterhoeven  * @work: pointer to kthread work struct contained in the controller struct
1687fc9e0f71SMark Brown  */
1688fc9e0f71SMark Brown static void spi_pump_messages(struct kthread_work *work)
1689fc9e0f71SMark Brown {
16908caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr =
16918caab75fSGeert Uytterhoeven 		container_of(work, struct spi_controller, pump_messages);
1692fc9e0f71SMark Brown 
16938caab75fSGeert Uytterhoeven 	__spi_pump_messages(ctlr, true);
1694fc9e0f71SMark Brown }
1695fc9e0f71SMark Brown 
1696924b5867SDouglas Anderson /**
1697350de7ceSAndy Shevchenko  * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1698b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1699b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1700862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1701b42faeeeSVladimir Oltean  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1702b42faeeeSVladimir Oltean  *	      transfer, for less jitter in time measurement. Only compatible
1703b42faeeeSVladimir Oltean  *	      with PIO drivers. If true, must follow up with
1704b42faeeeSVladimir Oltean  *	      spi_take_timestamp_post or otherwise system will crash.
1705b42faeeeSVladimir Oltean  *	      WARNING: for fully predictable results, the CPU frequency must
1706b42faeeeSVladimir Oltean  *	      also be under control (governor).
1707350de7ceSAndy Shevchenko  *
1708350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the beginning of the TX timestamp
1709350de7ceSAndy Shevchenko  * for the requested byte from the SPI transfer. The frequency with which this
1710350de7ceSAndy Shevchenko  * function must be called (once per word, once for the whole transfer, once
1711350de7ceSAndy Shevchenko  * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1712350de7ceSAndy Shevchenko  * greater than or equal to the requested byte at the time of the call. The
1713350de7ceSAndy Shevchenko  * timestamp is only taken once, at the first such call. It is assumed that
1714350de7ceSAndy Shevchenko  * the driver advances its @tx buffer pointer monotonically.
1715b42faeeeSVladimir Oltean  */
1716b42faeeeSVladimir Oltean void spi_take_timestamp_pre(struct spi_controller *ctlr,
1717b42faeeeSVladimir Oltean 			    struct spi_transfer *xfer,
1718862dd2a9SVladimir Oltean 			    size_t progress, bool irqs_off)
1719b42faeeeSVladimir Oltean {
1720b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1721b42faeeeSVladimir Oltean 		return;
1722b42faeeeSVladimir Oltean 
17236a726824SVladimir Oltean 	if (xfer->timestamped)
1724b42faeeeSVladimir Oltean 		return;
1725b42faeeeSVladimir Oltean 
17266a726824SVladimir Oltean 	if (progress > xfer->ptp_sts_word_pre)
1727b42faeeeSVladimir Oltean 		return;
1728b42faeeeSVladimir Oltean 
1729b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1730862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_pre = progress;
1731b42faeeeSVladimir Oltean 
1732b42faeeeSVladimir Oltean 	if (irqs_off) {
1733b42faeeeSVladimir Oltean 		local_irq_save(ctlr->irq_flags);
1734b42faeeeSVladimir Oltean 		preempt_disable();
1735b42faeeeSVladimir Oltean 	}
1736b42faeeeSVladimir Oltean 
1737b42faeeeSVladimir Oltean 	ptp_read_system_prets(xfer->ptp_sts);
1738b42faeeeSVladimir Oltean }
1739b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1740b42faeeeSVladimir Oltean 
1741b42faeeeSVladimir Oltean /**
1742350de7ceSAndy Shevchenko  * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1743b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1744b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1745862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1746b42faeeeSVladimir Oltean  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1747350de7ceSAndy Shevchenko  *
1748350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the end of the TX timestamp for
1749350de7ceSAndy Shevchenko  * the requested byte from the SPI transfer. Can be called with an arbitrary
1750350de7ceSAndy Shevchenko  * frequency: only the first call where @tx exceeds or is equal to the
1751350de7ceSAndy Shevchenko  * requested word will be timestamped.
1752b42faeeeSVladimir Oltean  */
1753b42faeeeSVladimir Oltean void spi_take_timestamp_post(struct spi_controller *ctlr,
1754b42faeeeSVladimir Oltean 			     struct spi_transfer *xfer,
1755862dd2a9SVladimir Oltean 			     size_t progress, bool irqs_off)
1756b42faeeeSVladimir Oltean {
1757b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1758b42faeeeSVladimir Oltean 		return;
1759b42faeeeSVladimir Oltean 
17606a726824SVladimir Oltean 	if (xfer->timestamped)
1761b42faeeeSVladimir Oltean 		return;
1762b42faeeeSVladimir Oltean 
1763862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_post)
1764b42faeeeSVladimir Oltean 		return;
1765b42faeeeSVladimir Oltean 
1766b42faeeeSVladimir Oltean 	ptp_read_system_postts(xfer->ptp_sts);
1767b42faeeeSVladimir Oltean 
1768b42faeeeSVladimir Oltean 	if (irqs_off) {
1769b42faeeeSVladimir Oltean 		local_irq_restore(ctlr->irq_flags);
1770b42faeeeSVladimir Oltean 		preempt_enable();
1771b42faeeeSVladimir Oltean 	}
1772b42faeeeSVladimir Oltean 
1773b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1774862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_post = progress;
1775b42faeeeSVladimir Oltean 
17766a726824SVladimir Oltean 	xfer->timestamped = true;
1777b42faeeeSVladimir Oltean }
1778b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1779b42faeeeSVladimir Oltean 
1780b42faeeeSVladimir Oltean /**
1781924b5867SDouglas Anderson  * spi_set_thread_rt - set the controller to pump at realtime priority
1782924b5867SDouglas Anderson  * @ctlr: controller to boost priority of
1783924b5867SDouglas Anderson  *
1784924b5867SDouglas Anderson  * This can be called because the controller requested realtime priority
1785924b5867SDouglas Anderson  * (by setting the ->rt value before calling spi_register_controller()) or
1786924b5867SDouglas Anderson  * because a device on the bus said that its transfers needed realtime
1787924b5867SDouglas Anderson  * priority.
1788924b5867SDouglas Anderson  *
1789924b5867SDouglas Anderson  * NOTE: at the moment if any device on a bus says it needs realtime then
1790924b5867SDouglas Anderson  * the thread will be at realtime priority for all transfers on that
1791924b5867SDouglas Anderson  * controller.  If this eventually becomes a problem we may see if we can
1792924b5867SDouglas Anderson  * find a way to boost the priority only temporarily during relevant
1793924b5867SDouglas Anderson  * transfers.
1794924b5867SDouglas Anderson  */
1795924b5867SDouglas Anderson static void spi_set_thread_rt(struct spi_controller *ctlr)
1796ffbbdd21SLinus Walleij {
1797924b5867SDouglas Anderson 	dev_info(&ctlr->dev,
1798924b5867SDouglas Anderson 		"will run message pump with realtime priority\n");
17996d2b84a4SLinus Torvalds 	sched_set_fifo(ctlr->kworker->task);
1800924b5867SDouglas Anderson }
1801924b5867SDouglas Anderson 
1802924b5867SDouglas Anderson static int spi_init_queue(struct spi_controller *ctlr)
1803924b5867SDouglas Anderson {
18048caab75fSGeert Uytterhoeven 	ctlr->running = false;
18058caab75fSGeert Uytterhoeven 	ctlr->busy = false;
1806ffbbdd21SLinus Walleij 
180760a883d1SMarek Szyprowski 	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
180860a883d1SMarek Szyprowski 	if (IS_ERR(ctlr->kworker)) {
180960a883d1SMarek Szyprowski 		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
181060a883d1SMarek Szyprowski 		return PTR_ERR(ctlr->kworker);
1811ffbbdd21SLinus Walleij 	}
181260a883d1SMarek Szyprowski 
18138caab75fSGeert Uytterhoeven 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1814f0125f1aSMark Brown 
1815ffbbdd21SLinus Walleij 	/*
18168caab75fSGeert Uytterhoeven 	 * Controller config will indicate if this controller should run the
1817ffbbdd21SLinus Walleij 	 * message pump with high (realtime) priority to reduce the transfer
1818ffbbdd21SLinus Walleij 	 * latency on the bus by minimising the delay between a transfer
1819ffbbdd21SLinus Walleij 	 * request and the scheduling of the message pump thread. Without this
1820ffbbdd21SLinus Walleij 	 * setting the message pump thread will remain at default priority.
1821ffbbdd21SLinus Walleij 	 */
1822924b5867SDouglas Anderson 	if (ctlr->rt)
1823924b5867SDouglas Anderson 		spi_set_thread_rt(ctlr);
1824ffbbdd21SLinus Walleij 
1825ffbbdd21SLinus Walleij 	return 0;
1826ffbbdd21SLinus Walleij }
1827ffbbdd21SLinus Walleij 
1828ffbbdd21SLinus Walleij /**
1829ffbbdd21SLinus Walleij  * spi_get_next_queued_message() - called by driver to check for queued
1830ffbbdd21SLinus Walleij  * messages
18318caab75fSGeert Uytterhoeven  * @ctlr: the controller to check for queued messages
1832ffbbdd21SLinus Walleij  *
1833ffbbdd21SLinus Walleij  * If there are more messages in the queue, the next message is returned from
1834ffbbdd21SLinus Walleij  * this call.
183597d56dc6SJavier Martinez Canillas  *
183697d56dc6SJavier Martinez Canillas  * Return: the next message in the queue, else NULL if the queue is empty.
1837ffbbdd21SLinus Walleij  */
18388caab75fSGeert Uytterhoeven struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1839ffbbdd21SLinus Walleij {
1840ffbbdd21SLinus Walleij 	struct spi_message *next;
1841ffbbdd21SLinus Walleij 	unsigned long flags;
1842ffbbdd21SLinus Walleij 
1843ffbbdd21SLinus Walleij 	/* get a pointer to the next message, if any */
18448caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
18458caab75fSGeert Uytterhoeven 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
18461cfd97f9SAxel Lin 					queue);
18478caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1848ffbbdd21SLinus Walleij 
1849ffbbdd21SLinus Walleij 	return next;
1850ffbbdd21SLinus Walleij }
1851ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1852ffbbdd21SLinus Walleij 
1853ffbbdd21SLinus Walleij /**
1854ffbbdd21SLinus Walleij  * spi_finalize_current_message() - the current message is complete
18558caab75fSGeert Uytterhoeven  * @ctlr: the controller to return the message to
1856ffbbdd21SLinus Walleij  *
1857ffbbdd21SLinus Walleij  * Called by the driver to notify the core that the message in the front of the
1858ffbbdd21SLinus Walleij  * queue is complete and can be removed from the queue.
1859ffbbdd21SLinus Walleij  */
18608caab75fSGeert Uytterhoeven void spi_finalize_current_message(struct spi_controller *ctlr)
1861ffbbdd21SLinus Walleij {
1862b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
1863ffbbdd21SLinus Walleij 	struct spi_message *mesg;
1864ffbbdd21SLinus Walleij 	unsigned long flags;
18652841a5fcSMark Brown 	int ret;
1866ffbbdd21SLinus Walleij 
18678caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
18688caab75fSGeert Uytterhoeven 	mesg = ctlr->cur_msg;
18698caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1870ffbbdd21SLinus Walleij 
1871b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1872b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1873b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1874b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1875b42faeeeSVladimir Oltean 		}
1876b42faeeeSVladimir Oltean 	}
1877b42faeeeSVladimir Oltean 
18786a726824SVladimir Oltean 	if (unlikely(ctlr->ptp_sts_supported))
18796a726824SVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
18806a726824SVladimir Oltean 			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1881f971a207SVladimir Oltean 
18828caab75fSGeert Uytterhoeven 	spi_unmap_msg(ctlr, mesg);
188399adef31SMark Brown 
1884350de7ceSAndy Shevchenko 	/*
1885350de7ceSAndy Shevchenko 	 * In the prepare_messages callback the SPI bus has the opportunity
1886350de7ceSAndy Shevchenko 	 * to split a transfer to smaller chunks.
1887350de7ceSAndy Shevchenko 	 *
1888350de7ceSAndy Shevchenko 	 * Release the split transfers here since spi_map_msg() is done on
1889350de7ceSAndy Shevchenko 	 * the split transfers.
1890b59a7ca1SGustav Wiklander 	 */
1891b59a7ca1SGustav Wiklander 	spi_res_release(ctlr, mesg);
1892b59a7ca1SGustav Wiklander 
18938caab75fSGeert Uytterhoeven 	if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
18948caab75fSGeert Uytterhoeven 		ret = ctlr->unprepare_message(ctlr, mesg);
18952841a5fcSMark Brown 		if (ret) {
18968caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
18978caab75fSGeert Uytterhoeven 				ret);
18982841a5fcSMark Brown 		}
18992841a5fcSMark Brown 	}
1900391949b6SUwe Kleine-König 
19018caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
19028caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
19038caab75fSGeert Uytterhoeven 	ctlr->cur_msg_prepared = false;
1904809b1b04SRobin Gong 	ctlr->fallback = false;
190560a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
19068caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
19078e76ef88SMartin Sperl 
19088e76ef88SMartin Sperl 	trace_spi_message_done(mesg);
19092841a5fcSMark Brown 
1910ffbbdd21SLinus Walleij 	mesg->state = NULL;
1911ffbbdd21SLinus Walleij 	if (mesg->complete)
1912ffbbdd21SLinus Walleij 		mesg->complete(mesg->context);
1913ffbbdd21SLinus Walleij }
1914ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1915ffbbdd21SLinus Walleij 
19168caab75fSGeert Uytterhoeven static int spi_start_queue(struct spi_controller *ctlr)
1917ffbbdd21SLinus Walleij {
1918ffbbdd21SLinus Walleij 	unsigned long flags;
1919ffbbdd21SLinus Walleij 
19208caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1921ffbbdd21SLinus Walleij 
19228caab75fSGeert Uytterhoeven 	if (ctlr->running || ctlr->busy) {
19238caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1924ffbbdd21SLinus Walleij 		return -EBUSY;
1925ffbbdd21SLinus Walleij 	}
1926ffbbdd21SLinus Walleij 
19278caab75fSGeert Uytterhoeven 	ctlr->running = true;
19288caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
19298caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1930ffbbdd21SLinus Walleij 
193160a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1932ffbbdd21SLinus Walleij 
1933ffbbdd21SLinus Walleij 	return 0;
1934ffbbdd21SLinus Walleij }
1935ffbbdd21SLinus Walleij 
19368caab75fSGeert Uytterhoeven static int spi_stop_queue(struct spi_controller *ctlr)
1937ffbbdd21SLinus Walleij {
1938ffbbdd21SLinus Walleij 	unsigned long flags;
1939ffbbdd21SLinus Walleij 	unsigned limit = 500;
1940ffbbdd21SLinus Walleij 	int ret = 0;
1941ffbbdd21SLinus Walleij 
19428caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1943ffbbdd21SLinus Walleij 
1944ffbbdd21SLinus Walleij 	/*
1945ffbbdd21SLinus Walleij 	 * This is a bit lame, but is optimized for the common execution path.
19468caab75fSGeert Uytterhoeven 	 * A wait_queue on the ctlr->busy could be used, but then the common
1947ffbbdd21SLinus Walleij 	 * execution path (pump_messages) would be required to call wake_up or
1948ffbbdd21SLinus Walleij 	 * friends on every SPI message. Do this instead.
1949ffbbdd21SLinus Walleij 	 */
19508caab75fSGeert Uytterhoeven 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
19518caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1952f97b26b0SAxel Lin 		usleep_range(10000, 11000);
19538caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1954ffbbdd21SLinus Walleij 	}
1955ffbbdd21SLinus Walleij 
19568caab75fSGeert Uytterhoeven 	if (!list_empty(&ctlr->queue) || ctlr->busy)
1957ffbbdd21SLinus Walleij 		ret = -EBUSY;
1958ffbbdd21SLinus Walleij 	else
19598caab75fSGeert Uytterhoeven 		ctlr->running = false;
1960ffbbdd21SLinus Walleij 
19618caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1962ffbbdd21SLinus Walleij 
1963ffbbdd21SLinus Walleij 	if (ret) {
19648caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "could not stop message queue\n");
1965ffbbdd21SLinus Walleij 		return ret;
1966ffbbdd21SLinus Walleij 	}
1967ffbbdd21SLinus Walleij 	return ret;
1968ffbbdd21SLinus Walleij }
1969ffbbdd21SLinus Walleij 
19708caab75fSGeert Uytterhoeven static int spi_destroy_queue(struct spi_controller *ctlr)
1971ffbbdd21SLinus Walleij {
1972ffbbdd21SLinus Walleij 	int ret;
1973ffbbdd21SLinus Walleij 
19748caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
1975ffbbdd21SLinus Walleij 
1976ffbbdd21SLinus Walleij 	/*
19773989144fSPetr Mladek 	 * kthread_flush_worker will block until all work is done.
1978ffbbdd21SLinus Walleij 	 * If the reason that stop_queue timed out is that the work will never
1979ffbbdd21SLinus Walleij 	 * finish, then it does no good to call flush/stop thread, so
1980ffbbdd21SLinus Walleij 	 * return anyway.
1981ffbbdd21SLinus Walleij 	 */
1982ffbbdd21SLinus Walleij 	if (ret) {
19838caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem destroying queue\n");
1984ffbbdd21SLinus Walleij 		return ret;
1985ffbbdd21SLinus Walleij 	}
1986ffbbdd21SLinus Walleij 
198760a883d1SMarek Szyprowski 	kthread_destroy_worker(ctlr->kworker);
1988ffbbdd21SLinus Walleij 
1989ffbbdd21SLinus Walleij 	return 0;
1990ffbbdd21SLinus Walleij }
1991ffbbdd21SLinus Walleij 
19920461a414SMark Brown static int __spi_queued_transfer(struct spi_device *spi,
19930461a414SMark Brown 				 struct spi_message *msg,
19940461a414SMark Brown 				 bool need_pump)
1995ffbbdd21SLinus Walleij {
19968caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
1997ffbbdd21SLinus Walleij 	unsigned long flags;
1998ffbbdd21SLinus Walleij 
19998caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2000ffbbdd21SLinus Walleij 
20018caab75fSGeert Uytterhoeven 	if (!ctlr->running) {
20028caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2003ffbbdd21SLinus Walleij 		return -ESHUTDOWN;
2004ffbbdd21SLinus Walleij 	}
2005ffbbdd21SLinus Walleij 	msg->actual_length = 0;
2006ffbbdd21SLinus Walleij 	msg->status = -EINPROGRESS;
2007ffbbdd21SLinus Walleij 
20088caab75fSGeert Uytterhoeven 	list_add_tail(&msg->queue, &ctlr->queue);
2009f0125f1aSMark Brown 	if (!ctlr->busy && need_pump)
201060a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2011ffbbdd21SLinus Walleij 
20128caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2013ffbbdd21SLinus Walleij 	return 0;
2014ffbbdd21SLinus Walleij }
2015ffbbdd21SLinus Walleij 
20160461a414SMark Brown /**
20170461a414SMark Brown  * spi_queued_transfer - transfer function for queued transfers
20180461a414SMark Brown  * @spi: spi device which is requesting transfer
20190461a414SMark Brown  * @msg: spi message which is to handled is queued to driver queue
202097d56dc6SJavier Martinez Canillas  *
202197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
20220461a414SMark Brown  */
20230461a414SMark Brown static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
20240461a414SMark Brown {
20250461a414SMark Brown 	return __spi_queued_transfer(spi, msg, true);
20260461a414SMark Brown }
20270461a414SMark Brown 
20288caab75fSGeert Uytterhoeven static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2029ffbbdd21SLinus Walleij {
2030ffbbdd21SLinus Walleij 	int ret;
2031ffbbdd21SLinus Walleij 
20328caab75fSGeert Uytterhoeven 	ctlr->transfer = spi_queued_transfer;
20338caab75fSGeert Uytterhoeven 	if (!ctlr->transfer_one_message)
20348caab75fSGeert Uytterhoeven 		ctlr->transfer_one_message = spi_transfer_one_message;
2035ffbbdd21SLinus Walleij 
2036ffbbdd21SLinus Walleij 	/* Initialize and start queue */
20378caab75fSGeert Uytterhoeven 	ret = spi_init_queue(ctlr);
2038ffbbdd21SLinus Walleij 	if (ret) {
20398caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem initializing queue\n");
2040ffbbdd21SLinus Walleij 		goto err_init_queue;
2041ffbbdd21SLinus Walleij 	}
20428caab75fSGeert Uytterhoeven 	ctlr->queued = true;
20438caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
2044ffbbdd21SLinus Walleij 	if (ret) {
20458caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem starting queue\n");
2046ffbbdd21SLinus Walleij 		goto err_start_queue;
2047ffbbdd21SLinus Walleij 	}
2048ffbbdd21SLinus Walleij 
2049ffbbdd21SLinus Walleij 	return 0;
2050ffbbdd21SLinus Walleij 
2051ffbbdd21SLinus Walleij err_start_queue:
20528caab75fSGeert Uytterhoeven 	spi_destroy_queue(ctlr);
2053c3676d5cSMark Brown err_init_queue:
2054ffbbdd21SLinus Walleij 	return ret;
2055ffbbdd21SLinus Walleij }
2056ffbbdd21SLinus Walleij 
2057988f259bSBoris Brezillon /**
2058988f259bSBoris Brezillon  * spi_flush_queue - Send all pending messages in the queue from the callers'
2059988f259bSBoris Brezillon  *		     context
2060988f259bSBoris Brezillon  * @ctlr: controller to process queue for
2061988f259bSBoris Brezillon  *
2062988f259bSBoris Brezillon  * This should be used when one wants to ensure all pending messages have been
2063988f259bSBoris Brezillon  * sent before doing something. Is used by the spi-mem code to make sure SPI
2064988f259bSBoris Brezillon  * memory operations do not preempt regular SPI transfers that have been queued
2065988f259bSBoris Brezillon  * before the spi-mem operation.
2066988f259bSBoris Brezillon  */
2067988f259bSBoris Brezillon void spi_flush_queue(struct spi_controller *ctlr)
2068988f259bSBoris Brezillon {
2069988f259bSBoris Brezillon 	if (ctlr->transfer == spi_queued_transfer)
2070988f259bSBoris Brezillon 		__spi_pump_messages(ctlr, false);
2071988f259bSBoris Brezillon }
2072988f259bSBoris Brezillon 
2073ffbbdd21SLinus Walleij /*-------------------------------------------------------------------------*/
2074ffbbdd21SLinus Walleij 
20757cb94361SAndreas Larsson #if defined(CONFIG_OF)
20768caab75fSGeert Uytterhoeven static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2077c2e51ac3SGeert Uytterhoeven 			   struct device_node *nc)
2078d57a4282SGrant Likely {
207989da4293STrent Piepho 	u32 value;
2080c2e51ac3SGeert Uytterhoeven 	int rc;
2081d57a4282SGrant Likely 
2082d57a4282SGrant Likely 	/* Mode (clock phase/polarity/etc.) */
2083e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpha"))
2084d57a4282SGrant Likely 		spi->mode |= SPI_CPHA;
2085e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpol"))
2086d57a4282SGrant Likely 		spi->mode |= SPI_CPOL;
2087e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-3wire"))
2088c20151dfSLars-Peter Clausen 		spi->mode |= SPI_3WIRE;
2089e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-lsb-first"))
2090cd6339e6SZhao Qiang 		spi->mode |= SPI_LSB_FIRST;
20913e5ec1dbSGregory CLEMENT 	if (of_property_read_bool(nc, "spi-cs-high"))
2092f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
2093f3186dd8SLinus Walleij 
2094f477b7fbSwangyuhang 	/* Device DUAL/QUAD mode */
209589da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
209689da4293STrent Piepho 		switch (value) {
2097d962608cSDragos Bogdan 		case 0:
2098d962608cSDragos Bogdan 			spi->mode |= SPI_NO_TX;
2099d962608cSDragos Bogdan 			break;
210089da4293STrent Piepho 		case 1:
2101f477b7fbSwangyuhang 			break;
210289da4293STrent Piepho 		case 2:
2103f477b7fbSwangyuhang 			spi->mode |= SPI_TX_DUAL;
2104f477b7fbSwangyuhang 			break;
210589da4293STrent Piepho 		case 4:
2106f477b7fbSwangyuhang 			spi->mode |= SPI_TX_QUAD;
2107f477b7fbSwangyuhang 			break;
21086b03061fSYogesh Narayan Gaur 		case 8:
21096b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_TX_OCTAL;
21106b03061fSYogesh Narayan Gaur 			break;
2111f477b7fbSwangyuhang 		default:
21128caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2113a110f93dSwangyuhang 				"spi-tx-bus-width %d not supported\n",
211489da4293STrent Piepho 				value);
211580874d8cSGeert Uytterhoeven 			break;
2116f477b7fbSwangyuhang 		}
2117a822e99cSMark Brown 	}
2118f477b7fbSwangyuhang 
211989da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
212089da4293STrent Piepho 		switch (value) {
2121d962608cSDragos Bogdan 		case 0:
2122d962608cSDragos Bogdan 			spi->mode |= SPI_NO_RX;
2123d962608cSDragos Bogdan 			break;
212489da4293STrent Piepho 		case 1:
2125f477b7fbSwangyuhang 			break;
212689da4293STrent Piepho 		case 2:
2127f477b7fbSwangyuhang 			spi->mode |= SPI_RX_DUAL;
2128f477b7fbSwangyuhang 			break;
212989da4293STrent Piepho 		case 4:
2130f477b7fbSwangyuhang 			spi->mode |= SPI_RX_QUAD;
2131f477b7fbSwangyuhang 			break;
21326b03061fSYogesh Narayan Gaur 		case 8:
21336b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_RX_OCTAL;
21346b03061fSYogesh Narayan Gaur 			break;
2135f477b7fbSwangyuhang 		default:
21368caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2137a110f93dSwangyuhang 				"spi-rx-bus-width %d not supported\n",
213889da4293STrent Piepho 				value);
213980874d8cSGeert Uytterhoeven 			break;
2140f477b7fbSwangyuhang 		}
2141a822e99cSMark Brown 	}
2142f477b7fbSwangyuhang 
21438caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr)) {
2144194276b0SRob Herring 		if (!of_node_name_eq(nc, "slave")) {
214525c56c88SRob Herring 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
214625c56c88SRob Herring 				nc);
21476c364062SGeert Uytterhoeven 			return -EINVAL;
21486c364062SGeert Uytterhoeven 		}
21496c364062SGeert Uytterhoeven 		return 0;
21506c364062SGeert Uytterhoeven 	}
21516c364062SGeert Uytterhoeven 
21526c364062SGeert Uytterhoeven 	/* Device address */
21536c364062SGeert Uytterhoeven 	rc = of_property_read_u32(nc, "reg", &value);
21546c364062SGeert Uytterhoeven 	if (rc) {
215525c56c88SRob Herring 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
215625c56c88SRob Herring 			nc, rc);
21576c364062SGeert Uytterhoeven 		return rc;
21586c364062SGeert Uytterhoeven 	}
21596c364062SGeert Uytterhoeven 	spi->chip_select = value;
21606c364062SGeert Uytterhoeven 
2161d57a4282SGrant Likely 	/* Device speed */
2162671c3bf5SChuanhong Guo 	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
216389da4293STrent Piepho 		spi->max_speed_hz = value;
2164d57a4282SGrant Likely 
2165c2e51ac3SGeert Uytterhoeven 	return 0;
2166c2e51ac3SGeert Uytterhoeven }
2167c2e51ac3SGeert Uytterhoeven 
2168c2e51ac3SGeert Uytterhoeven static struct spi_device *
21698caab75fSGeert Uytterhoeven of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2170c2e51ac3SGeert Uytterhoeven {
2171c2e51ac3SGeert Uytterhoeven 	struct spi_device *spi;
2172c2e51ac3SGeert Uytterhoeven 	int rc;
2173c2e51ac3SGeert Uytterhoeven 
2174c2e51ac3SGeert Uytterhoeven 	/* Alloc an spi_device */
21758caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
2176c2e51ac3SGeert Uytterhoeven 	if (!spi) {
217725c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2178c2e51ac3SGeert Uytterhoeven 		rc = -ENOMEM;
2179c2e51ac3SGeert Uytterhoeven 		goto err_out;
2180c2e51ac3SGeert Uytterhoeven 	}
2181c2e51ac3SGeert Uytterhoeven 
2182c2e51ac3SGeert Uytterhoeven 	/* Select device driver */
2183c2e51ac3SGeert Uytterhoeven 	rc = of_modalias_node(nc, spi->modalias,
2184c2e51ac3SGeert Uytterhoeven 				sizeof(spi->modalias));
2185c2e51ac3SGeert Uytterhoeven 	if (rc < 0) {
218625c56c88SRob Herring 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2187c2e51ac3SGeert Uytterhoeven 		goto err_out;
2188c2e51ac3SGeert Uytterhoeven 	}
2189c2e51ac3SGeert Uytterhoeven 
21908caab75fSGeert Uytterhoeven 	rc = of_spi_parse_dt(ctlr, spi, nc);
2191c2e51ac3SGeert Uytterhoeven 	if (rc)
2192c2e51ac3SGeert Uytterhoeven 		goto err_out;
2193c2e51ac3SGeert Uytterhoeven 
2194d57a4282SGrant Likely 	/* Store a pointer to the node in the device structure */
2195d57a4282SGrant Likely 	of_node_get(nc);
2196d57a4282SGrant Likely 	spi->dev.of_node = nc;
21970e793ba7SCharles Keepax 	spi->dev.fwnode = of_fwnode_handle(nc);
2198d57a4282SGrant Likely 
2199d57a4282SGrant Likely 	/* Register the new device */
2200d57a4282SGrant Likely 	rc = spi_add_device(spi);
2201d57a4282SGrant Likely 	if (rc) {
220225c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
22038324147fSJohan Hovold 		goto err_of_node_put;
2204d57a4282SGrant Likely 	}
2205d57a4282SGrant Likely 
2206aff5e3f8SPantelis Antoniou 	return spi;
2207aff5e3f8SPantelis Antoniou 
22088324147fSJohan Hovold err_of_node_put:
22098324147fSJohan Hovold 	of_node_put(nc);
2210aff5e3f8SPantelis Antoniou err_out:
2211aff5e3f8SPantelis Antoniou 	spi_dev_put(spi);
2212aff5e3f8SPantelis Antoniou 	return ERR_PTR(rc);
2213aff5e3f8SPantelis Antoniou }
2214aff5e3f8SPantelis Antoniou 
2215aff5e3f8SPantelis Antoniou /**
2216aff5e3f8SPantelis Antoniou  * of_register_spi_devices() - Register child devices onto the SPI bus
22178caab75fSGeert Uytterhoeven  * @ctlr:	Pointer to spi_controller device
2218aff5e3f8SPantelis Antoniou  *
22196c364062SGeert Uytterhoeven  * Registers an spi_device for each child node of controller node which
22206c364062SGeert Uytterhoeven  * represents a valid SPI slave.
2221aff5e3f8SPantelis Antoniou  */
22228caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr)
2223aff5e3f8SPantelis Antoniou {
2224aff5e3f8SPantelis Antoniou 	struct spi_device *spi;
2225aff5e3f8SPantelis Antoniou 	struct device_node *nc;
2226aff5e3f8SPantelis Antoniou 
22278caab75fSGeert Uytterhoeven 	if (!ctlr->dev.of_node)
2228aff5e3f8SPantelis Antoniou 		return;
2229aff5e3f8SPantelis Antoniou 
22308caab75fSGeert Uytterhoeven 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2231bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2232bd6c1644SGeert Uytterhoeven 			continue;
22338caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, nc);
2234e0af98a7SRalf Ramsauer 		if (IS_ERR(spi)) {
22358caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
223625c56c88SRob Herring 				 "Failed to create SPI device for %pOF\n", nc);
2237e0af98a7SRalf Ramsauer 			of_node_clear_flag(nc, OF_POPULATED);
2238e0af98a7SRalf Ramsauer 		}
2239d57a4282SGrant Likely 	}
2240d57a4282SGrant Likely }
2241d57a4282SGrant Likely #else
22428caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr) { }
2243d57a4282SGrant Likely #endif
2244d57a4282SGrant Likely 
22450c79378cSSebastian Reichel /**
22460c79378cSSebastian Reichel  * spi_new_ancillary_device() - Register ancillary SPI device
22470c79378cSSebastian Reichel  * @spi:         Pointer to the main SPI device registering the ancillary device
22480c79378cSSebastian Reichel  * @chip_select: Chip Select of the ancillary device
22490c79378cSSebastian Reichel  *
22500c79378cSSebastian Reichel  * Register an ancillary SPI device; for example some chips have a chip-select
22510c79378cSSebastian Reichel  * for normal device usage and another one for setup/firmware upload.
22520c79378cSSebastian Reichel  *
22530c79378cSSebastian Reichel  * This may only be called from main SPI device's probe routine.
22540c79378cSSebastian Reichel  *
22550c79378cSSebastian Reichel  * Return: 0 on success; negative errno on failure
22560c79378cSSebastian Reichel  */
22570c79378cSSebastian Reichel struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
22580c79378cSSebastian Reichel 					     u8 chip_select)
22590c79378cSSebastian Reichel {
22600c79378cSSebastian Reichel 	struct spi_device *ancillary;
22610c79378cSSebastian Reichel 	int rc = 0;
22620c79378cSSebastian Reichel 
22630c79378cSSebastian Reichel 	/* Alloc an spi_device */
22640c79378cSSebastian Reichel 	ancillary = spi_alloc_device(spi->controller);
22650c79378cSSebastian Reichel 	if (!ancillary) {
22660c79378cSSebastian Reichel 		rc = -ENOMEM;
22670c79378cSSebastian Reichel 		goto err_out;
22680c79378cSSebastian Reichel 	}
22690c79378cSSebastian Reichel 
22700c79378cSSebastian Reichel 	strlcpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
22710c79378cSSebastian Reichel 
22720c79378cSSebastian Reichel 	/* Use provided chip-select for ancillary device */
22730c79378cSSebastian Reichel 	ancillary->chip_select = chip_select;
22740c79378cSSebastian Reichel 
22750c79378cSSebastian Reichel 	/* Take over SPI mode/speed from SPI main device */
22760c79378cSSebastian Reichel 	ancillary->max_speed_hz = spi->max_speed_hz;
2277b01d5506SColin Ian King 	ancillary->mode = spi->mode;
22780c79378cSSebastian Reichel 
22790c79378cSSebastian Reichel 	/* Register the new device */
22800c79378cSSebastian Reichel 	rc = spi_add_device_locked(ancillary);
22810c79378cSSebastian Reichel 	if (rc) {
22820c79378cSSebastian Reichel 		dev_err(&spi->dev, "failed to register ancillary device\n");
22830c79378cSSebastian Reichel 		goto err_out;
22840c79378cSSebastian Reichel 	}
22850c79378cSSebastian Reichel 
22860c79378cSSebastian Reichel 	return ancillary;
22870c79378cSSebastian Reichel 
22880c79378cSSebastian Reichel err_out:
22890c79378cSSebastian Reichel 	spi_dev_put(ancillary);
22900c79378cSSebastian Reichel 	return ERR_PTR(rc);
22910c79378cSSebastian Reichel }
22920c79378cSSebastian Reichel EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
22930c79378cSSebastian Reichel 
229464bee4d2SMika Westerberg #ifdef CONFIG_ACPI
22954c3c5954SArd Biesheuvel struct acpi_spi_lookup {
22964c3c5954SArd Biesheuvel 	struct spi_controller 	*ctlr;
22974c3c5954SArd Biesheuvel 	u32			max_speed_hz;
22984c3c5954SArd Biesheuvel 	u32			mode;
22994c3c5954SArd Biesheuvel 	int			irq;
23004c3c5954SArd Biesheuvel 	u8			bits_per_word;
23014c3c5954SArd Biesheuvel 	u8			chip_select;
230287e59b36SStefan Binding 	int			n;
230387e59b36SStefan Binding 	int			index;
23044c3c5954SArd Biesheuvel };
23054c3c5954SArd Biesheuvel 
2306e612af7aSStefan Binding static int acpi_spi_count(struct acpi_resource *ares, void *data)
2307e612af7aSStefan Binding {
2308e612af7aSStefan Binding 	struct acpi_resource_spi_serialbus *sb;
2309e612af7aSStefan Binding 	int *count = data;
2310e612af7aSStefan Binding 
2311e612af7aSStefan Binding 	if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2312e612af7aSStefan Binding 		return 1;
2313e612af7aSStefan Binding 
2314e612af7aSStefan Binding 	sb = &ares->data.spi_serial_bus;
2315e612af7aSStefan Binding 	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2316e612af7aSStefan Binding 		return 1;
2317e612af7aSStefan Binding 
2318e612af7aSStefan Binding 	*count = *count + 1;
2319e612af7aSStefan Binding 
2320e612af7aSStefan Binding 	return 1;
2321e612af7aSStefan Binding }
2322e612af7aSStefan Binding 
2323e612af7aSStefan Binding /**
2324e612af7aSStefan Binding  * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2325e612af7aSStefan Binding  * @adev:	ACPI device
2326e612af7aSStefan Binding  *
2327e612af7aSStefan Binding  * Returns the number of SpiSerialBus resources in the ACPI-device's
2328e612af7aSStefan Binding  * resource-list; or a negative error code.
2329e612af7aSStefan Binding  */
2330e612af7aSStefan Binding int acpi_spi_count_resources(struct acpi_device *adev)
2331e612af7aSStefan Binding {
2332e612af7aSStefan Binding 	LIST_HEAD(r);
2333e612af7aSStefan Binding 	int count = 0;
2334e612af7aSStefan Binding 	int ret;
2335e612af7aSStefan Binding 
2336e612af7aSStefan Binding 	ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2337e612af7aSStefan Binding 	if (ret < 0)
2338e612af7aSStefan Binding 		return ret;
2339e612af7aSStefan Binding 
2340e612af7aSStefan Binding 	acpi_dev_free_resource_list(&r);
2341e612af7aSStefan Binding 
2342e612af7aSStefan Binding 	return count;
2343e612af7aSStefan Binding }
2344e612af7aSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2345e612af7aSStefan Binding 
23464c3c5954SArd Biesheuvel static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
23474c3c5954SArd Biesheuvel 					    struct acpi_spi_lookup *lookup)
23488a2e487eSLukas Wunner {
23498a2e487eSLukas Wunner 	const union acpi_object *obj;
23508a2e487eSLukas Wunner 
23518a2e487eSLukas Wunner 	if (!x86_apple_machine)
23528a2e487eSLukas Wunner 		return;
23538a2e487eSLukas Wunner 
23548a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
23558a2e487eSLukas Wunner 	    && obj->buffer.length >= 4)
23564c3c5954SArd Biesheuvel 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
23578a2e487eSLukas Wunner 
23588a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
23598a2e487eSLukas Wunner 	    && obj->buffer.length == 8)
23604c3c5954SArd Biesheuvel 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
23618a2e487eSLukas Wunner 
23628a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
23638a2e487eSLukas Wunner 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
23644c3c5954SArd Biesheuvel 		lookup->mode |= SPI_LSB_FIRST;
23658a2e487eSLukas Wunner 
23668a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
23678a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
23684c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPOL;
23698a2e487eSLukas Wunner 
23708a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
23718a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
23724c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPHA;
23738a2e487eSLukas Wunner }
23748a2e487eSLukas Wunner 
237587e59b36SStefan Binding static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
237687e59b36SStefan Binding 
237764bee4d2SMika Westerberg static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
237864bee4d2SMika Westerberg {
23794c3c5954SArd Biesheuvel 	struct acpi_spi_lookup *lookup = data;
23804c3c5954SArd Biesheuvel 	struct spi_controller *ctlr = lookup->ctlr;
238164bee4d2SMika Westerberg 
238264bee4d2SMika Westerberg 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
238364bee4d2SMika Westerberg 		struct acpi_resource_spi_serialbus *sb;
23844c3c5954SArd Biesheuvel 		acpi_handle parent_handle;
23854c3c5954SArd Biesheuvel 		acpi_status status;
238664bee4d2SMika Westerberg 
238764bee4d2SMika Westerberg 		sb = &ares->data.spi_serial_bus;
238864bee4d2SMika Westerberg 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
23894c3c5954SArd Biesheuvel 
239087e59b36SStefan Binding 			if (lookup->index != -1 && lookup->n++ != lookup->index)
239187e59b36SStefan Binding 				return 1;
239287e59b36SStefan Binding 
239387e59b36SStefan Binding 			if (lookup->index == -1 && !ctlr)
239487e59b36SStefan Binding 				return -ENODEV;
239587e59b36SStefan Binding 
23964c3c5954SArd Biesheuvel 			status = acpi_get_handle(NULL,
23974c3c5954SArd Biesheuvel 						 sb->resource_source.string_ptr,
23984c3c5954SArd Biesheuvel 						 &parent_handle);
23994c3c5954SArd Biesheuvel 
240087e59b36SStefan Binding 			if (ACPI_FAILURE(status))
24014c3c5954SArd Biesheuvel 				return -ENODEV;
24024c3c5954SArd Biesheuvel 
240387e59b36SStefan Binding 			if (ctlr) {
240487e59b36SStefan Binding 				if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
240587e59b36SStefan Binding 					return -ENODEV;
240687e59b36SStefan Binding 			} else {
240787e59b36SStefan Binding 				struct acpi_device *adev;
240887e59b36SStefan Binding 
2409*ac2a3feeSRafael J. Wysocki 				adev = acpi_fetch_acpi_dev(parent_handle);
2410*ac2a3feeSRafael J. Wysocki 				if (!adev)
241187e59b36SStefan Binding 					return -ENODEV;
241287e59b36SStefan Binding 
241387e59b36SStefan Binding 				ctlr = acpi_spi_find_controller_by_adev(adev);
241487e59b36SStefan Binding 				if (!ctlr)
241587e59b36SStefan Binding 					return -ENODEV;
241687e59b36SStefan Binding 
241787e59b36SStefan Binding 				lookup->ctlr = ctlr;
241887e59b36SStefan Binding 			}
241987e59b36SStefan Binding 
2420a0a90718SMika Westerberg 			/*
2421a0a90718SMika Westerberg 			 * ACPI DeviceSelection numbering is handled by the
2422a0a90718SMika Westerberg 			 * host controller driver in Windows and can vary
2423a0a90718SMika Westerberg 			 * from driver to driver. In Linux we always expect
2424a0a90718SMika Westerberg 			 * 0 .. max - 1 so we need to ask the driver to
2425a0a90718SMika Westerberg 			 * translate between the two schemes.
2426a0a90718SMika Westerberg 			 */
24278caab75fSGeert Uytterhoeven 			if (ctlr->fw_translate_cs) {
24288caab75fSGeert Uytterhoeven 				int cs = ctlr->fw_translate_cs(ctlr,
2429a0a90718SMika Westerberg 						sb->device_selection);
2430a0a90718SMika Westerberg 				if (cs < 0)
2431a0a90718SMika Westerberg 					return cs;
24324c3c5954SArd Biesheuvel 				lookup->chip_select = cs;
2433a0a90718SMika Westerberg 			} else {
24344c3c5954SArd Biesheuvel 				lookup->chip_select = sb->device_selection;
2435a0a90718SMika Westerberg 			}
2436a0a90718SMika Westerberg 
24374c3c5954SArd Biesheuvel 			lookup->max_speed_hz = sb->connection_speed;
24380dadde34SAndy Shevchenko 			lookup->bits_per_word = sb->data_bit_length;
243964bee4d2SMika Westerberg 
244064bee4d2SMika Westerberg 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
24414c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPHA;
244264bee4d2SMika Westerberg 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
24434c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPOL;
244464bee4d2SMika Westerberg 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
24454c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CS_HIGH;
244664bee4d2SMika Westerberg 		}
24474c3c5954SArd Biesheuvel 	} else if (lookup->irq < 0) {
244864bee4d2SMika Westerberg 		struct resource r;
244964bee4d2SMika Westerberg 
245064bee4d2SMika Westerberg 		if (acpi_dev_resource_interrupt(ares, 0, &r))
24514c3c5954SArd Biesheuvel 			lookup->irq = r.start;
245264bee4d2SMika Westerberg 	}
245364bee4d2SMika Westerberg 
245464bee4d2SMika Westerberg 	/* Always tell the ACPI core to skip this resource */
245564bee4d2SMika Westerberg 	return 1;
245664bee4d2SMika Westerberg }
245764bee4d2SMika Westerberg 
2458000bee0eSStefan Binding /**
2459000bee0eSStefan Binding  * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2460000bee0eSStefan Binding  * @ctlr: controller to which the spi device belongs
2461000bee0eSStefan Binding  * @adev: ACPI Device for the spi device
246287e59b36SStefan Binding  * @index: Index of the spi resource inside the ACPI Node
2463000bee0eSStefan Binding  *
2464000bee0eSStefan Binding  * This should be used to allocate a new spi device from and ACPI Node.
2465000bee0eSStefan Binding  * The caller is responsible for calling spi_add_device to register the spi device.
2466000bee0eSStefan Binding  *
246787e59b36SStefan Binding  * If ctlr is set to NULL, the Controller for the spi device will be looked up
246887e59b36SStefan Binding  * using the resource.
246987e59b36SStefan Binding  * If index is set to -1, index is not used.
247087e59b36SStefan Binding  * Note: If index is -1, ctlr must be set.
247187e59b36SStefan Binding  *
2472000bee0eSStefan Binding  * Return: a pointer to the new device, or ERR_PTR on error.
2473000bee0eSStefan Binding  */
2474000bee0eSStefan Binding struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
247587e59b36SStefan Binding 					 struct acpi_device *adev,
247687e59b36SStefan Binding 					 int index)
247764bee4d2SMika Westerberg {
24784c3c5954SArd Biesheuvel 	acpi_handle parent_handle = NULL;
247964bee4d2SMika Westerberg 	struct list_head resource_list;
2480b28944c6SArd Biesheuvel 	struct acpi_spi_lookup lookup = {};
248164bee4d2SMika Westerberg 	struct spi_device *spi;
248264bee4d2SMika Westerberg 	int ret;
248364bee4d2SMika Westerberg 
248487e59b36SStefan Binding 	if (!ctlr && index == -1)
248587e59b36SStefan Binding 		return ERR_PTR(-EINVAL);
248687e59b36SStefan Binding 
24874c3c5954SArd Biesheuvel 	lookup.ctlr		= ctlr;
24884c3c5954SArd Biesheuvel 	lookup.irq		= -1;
248987e59b36SStefan Binding 	lookup.index		= index;
249087e59b36SStefan Binding 	lookup.n		= 0;
24914c3c5954SArd Biesheuvel 
24924c3c5954SArd Biesheuvel 	INIT_LIST_HEAD(&resource_list);
24934c3c5954SArd Biesheuvel 	ret = acpi_dev_get_resources(adev, &resource_list,
24944c3c5954SArd Biesheuvel 				     acpi_spi_add_resource, &lookup);
24954c3c5954SArd Biesheuvel 	acpi_dev_free_resource_list(&resource_list);
24964c3c5954SArd Biesheuvel 
24974c3c5954SArd Biesheuvel 	if (ret < 0)
24984c3c5954SArd Biesheuvel 		/* found SPI in _CRS but it points to another controller */
2499000bee0eSStefan Binding 		return ERR_PTR(-ENODEV);
25004c3c5954SArd Biesheuvel 
25014c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz &&
250210e92724SBjorn Helgaas 	    ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
250387e59b36SStefan Binding 	    ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
25044c3c5954SArd Biesheuvel 		/* Apple does not use _CRS but nested devices for SPI slaves */
25054c3c5954SArd Biesheuvel 		acpi_spi_parse_apple_properties(adev, &lookup);
25064c3c5954SArd Biesheuvel 	}
25074c3c5954SArd Biesheuvel 
25084c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz)
2509000bee0eSStefan Binding 		return ERR_PTR(-ENODEV);
25104c3c5954SArd Biesheuvel 
251187e59b36SStefan Binding 	spi = spi_alloc_device(lookup.ctlr);
251264bee4d2SMika Westerberg 	if (!spi) {
251387e59b36SStefan Binding 		dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
251464bee4d2SMika Westerberg 			dev_name(&adev->dev));
2515000bee0eSStefan Binding 		return ERR_PTR(-ENOMEM);
251664bee4d2SMika Westerberg 	}
251764bee4d2SMika Westerberg 
25187b199811SRafael J. Wysocki 	ACPI_COMPANION_SET(&spi->dev, adev);
25194c3c5954SArd Biesheuvel 	spi->max_speed_hz	= lookup.max_speed_hz;
2520ea235786SJohn Garry 	spi->mode		|= lookup.mode;
25214c3c5954SArd Biesheuvel 	spi->irq		= lookup.irq;
25224c3c5954SArd Biesheuvel 	spi->bits_per_word	= lookup.bits_per_word;
25234c3c5954SArd Biesheuvel 	spi->chip_select	= lookup.chip_select;
252464bee4d2SMika Westerberg 
2525000bee0eSStefan Binding 	return spi;
2526000bee0eSStefan Binding }
2527000bee0eSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2528000bee0eSStefan Binding 
2529000bee0eSStefan Binding static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2530000bee0eSStefan Binding 					    struct acpi_device *adev)
2531000bee0eSStefan Binding {
2532000bee0eSStefan Binding 	struct spi_device *spi;
2533000bee0eSStefan Binding 
2534000bee0eSStefan Binding 	if (acpi_bus_get_status(adev) || !adev->status.present ||
2535000bee0eSStefan Binding 	    acpi_device_enumerated(adev))
2536000bee0eSStefan Binding 		return AE_OK;
2537000bee0eSStefan Binding 
253887e59b36SStefan Binding 	spi = acpi_spi_device_alloc(ctlr, adev, -1);
2539000bee0eSStefan Binding 	if (IS_ERR(spi)) {
2540000bee0eSStefan Binding 		if (PTR_ERR(spi) == -ENOMEM)
2541000bee0eSStefan Binding 			return AE_NO_MEMORY;
2542000bee0eSStefan Binding 		else
2543000bee0eSStefan Binding 			return AE_OK;
2544000bee0eSStefan Binding 	}
2545000bee0eSStefan Binding 
25460c6543f6SDan O'Donovan 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
25470c6543f6SDan O'Donovan 			  sizeof(spi->modalias));
25480c6543f6SDan O'Donovan 
254933ada67dSChristophe RICARD 	if (spi->irq < 0)
255033ada67dSChristophe RICARD 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
255133ada67dSChristophe RICARD 
25527f24467fSOctavian Purdila 	acpi_device_set_enumerated(adev);
25537f24467fSOctavian Purdila 
255433cf00e5SMika Westerberg 	adev->power.flags.ignore_parent = true;
255564bee4d2SMika Westerberg 	if (spi_add_device(spi)) {
255633cf00e5SMika Westerberg 		adev->power.flags.ignore_parent = false;
25578caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
255864bee4d2SMika Westerberg 			dev_name(&adev->dev));
255964bee4d2SMika Westerberg 		spi_dev_put(spi);
256064bee4d2SMika Westerberg 	}
256164bee4d2SMika Westerberg 
256264bee4d2SMika Westerberg 	return AE_OK;
256364bee4d2SMika Westerberg }
256464bee4d2SMika Westerberg 
25657f24467fSOctavian Purdila static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
25667f24467fSOctavian Purdila 				       void *data, void **return_value)
25677f24467fSOctavian Purdila {
25687030c428SRafael J. Wysocki 	struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
25698caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = data;
25707f24467fSOctavian Purdila 
25717030c428SRafael J. Wysocki 	if (!adev)
25727f24467fSOctavian Purdila 		return AE_OK;
25737f24467fSOctavian Purdila 
25748caab75fSGeert Uytterhoeven 	return acpi_register_spi_device(ctlr, adev);
25757f24467fSOctavian Purdila }
25767f24467fSOctavian Purdila 
25774c3c5954SArd Biesheuvel #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
25784c3c5954SArd Biesheuvel 
25798caab75fSGeert Uytterhoeven static void acpi_register_spi_devices(struct spi_controller *ctlr)
258064bee4d2SMika Westerberg {
258164bee4d2SMika Westerberg 	acpi_status status;
258264bee4d2SMika Westerberg 	acpi_handle handle;
258364bee4d2SMika Westerberg 
25848caab75fSGeert Uytterhoeven 	handle = ACPI_HANDLE(ctlr->dev.parent);
258564bee4d2SMika Westerberg 	if (!handle)
258664bee4d2SMika Westerberg 		return;
258764bee4d2SMika Westerberg 
25884c3c5954SArd Biesheuvel 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
25894c3c5954SArd Biesheuvel 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
25908caab75fSGeert Uytterhoeven 				     acpi_spi_add_device, NULL, ctlr, NULL);
259164bee4d2SMika Westerberg 	if (ACPI_FAILURE(status))
25928caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
259364bee4d2SMika Westerberg }
259464bee4d2SMika Westerberg #else
25958caab75fSGeert Uytterhoeven static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
259664bee4d2SMika Westerberg #endif /* CONFIG_ACPI */
259764bee4d2SMika Westerberg 
25988caab75fSGeert Uytterhoeven static void spi_controller_release(struct device *dev)
25998ae12a0dSDavid Brownell {
26008caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
26018ae12a0dSDavid Brownell 
26028caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
26038caab75fSGeert Uytterhoeven 	kfree(ctlr);
26048ae12a0dSDavid Brownell }
26058ae12a0dSDavid Brownell 
26068ae12a0dSDavid Brownell static struct class spi_master_class = {
26078ae12a0dSDavid Brownell 	.name		= "spi_master",
26088ae12a0dSDavid Brownell 	.owner		= THIS_MODULE,
26098caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
2610eca2ebc7SMartin Sperl 	.dev_groups	= spi_master_groups,
26118ae12a0dSDavid Brownell };
26128ae12a0dSDavid Brownell 
26136c364062SGeert Uytterhoeven #ifdef CONFIG_SPI_SLAVE
26146c364062SGeert Uytterhoeven /**
26156c364062SGeert Uytterhoeven  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
26166c364062SGeert Uytterhoeven  *		     controller
26176c364062SGeert Uytterhoeven  * @spi: device used for the current transfer
26186c364062SGeert Uytterhoeven  */
26196c364062SGeert Uytterhoeven int spi_slave_abort(struct spi_device *spi)
26206c364062SGeert Uytterhoeven {
26218caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
26226c364062SGeert Uytterhoeven 
26238caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
26248caab75fSGeert Uytterhoeven 		return ctlr->slave_abort(ctlr);
26256c364062SGeert Uytterhoeven 
26266c364062SGeert Uytterhoeven 	return -ENOTSUPP;
26276c364062SGeert Uytterhoeven }
26286c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_slave_abort);
26296c364062SGeert Uytterhoeven 
26306c364062SGeert Uytterhoeven static int match_true(struct device *dev, void *data)
26316c364062SGeert Uytterhoeven {
26326c364062SGeert Uytterhoeven 	return 1;
26336c364062SGeert Uytterhoeven }
26346c364062SGeert Uytterhoeven 
2635cc8b4659SGeert Uytterhoeven static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2636cc8b4659SGeert Uytterhoeven 			  char *buf)
26376c364062SGeert Uytterhoeven {
26388caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
26398caab75fSGeert Uytterhoeven 						   dev);
26406c364062SGeert Uytterhoeven 	struct device *child;
26416c364062SGeert Uytterhoeven 
26426c364062SGeert Uytterhoeven 	child = device_find_child(&ctlr->dev, NULL, match_true);
26436c364062SGeert Uytterhoeven 	return sprintf(buf, "%s\n",
26446c364062SGeert Uytterhoeven 		       child ? to_spi_device(child)->modalias : NULL);
26456c364062SGeert Uytterhoeven }
26466c364062SGeert Uytterhoeven 
2647cc8b4659SGeert Uytterhoeven static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2648cc8b4659SGeert Uytterhoeven 			   const char *buf, size_t count)
26496c364062SGeert Uytterhoeven {
26508caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
26518caab75fSGeert Uytterhoeven 						   dev);
26526c364062SGeert Uytterhoeven 	struct spi_device *spi;
26536c364062SGeert Uytterhoeven 	struct device *child;
26546c364062SGeert Uytterhoeven 	char name[32];
26556c364062SGeert Uytterhoeven 	int rc;
26566c364062SGeert Uytterhoeven 
26576c364062SGeert Uytterhoeven 	rc = sscanf(buf, "%31s", name);
26586c364062SGeert Uytterhoeven 	if (rc != 1 || !name[0])
26596c364062SGeert Uytterhoeven 		return -EINVAL;
26606c364062SGeert Uytterhoeven 
26616c364062SGeert Uytterhoeven 	child = device_find_child(&ctlr->dev, NULL, match_true);
26626c364062SGeert Uytterhoeven 	if (child) {
26636c364062SGeert Uytterhoeven 		/* Remove registered slave */
26646c364062SGeert Uytterhoeven 		device_unregister(child);
26656c364062SGeert Uytterhoeven 		put_device(child);
26666c364062SGeert Uytterhoeven 	}
26676c364062SGeert Uytterhoeven 
26686c364062SGeert Uytterhoeven 	if (strcmp(name, "(null)")) {
26696c364062SGeert Uytterhoeven 		/* Register new slave */
26706c364062SGeert Uytterhoeven 		spi = spi_alloc_device(ctlr);
26716c364062SGeert Uytterhoeven 		if (!spi)
26726c364062SGeert Uytterhoeven 			return -ENOMEM;
26736c364062SGeert Uytterhoeven 
26746c364062SGeert Uytterhoeven 		strlcpy(spi->modalias, name, sizeof(spi->modalias));
26756c364062SGeert Uytterhoeven 
26766c364062SGeert Uytterhoeven 		rc = spi_add_device(spi);
26776c364062SGeert Uytterhoeven 		if (rc) {
26786c364062SGeert Uytterhoeven 			spi_dev_put(spi);
26796c364062SGeert Uytterhoeven 			return rc;
26806c364062SGeert Uytterhoeven 		}
26816c364062SGeert Uytterhoeven 	}
26826c364062SGeert Uytterhoeven 
26836c364062SGeert Uytterhoeven 	return count;
26846c364062SGeert Uytterhoeven }
26856c364062SGeert Uytterhoeven 
2686cc8b4659SGeert Uytterhoeven static DEVICE_ATTR_RW(slave);
26876c364062SGeert Uytterhoeven 
26886c364062SGeert Uytterhoeven static struct attribute *spi_slave_attrs[] = {
26896c364062SGeert Uytterhoeven 	&dev_attr_slave.attr,
26906c364062SGeert Uytterhoeven 	NULL,
26916c364062SGeert Uytterhoeven };
26926c364062SGeert Uytterhoeven 
26936c364062SGeert Uytterhoeven static const struct attribute_group spi_slave_group = {
26946c364062SGeert Uytterhoeven 	.attrs = spi_slave_attrs,
26956c364062SGeert Uytterhoeven };
26966c364062SGeert Uytterhoeven 
26976c364062SGeert Uytterhoeven static const struct attribute_group *spi_slave_groups[] = {
26988caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
26996c364062SGeert Uytterhoeven 	&spi_slave_group,
27006c364062SGeert Uytterhoeven 	NULL,
27016c364062SGeert Uytterhoeven };
27026c364062SGeert Uytterhoeven 
27036c364062SGeert Uytterhoeven static struct class spi_slave_class = {
27046c364062SGeert Uytterhoeven 	.name		= "spi_slave",
27056c364062SGeert Uytterhoeven 	.owner		= THIS_MODULE,
27068caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
27076c364062SGeert Uytterhoeven 	.dev_groups	= spi_slave_groups,
27086c364062SGeert Uytterhoeven };
27096c364062SGeert Uytterhoeven #else
27106c364062SGeert Uytterhoeven extern struct class spi_slave_class;	/* dummy */
27116c364062SGeert Uytterhoeven #endif
27128ae12a0dSDavid Brownell 
27138ae12a0dSDavid Brownell /**
27146c364062SGeert Uytterhoeven  * __spi_alloc_controller - allocate an SPI master or slave controller
27158ae12a0dSDavid Brownell  * @dev: the controller, possibly using the platform_bus
271633e34dc6SDavid Brownell  * @size: how much zeroed driver-private data to allocate; the pointer to this
2717229e6af1SLukas Wunner  *	memory is in the driver_data field of the returned device, accessible
2718229e6af1SLukas Wunner  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2719229e6af1SLukas Wunner  *	drivers granting DMA access to portions of their private data need to
2720229e6af1SLukas Wunner  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
27216c364062SGeert Uytterhoeven  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
27226c364062SGeert Uytterhoeven  *	slave (true) controller
272333e34dc6SDavid Brownell  * Context: can sleep
27248ae12a0dSDavid Brownell  *
27256c364062SGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
27268ae12a0dSDavid Brownell  * only ones directly touching chip registers.  It's how they allocate
27278caab75fSGeert Uytterhoeven  * an spi_controller structure, prior to calling spi_register_controller().
27288ae12a0dSDavid Brownell  *
272997d56dc6SJavier Martinez Canillas  * This must be called from context that can sleep.
27308ae12a0dSDavid Brownell  *
27316c364062SGeert Uytterhoeven  * The caller is responsible for assigning the bus number and initializing the
27328caab75fSGeert Uytterhoeven  * controller's methods before calling spi_register_controller(); and (after
27338caab75fSGeert Uytterhoeven  * errors adding the device) calling spi_controller_put() to prevent a memory
27348caab75fSGeert Uytterhoeven  * leak.
273597d56dc6SJavier Martinez Canillas  *
27366c364062SGeert Uytterhoeven  * Return: the SPI controller structure on success, else NULL.
27378ae12a0dSDavid Brownell  */
27388caab75fSGeert Uytterhoeven struct spi_controller *__spi_alloc_controller(struct device *dev,
27396c364062SGeert Uytterhoeven 					      unsigned int size, bool slave)
27408ae12a0dSDavid Brownell {
27418caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr;
2742229e6af1SLukas Wunner 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
27438ae12a0dSDavid Brownell 
27440c868461SDavid Brownell 	if (!dev)
27450c868461SDavid Brownell 		return NULL;
27460c868461SDavid Brownell 
2747229e6af1SLukas Wunner 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
27488caab75fSGeert Uytterhoeven 	if (!ctlr)
27498ae12a0dSDavid Brownell 		return NULL;
27508ae12a0dSDavid Brownell 
27518caab75fSGeert Uytterhoeven 	device_initialize(&ctlr->dev);
275216a8e2fbSUwe Kleine-König 	INIT_LIST_HEAD(&ctlr->queue);
275316a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->queue_lock);
275416a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->bus_lock_spinlock);
275516a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->bus_lock_mutex);
275616a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->io_mutex);
275716a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->add_lock);
27588caab75fSGeert Uytterhoeven 	ctlr->bus_num = -1;
27598caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = 1;
27608caab75fSGeert Uytterhoeven 	ctlr->slave = slave;
27616c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
27628caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_slave_class;
27636c364062SGeert Uytterhoeven 	else
27648caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_master_class;
27658caab75fSGeert Uytterhoeven 	ctlr->dev.parent = dev;
27668caab75fSGeert Uytterhoeven 	pm_suspend_ignore_children(&ctlr->dev, true);
2767229e6af1SLukas Wunner 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
27688ae12a0dSDavid Brownell 
27698caab75fSGeert Uytterhoeven 	return ctlr;
27708ae12a0dSDavid Brownell }
27716c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(__spi_alloc_controller);
27728ae12a0dSDavid Brownell 
27735e844cc3SLukas Wunner static void devm_spi_release_controller(struct device *dev, void *ctlr)
27745e844cc3SLukas Wunner {
27755e844cc3SLukas Wunner 	spi_controller_put(*(struct spi_controller **)ctlr);
27765e844cc3SLukas Wunner }
27775e844cc3SLukas Wunner 
27785e844cc3SLukas Wunner /**
27795e844cc3SLukas Wunner  * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
27805e844cc3SLukas Wunner  * @dev: physical device of SPI controller
27815e844cc3SLukas Wunner  * @size: how much zeroed driver-private data to allocate
27825e844cc3SLukas Wunner  * @slave: whether to allocate an SPI master (false) or SPI slave (true)
27835e844cc3SLukas Wunner  * Context: can sleep
27845e844cc3SLukas Wunner  *
27855e844cc3SLukas Wunner  * Allocate an SPI controller and automatically release a reference on it
27865e844cc3SLukas Wunner  * when @dev is unbound from its driver.  Drivers are thus relieved from
27875e844cc3SLukas Wunner  * having to call spi_controller_put().
27885e844cc3SLukas Wunner  *
27895e844cc3SLukas Wunner  * The arguments to this function are identical to __spi_alloc_controller().
27905e844cc3SLukas Wunner  *
27915e844cc3SLukas Wunner  * Return: the SPI controller structure on success, else NULL.
27925e844cc3SLukas Wunner  */
27935e844cc3SLukas Wunner struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
27945e844cc3SLukas Wunner 						   unsigned int size,
27955e844cc3SLukas Wunner 						   bool slave)
27965e844cc3SLukas Wunner {
27975e844cc3SLukas Wunner 	struct spi_controller **ptr, *ctlr;
27985e844cc3SLukas Wunner 
27995e844cc3SLukas Wunner 	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
28005e844cc3SLukas Wunner 			   GFP_KERNEL);
28015e844cc3SLukas Wunner 	if (!ptr)
28025e844cc3SLukas Wunner 		return NULL;
28035e844cc3SLukas Wunner 
28045e844cc3SLukas Wunner 	ctlr = __spi_alloc_controller(dev, size, slave);
28055e844cc3SLukas Wunner 	if (ctlr) {
2806794aaf01SWilliam A. Kennington III 		ctlr->devm_allocated = true;
28075e844cc3SLukas Wunner 		*ptr = ctlr;
28085e844cc3SLukas Wunner 		devres_add(dev, ptr);
28095e844cc3SLukas Wunner 	} else {
28105e844cc3SLukas Wunner 		devres_free(ptr);
28115e844cc3SLukas Wunner 	}
28125e844cc3SLukas Wunner 
28135e844cc3SLukas Wunner 	return ctlr;
28145e844cc3SLukas Wunner }
28155e844cc3SLukas Wunner EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
28165e844cc3SLukas Wunner 
2817f3186dd8SLinus Walleij /**
2818f3186dd8SLinus Walleij  * spi_get_gpio_descs() - grab chip select GPIOs for the master
2819f3186dd8SLinus Walleij  * @ctlr: The SPI master to grab GPIO descriptors for
2820f3186dd8SLinus Walleij  */
2821f3186dd8SLinus Walleij static int spi_get_gpio_descs(struct spi_controller *ctlr)
2822f3186dd8SLinus Walleij {
2823f3186dd8SLinus Walleij 	int nb, i;
2824f3186dd8SLinus Walleij 	struct gpio_desc **cs;
2825f3186dd8SLinus Walleij 	struct device *dev = &ctlr->dev;
28267d93aecdSGeert Uytterhoeven 	unsigned long native_cs_mask = 0;
28277d93aecdSGeert Uytterhoeven 	unsigned int num_cs_gpios = 0;
2828f3186dd8SLinus Walleij 
2829f3186dd8SLinus Walleij 	nb = gpiod_count(dev, "cs");
283031ed8ebcSAndy Shevchenko 	if (nb < 0) {
2831f3186dd8SLinus Walleij 		/* No GPIOs at all is fine, else return the error */
283231ed8ebcSAndy Shevchenko 		if (nb == -ENOENT)
2833f3186dd8SLinus Walleij 			return 0;
2834f3186dd8SLinus Walleij 		return nb;
283531ed8ebcSAndy Shevchenko 	}
283631ed8ebcSAndy Shevchenko 
283731ed8ebcSAndy Shevchenko 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2838f3186dd8SLinus Walleij 
2839f3186dd8SLinus Walleij 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2840f3186dd8SLinus Walleij 			  GFP_KERNEL);
2841f3186dd8SLinus Walleij 	if (!cs)
2842f3186dd8SLinus Walleij 		return -ENOMEM;
2843f3186dd8SLinus Walleij 	ctlr->cs_gpiods = cs;
2844f3186dd8SLinus Walleij 
2845f3186dd8SLinus Walleij 	for (i = 0; i < nb; i++) {
2846f3186dd8SLinus Walleij 		/*
2847f3186dd8SLinus Walleij 		 * Most chipselects are active low, the inverted
2848f3186dd8SLinus Walleij 		 * semantics are handled by special quirks in gpiolib,
2849f3186dd8SLinus Walleij 		 * so initializing them GPIOD_OUT_LOW here means
2850f3186dd8SLinus Walleij 		 * "unasserted", in most cases this will drive the physical
2851f3186dd8SLinus Walleij 		 * line high.
2852f3186dd8SLinus Walleij 		 */
2853f3186dd8SLinus Walleij 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2854f3186dd8SLinus Walleij 						      GPIOD_OUT_LOW);
28551723fdecSGeert Uytterhoeven 		if (IS_ERR(cs[i]))
28561723fdecSGeert Uytterhoeven 			return PTR_ERR(cs[i]);
2857f3186dd8SLinus Walleij 
2858f3186dd8SLinus Walleij 		if (cs[i]) {
2859f3186dd8SLinus Walleij 			/*
2860f3186dd8SLinus Walleij 			 * If we find a CS GPIO, name it after the device and
2861f3186dd8SLinus Walleij 			 * chip select line.
2862f3186dd8SLinus Walleij 			 */
2863f3186dd8SLinus Walleij 			char *gpioname;
2864f3186dd8SLinus Walleij 
2865f3186dd8SLinus Walleij 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2866f3186dd8SLinus Walleij 						  dev_name(dev), i);
2867f3186dd8SLinus Walleij 			if (!gpioname)
2868f3186dd8SLinus Walleij 				return -ENOMEM;
2869f3186dd8SLinus Walleij 			gpiod_set_consumer_name(cs[i], gpioname);
28707d93aecdSGeert Uytterhoeven 			num_cs_gpios++;
28717d93aecdSGeert Uytterhoeven 			continue;
2872f3186dd8SLinus Walleij 		}
28737d93aecdSGeert Uytterhoeven 
28747d93aecdSGeert Uytterhoeven 		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
28757d93aecdSGeert Uytterhoeven 			dev_err(dev, "Invalid native chip select %d\n", i);
28767d93aecdSGeert Uytterhoeven 			return -EINVAL;
28777d93aecdSGeert Uytterhoeven 		}
28787d93aecdSGeert Uytterhoeven 		native_cs_mask |= BIT(i);
28797d93aecdSGeert Uytterhoeven 	}
28807d93aecdSGeert Uytterhoeven 
2881f60d7270SAndy Shevchenko 	ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2882dbaca8e5SAndy Shevchenko 
2883dbaca8e5SAndy Shevchenko 	if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2884dbaca8e5SAndy Shevchenko 	    ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
28857d93aecdSGeert Uytterhoeven 		dev_err(dev, "No unused native chip select available\n");
28867d93aecdSGeert Uytterhoeven 		return -EINVAL;
2887f3186dd8SLinus Walleij 	}
2888f3186dd8SLinus Walleij 
2889f3186dd8SLinus Walleij 	return 0;
2890f3186dd8SLinus Walleij }
2891f3186dd8SLinus Walleij 
2892bdf3a3b5SBoris Brezillon static int spi_controller_check_ops(struct spi_controller *ctlr)
2893bdf3a3b5SBoris Brezillon {
2894bdf3a3b5SBoris Brezillon 	/*
2895b5932f5cSBoris Brezillon 	 * The controller may implement only the high-level SPI-memory like
2896b5932f5cSBoris Brezillon 	 * operations if it does not support regular SPI transfers, and this is
2897b5932f5cSBoris Brezillon 	 * valid use case.
2898b5932f5cSBoris Brezillon 	 * If ->mem_ops is NULL, we request that at least one of the
2899b5932f5cSBoris Brezillon 	 * ->transfer_xxx() method be implemented.
2900bdf3a3b5SBoris Brezillon 	 */
2901b5932f5cSBoris Brezillon 	if (ctlr->mem_ops) {
2902b5932f5cSBoris Brezillon 		if (!ctlr->mem_ops->exec_op)
2903bdf3a3b5SBoris Brezillon 			return -EINVAL;
2904b5932f5cSBoris Brezillon 	} else if (!ctlr->transfer && !ctlr->transfer_one &&
2905b5932f5cSBoris Brezillon 		   !ctlr->transfer_one_message) {
2906b5932f5cSBoris Brezillon 		return -EINVAL;
2907b5932f5cSBoris Brezillon 	}
2908bdf3a3b5SBoris Brezillon 
2909bdf3a3b5SBoris Brezillon 	return 0;
2910bdf3a3b5SBoris Brezillon }
2911bdf3a3b5SBoris Brezillon 
29128ae12a0dSDavid Brownell /**
29138caab75fSGeert Uytterhoeven  * spi_register_controller - register SPI master or slave controller
29148caab75fSGeert Uytterhoeven  * @ctlr: initialized master, originally from spi_alloc_master() or
29158caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
291633e34dc6SDavid Brownell  * Context: can sleep
29178ae12a0dSDavid Brownell  *
29188caab75fSGeert Uytterhoeven  * SPI controllers connect to their drivers using some non-SPI bus,
29198ae12a0dSDavid Brownell  * such as the platform bus.  The final stage of probe() in that code
29208caab75fSGeert Uytterhoeven  * includes calling spi_register_controller() to hook up to this SPI bus glue.
29218ae12a0dSDavid Brownell  *
29228ae12a0dSDavid Brownell  * SPI controllers use board specific (often SOC specific) bus numbers,
29238ae12a0dSDavid Brownell  * and board-specific addressing for SPI devices combines those numbers
29248ae12a0dSDavid Brownell  * with chip select numbers.  Since SPI does not directly support dynamic
29258ae12a0dSDavid Brownell  * device identification, boards need configuration tables telling which
29268ae12a0dSDavid Brownell  * chip is at which address.
29278ae12a0dSDavid Brownell  *
29288ae12a0dSDavid Brownell  * This must be called from context that can sleep.  It returns zero on
29298caab75fSGeert Uytterhoeven  * success, else a negative error code (dropping the controller's refcount).
29300c868461SDavid Brownell  * After a successful return, the caller is responsible for calling
29318caab75fSGeert Uytterhoeven  * spi_unregister_controller().
293297d56dc6SJavier Martinez Canillas  *
293397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
29348ae12a0dSDavid Brownell  */
29358caab75fSGeert Uytterhoeven int spi_register_controller(struct spi_controller *ctlr)
29368ae12a0dSDavid Brownell {
29378caab75fSGeert Uytterhoeven 	struct device		*dev = ctlr->dev.parent;
29382b9603a0SFeng Tang 	struct boardinfo	*bi;
2939b93318a2SSergei Shtylyov 	int			status;
294042bdd706SLucas Stach 	int			id, first_dynamic;
29418ae12a0dSDavid Brownell 
29420c868461SDavid Brownell 	if (!dev)
29430c868461SDavid Brownell 		return -ENODEV;
29440c868461SDavid Brownell 
2945bdf3a3b5SBoris Brezillon 	/*
2946bdf3a3b5SBoris Brezillon 	 * Make sure all necessary hooks are implemented before registering
2947bdf3a3b5SBoris Brezillon 	 * the SPI controller.
2948bdf3a3b5SBoris Brezillon 	 */
2949bdf3a3b5SBoris Brezillon 	status = spi_controller_check_ops(ctlr);
2950bdf3a3b5SBoris Brezillon 	if (status)
2951bdf3a3b5SBoris Brezillon 		return status;
2952bdf3a3b5SBoris Brezillon 
295304b2d03aSGeert Uytterhoeven 	if (ctlr->bus_num >= 0) {
295404b2d03aSGeert Uytterhoeven 		/* devices with a fixed bus num must check-in with the num */
295504b2d03aSGeert Uytterhoeven 		mutex_lock(&board_lock);
295604b2d03aSGeert Uytterhoeven 		id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
295704b2d03aSGeert Uytterhoeven 			ctlr->bus_num + 1, GFP_KERNEL);
295804b2d03aSGeert Uytterhoeven 		mutex_unlock(&board_lock);
295904b2d03aSGeert Uytterhoeven 		if (WARN(id < 0, "couldn't get idr"))
296004b2d03aSGeert Uytterhoeven 			return id == -ENOSPC ? -EBUSY : id;
296104b2d03aSGeert Uytterhoeven 		ctlr->bus_num = id;
296204b2d03aSGeert Uytterhoeven 	} else if (ctlr->dev.of_node) {
29639b61e302SSuniel Mahesh 		/* allocate dynamic bus number using Linux idr */
29649b61e302SSuniel Mahesh 		id = of_alias_get_id(ctlr->dev.of_node, "spi");
29659b61e302SSuniel Mahesh 		if (id >= 0) {
29669b61e302SSuniel Mahesh 			ctlr->bus_num = id;
29679b61e302SSuniel Mahesh 			mutex_lock(&board_lock);
29689b61e302SSuniel Mahesh 			id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
29699b61e302SSuniel Mahesh 				       ctlr->bus_num + 1, GFP_KERNEL);
29709b61e302SSuniel Mahesh 			mutex_unlock(&board_lock);
29719b61e302SSuniel Mahesh 			if (WARN(id < 0, "couldn't get idr"))
29729b61e302SSuniel Mahesh 				return id == -ENOSPC ? -EBUSY : id;
29739b61e302SSuniel Mahesh 		}
29749b61e302SSuniel Mahesh 	}
29758caab75fSGeert Uytterhoeven 	if (ctlr->bus_num < 0) {
297642bdd706SLucas Stach 		first_dynamic = of_alias_get_highest_id("spi");
297742bdd706SLucas Stach 		if (first_dynamic < 0)
297842bdd706SLucas Stach 			first_dynamic = 0;
297942bdd706SLucas Stach 		else
298042bdd706SLucas Stach 			first_dynamic++;
298142bdd706SLucas Stach 
29829b61e302SSuniel Mahesh 		mutex_lock(&board_lock);
298342bdd706SLucas Stach 		id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
298442bdd706SLucas Stach 			       0, GFP_KERNEL);
29859b61e302SSuniel Mahesh 		mutex_unlock(&board_lock);
29869b61e302SSuniel Mahesh 		if (WARN(id < 0, "couldn't get idr"))
29879b61e302SSuniel Mahesh 			return id;
29889b61e302SSuniel Mahesh 		ctlr->bus_num = id;
29898ae12a0dSDavid Brownell 	}
29908caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
29918caab75fSGeert Uytterhoeven 	init_completion(&ctlr->xfer_completion);
29928caab75fSGeert Uytterhoeven 	if (!ctlr->max_dma_len)
29938caab75fSGeert Uytterhoeven 		ctlr->max_dma_len = INT_MAX;
2994cf32b71eSErnst Schwab 
2995350de7ceSAndy Shevchenko 	/*
2996350de7ceSAndy Shevchenko 	 * Register the device, then userspace will see it.
2997350de7ceSAndy Shevchenko 	 * Registration fails if the bus ID is in use.
29988ae12a0dSDavid Brownell 	 */
29998caab75fSGeert Uytterhoeven 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
30000a919ae4SAndrey Smirnov 
3001f48dc6b9SLinus Walleij 	if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
30020a919ae4SAndrey Smirnov 		status = spi_get_gpio_descs(ctlr);
30030a919ae4SAndrey Smirnov 		if (status)
3004f9981d4fSAaro Koskinen 			goto free_bus_id;
30050a919ae4SAndrey Smirnov 		/*
30060a919ae4SAndrey Smirnov 		 * A controller using GPIO descriptors always
30070a919ae4SAndrey Smirnov 		 * supports SPI_CS_HIGH if need be.
30080a919ae4SAndrey Smirnov 		 */
30090a919ae4SAndrey Smirnov 		ctlr->mode_bits |= SPI_CS_HIGH;
30100a919ae4SAndrey Smirnov 	}
30110a919ae4SAndrey Smirnov 
3012f9481b08STudor Ambarus 	/*
3013f9481b08STudor Ambarus 	 * Even if it's just one always-selected device, there must
3014f9481b08STudor Ambarus 	 * be at least one chipselect.
3015f9481b08STudor Ambarus 	 */
3016f9981d4fSAaro Koskinen 	if (!ctlr->num_chipselect) {
3017f9981d4fSAaro Koskinen 		status = -EINVAL;
3018f9981d4fSAaro Koskinen 		goto free_bus_id;
3019f9981d4fSAaro Koskinen 	}
3020f9481b08STudor Ambarus 
30216bb477dfSYun Zhou 	/* setting last_cs to -1 means no chip selected */
30226bb477dfSYun Zhou 	ctlr->last_cs = -1;
30236bb477dfSYun Zhou 
30248caab75fSGeert Uytterhoeven 	status = device_add(&ctlr->dev);
3025f9981d4fSAaro Koskinen 	if (status < 0)
3026f9981d4fSAaro Koskinen 		goto free_bus_id;
30279b61e302SSuniel Mahesh 	dev_dbg(dev, "registered %s %s\n",
30288caab75fSGeert Uytterhoeven 			spi_controller_is_slave(ctlr) ? "slave" : "master",
30299b61e302SSuniel Mahesh 			dev_name(&ctlr->dev));
30308ae12a0dSDavid Brownell 
3031b5932f5cSBoris Brezillon 	/*
3032b5932f5cSBoris Brezillon 	 * If we're using a queued driver, start the queue. Note that we don't
3033b5932f5cSBoris Brezillon 	 * need the queueing logic if the driver is only supporting high-level
3034b5932f5cSBoris Brezillon 	 * memory operations.
3035b5932f5cSBoris Brezillon 	 */
3036b5932f5cSBoris Brezillon 	if (ctlr->transfer) {
30378caab75fSGeert Uytterhoeven 		dev_info(dev, "controller is unqueued, this is deprecated\n");
3038b5932f5cSBoris Brezillon 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
30398caab75fSGeert Uytterhoeven 		status = spi_controller_initialize_queue(ctlr);
3040ffbbdd21SLinus Walleij 		if (status) {
30418caab75fSGeert Uytterhoeven 			device_del(&ctlr->dev);
3042f9981d4fSAaro Koskinen 			goto free_bus_id;
3043ffbbdd21SLinus Walleij 		}
3044ffbbdd21SLinus Walleij 	}
3045eca2ebc7SMartin Sperl 	/* add statistics */
30468caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->statistics.lock);
3047ffbbdd21SLinus Walleij 
30482b9603a0SFeng Tang 	mutex_lock(&board_lock);
30498caab75fSGeert Uytterhoeven 	list_add_tail(&ctlr->list, &spi_controller_list);
30502b9603a0SFeng Tang 	list_for_each_entry(bi, &board_list, list)
30518caab75fSGeert Uytterhoeven 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
30522b9603a0SFeng Tang 	mutex_unlock(&board_lock);
30532b9603a0SFeng Tang 
305464bee4d2SMika Westerberg 	/* Register devices from the device tree and ACPI */
30558caab75fSGeert Uytterhoeven 	of_register_spi_devices(ctlr);
30568caab75fSGeert Uytterhoeven 	acpi_register_spi_devices(ctlr);
3057f9981d4fSAaro Koskinen 	return status;
3058f9981d4fSAaro Koskinen 
3059f9981d4fSAaro Koskinen free_bus_id:
3060f9981d4fSAaro Koskinen 	mutex_lock(&board_lock);
3061f9981d4fSAaro Koskinen 	idr_remove(&spi_master_idr, ctlr->bus_num);
3062f9981d4fSAaro Koskinen 	mutex_unlock(&board_lock);
30638ae12a0dSDavid Brownell 	return status;
30648ae12a0dSDavid Brownell }
30658caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_register_controller);
30668ae12a0dSDavid Brownell 
306759ebbe40STian Tao static void devm_spi_unregister(void *ctlr)
3068666d5b4cSMark Brown {
306959ebbe40STian Tao 	spi_unregister_controller(ctlr);
3070666d5b4cSMark Brown }
3071666d5b4cSMark Brown 
3072666d5b4cSMark Brown /**
30738caab75fSGeert Uytterhoeven  * devm_spi_register_controller - register managed SPI master or slave
30748caab75fSGeert Uytterhoeven  *	controller
30758caab75fSGeert Uytterhoeven  * @dev:    device managing SPI controller
30768caab75fSGeert Uytterhoeven  * @ctlr: initialized controller, originally from spi_alloc_master() or
30778caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
3078666d5b4cSMark Brown  * Context: can sleep
3079666d5b4cSMark Brown  *
30808caab75fSGeert Uytterhoeven  * Register a SPI device as with spi_register_controller() which will
308168b892f1SJohan Hovold  * automatically be unregistered and freed.
308297d56dc6SJavier Martinez Canillas  *
308397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3084666d5b4cSMark Brown  */
30858caab75fSGeert Uytterhoeven int devm_spi_register_controller(struct device *dev,
30868caab75fSGeert Uytterhoeven 				 struct spi_controller *ctlr)
3087666d5b4cSMark Brown {
3088666d5b4cSMark Brown 	int ret;
3089666d5b4cSMark Brown 
30908caab75fSGeert Uytterhoeven 	ret = spi_register_controller(ctlr);
309159ebbe40STian Tao 	if (ret)
3092666d5b4cSMark Brown 		return ret;
309359ebbe40STian Tao 
309459ebbe40STian Tao 	return devm_add_action_or_reset(dev, devm_spi_unregister, ctlr);
3095666d5b4cSMark Brown }
30968caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3097666d5b4cSMark Brown 
309834860089SDavid Lamparter static int __unregister(struct device *dev, void *null)
30998ae12a0dSDavid Brownell {
31000c868461SDavid Brownell 	spi_unregister_device(to_spi_device(dev));
31018ae12a0dSDavid Brownell 	return 0;
31028ae12a0dSDavid Brownell }
31038ae12a0dSDavid Brownell 
31048ae12a0dSDavid Brownell /**
31058caab75fSGeert Uytterhoeven  * spi_unregister_controller - unregister SPI master or slave controller
31068caab75fSGeert Uytterhoeven  * @ctlr: the controller being unregistered
310733e34dc6SDavid Brownell  * Context: can sleep
31088ae12a0dSDavid Brownell  *
31098caab75fSGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
31108ae12a0dSDavid Brownell  * only ones directly touching chip registers.
31118ae12a0dSDavid Brownell  *
31128ae12a0dSDavid Brownell  * This must be called from context that can sleep.
311368b892f1SJohan Hovold  *
311468b892f1SJohan Hovold  * Note that this function also drops a reference to the controller.
31158ae12a0dSDavid Brownell  */
31168caab75fSGeert Uytterhoeven void spi_unregister_controller(struct spi_controller *ctlr)
31178ae12a0dSDavid Brownell {
31189b61e302SSuniel Mahesh 	struct spi_controller *found;
311967f7b278SJohan Hovold 	int id = ctlr->bus_num;
312089fc9a1aSJeff Garzik 
3121ddf75be4SLukas Wunner 	/* Prevent addition of new devices, unregister existing ones */
3122ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
31236098475dSMark Brown 		mutex_lock(&ctlr->add_lock);
3124ddf75be4SLukas Wunner 
312584855678SLukas Wunner 	device_for_each_child(&ctlr->dev, NULL, __unregister);
312684855678SLukas Wunner 
31279b61e302SSuniel Mahesh 	/* First make sure that this controller was ever added */
31289b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
312967f7b278SJohan Hovold 	found = idr_find(&spi_master_idr, id);
31309b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
31318caab75fSGeert Uytterhoeven 	if (ctlr->queued) {
31328caab75fSGeert Uytterhoeven 		if (spi_destroy_queue(ctlr))
31338caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue remove failed\n");
3134ffbbdd21SLinus Walleij 	}
31352b9603a0SFeng Tang 	mutex_lock(&board_lock);
31368caab75fSGeert Uytterhoeven 	list_del(&ctlr->list);
31372b9603a0SFeng Tang 	mutex_unlock(&board_lock);
31382b9603a0SFeng Tang 
31395e844cc3SLukas Wunner 	device_del(&ctlr->dev);
31405e844cc3SLukas Wunner 
31419b61e302SSuniel Mahesh 	/* free bus id */
31429b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
3143613bd1eaSJarkko Nikula 	if (found == ctlr)
314467f7b278SJohan Hovold 		idr_remove(&spi_master_idr, id);
31459b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
3146ddf75be4SLukas Wunner 
3147ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
31486098475dSMark Brown 		mutex_unlock(&ctlr->add_lock);
31496c53b45cSMichael Walle 
31506c53b45cSMichael Walle 	/* Release the last reference on the controller if its driver
31516c53b45cSMichael Walle 	 * has not yet been converted to devm_spi_alloc_master/slave().
31526c53b45cSMichael Walle 	 */
31536c53b45cSMichael Walle 	if (!ctlr->devm_allocated)
31546c53b45cSMichael Walle 		put_device(&ctlr->dev);
31558ae12a0dSDavid Brownell }
31568caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_controller);
31578ae12a0dSDavid Brownell 
31588caab75fSGeert Uytterhoeven int spi_controller_suspend(struct spi_controller *ctlr)
3159ffbbdd21SLinus Walleij {
3160ffbbdd21SLinus Walleij 	int ret;
3161ffbbdd21SLinus Walleij 
31628caab75fSGeert Uytterhoeven 	/* Basically no-ops for non-queued controllers */
31638caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
3164ffbbdd21SLinus Walleij 		return 0;
3165ffbbdd21SLinus Walleij 
31668caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
3167ffbbdd21SLinus Walleij 	if (ret)
31688caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue stop failed\n");
3169ffbbdd21SLinus Walleij 
3170ffbbdd21SLinus Walleij 	return ret;
3171ffbbdd21SLinus Walleij }
31728caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_suspend);
3173ffbbdd21SLinus Walleij 
31748caab75fSGeert Uytterhoeven int spi_controller_resume(struct spi_controller *ctlr)
3175ffbbdd21SLinus Walleij {
3176ffbbdd21SLinus Walleij 	int ret;
3177ffbbdd21SLinus Walleij 
31788caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
3179ffbbdd21SLinus Walleij 		return 0;
3180ffbbdd21SLinus Walleij 
31818caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
3182ffbbdd21SLinus Walleij 	if (ret)
31838caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue restart failed\n");
3184ffbbdd21SLinus Walleij 
3185ffbbdd21SLinus Walleij 	return ret;
3186ffbbdd21SLinus Walleij }
31878caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_resume);
3188ffbbdd21SLinus Walleij 
31898ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
31908ae12a0dSDavid Brownell 
3191523baf5aSMartin Sperl /* Core methods for spi_message alterations */
3192523baf5aSMartin Sperl 
31938caab75fSGeert Uytterhoeven static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3194523baf5aSMartin Sperl 					    struct spi_message *msg,
3195523baf5aSMartin Sperl 					    void *res)
3196523baf5aSMartin Sperl {
3197523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer = res;
3198523baf5aSMartin Sperl 	size_t i;
3199523baf5aSMartin Sperl 
3200523baf5aSMartin Sperl 	/* call extra callback if requested */
3201523baf5aSMartin Sperl 	if (rxfer->release)
32028caab75fSGeert Uytterhoeven 		rxfer->release(ctlr, msg, res);
3203523baf5aSMartin Sperl 
3204523baf5aSMartin Sperl 	/* insert replaced transfers back into the message */
3205523baf5aSMartin Sperl 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3206523baf5aSMartin Sperl 
3207523baf5aSMartin Sperl 	/* remove the formerly inserted entries */
3208523baf5aSMartin Sperl 	for (i = 0; i < rxfer->inserted; i++)
3209523baf5aSMartin Sperl 		list_del(&rxfer->inserted_transfers[i].transfer_list);
3210523baf5aSMartin Sperl }
3211523baf5aSMartin Sperl 
3212523baf5aSMartin Sperl /**
3213523baf5aSMartin Sperl  * spi_replace_transfers - replace transfers with several transfers
3214523baf5aSMartin Sperl  *                         and register change with spi_message.resources
3215523baf5aSMartin Sperl  * @msg:           the spi_message we work upon
3216523baf5aSMartin Sperl  * @xfer_first:    the first spi_transfer we want to replace
3217523baf5aSMartin Sperl  * @remove:        number of transfers to remove
3218523baf5aSMartin Sperl  * @insert:        the number of transfers we want to insert instead
3219523baf5aSMartin Sperl  * @release:       extra release code necessary in some circumstances
3220523baf5aSMartin Sperl  * @extradatasize: extra data to allocate (with alignment guarantees
3221523baf5aSMartin Sperl  *                 of struct @spi_transfer)
322205885397SMartin Sperl  * @gfp:           gfp flags
3223523baf5aSMartin Sperl  *
3224523baf5aSMartin Sperl  * Returns: pointer to @spi_replaced_transfers,
3225523baf5aSMartin Sperl  *          PTR_ERR(...) in case of errors.
3226523baf5aSMartin Sperl  */
3227da21fde0SUwe Kleine-König static struct spi_replaced_transfers *spi_replace_transfers(
3228523baf5aSMartin Sperl 	struct spi_message *msg,
3229523baf5aSMartin Sperl 	struct spi_transfer *xfer_first,
3230523baf5aSMartin Sperl 	size_t remove,
3231523baf5aSMartin Sperl 	size_t insert,
3232523baf5aSMartin Sperl 	spi_replaced_release_t release,
3233523baf5aSMartin Sperl 	size_t extradatasize,
3234523baf5aSMartin Sperl 	gfp_t gfp)
3235523baf5aSMartin Sperl {
3236523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer;
3237523baf5aSMartin Sperl 	struct spi_transfer *xfer;
3238523baf5aSMartin Sperl 	size_t i;
3239523baf5aSMartin Sperl 
3240523baf5aSMartin Sperl 	/* allocate the structure using spi_res */
3241523baf5aSMartin Sperl 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3242aef97522SGustavo A. R. Silva 			      struct_size(rxfer, inserted_transfers, insert)
3243523baf5aSMartin Sperl 			      + extradatasize,
3244523baf5aSMartin Sperl 			      gfp);
3245523baf5aSMartin Sperl 	if (!rxfer)
3246523baf5aSMartin Sperl 		return ERR_PTR(-ENOMEM);
3247523baf5aSMartin Sperl 
3248523baf5aSMartin Sperl 	/* the release code to invoke before running the generic release */
3249523baf5aSMartin Sperl 	rxfer->release = release;
3250523baf5aSMartin Sperl 
3251523baf5aSMartin Sperl 	/* assign extradata */
3252523baf5aSMartin Sperl 	if (extradatasize)
3253523baf5aSMartin Sperl 		rxfer->extradata =
3254523baf5aSMartin Sperl 			&rxfer->inserted_transfers[insert];
3255523baf5aSMartin Sperl 
3256523baf5aSMartin Sperl 	/* init the replaced_transfers list */
3257523baf5aSMartin Sperl 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3258523baf5aSMartin Sperl 
3259350de7ceSAndy Shevchenko 	/*
3260350de7ceSAndy Shevchenko 	 * Assign the list_entry after which we should reinsert
3261523baf5aSMartin Sperl 	 * the @replaced_transfers - it may be spi_message.messages!
3262523baf5aSMartin Sperl 	 */
3263523baf5aSMartin Sperl 	rxfer->replaced_after = xfer_first->transfer_list.prev;
3264523baf5aSMartin Sperl 
3265523baf5aSMartin Sperl 	/* remove the requested number of transfers */
3266523baf5aSMartin Sperl 	for (i = 0; i < remove; i++) {
3267350de7ceSAndy Shevchenko 		/*
3268350de7ceSAndy Shevchenko 		 * If the entry after replaced_after it is msg->transfers
3269523baf5aSMartin Sperl 		 * then we have been requested to remove more transfers
3270350de7ceSAndy Shevchenko 		 * than are in the list.
3271523baf5aSMartin Sperl 		 */
3272523baf5aSMartin Sperl 		if (rxfer->replaced_after->next == &msg->transfers) {
3273523baf5aSMartin Sperl 			dev_err(&msg->spi->dev,
3274523baf5aSMartin Sperl 				"requested to remove more spi_transfers than are available\n");
3275523baf5aSMartin Sperl 			/* insert replaced transfers back into the message */
3276523baf5aSMartin Sperl 			list_splice(&rxfer->replaced_transfers,
3277523baf5aSMartin Sperl 				    rxfer->replaced_after);
3278523baf5aSMartin Sperl 
3279523baf5aSMartin Sperl 			/* free the spi_replace_transfer structure */
3280523baf5aSMartin Sperl 			spi_res_free(rxfer);
3281523baf5aSMartin Sperl 
3282523baf5aSMartin Sperl 			/* and return with an error */
3283523baf5aSMartin Sperl 			return ERR_PTR(-EINVAL);
3284523baf5aSMartin Sperl 		}
3285523baf5aSMartin Sperl 
3286350de7ceSAndy Shevchenko 		/*
3287350de7ceSAndy Shevchenko 		 * Remove the entry after replaced_after from list of
3288350de7ceSAndy Shevchenko 		 * transfers and add it to list of replaced_transfers.
3289523baf5aSMartin Sperl 		 */
3290523baf5aSMartin Sperl 		list_move_tail(rxfer->replaced_after->next,
3291523baf5aSMartin Sperl 			       &rxfer->replaced_transfers);
3292523baf5aSMartin Sperl 	}
3293523baf5aSMartin Sperl 
3294350de7ceSAndy Shevchenko 	/*
3295350de7ceSAndy Shevchenko 	 * Create copy of the given xfer with identical settings
3296350de7ceSAndy Shevchenko 	 * based on the first transfer to get removed.
3297523baf5aSMartin Sperl 	 */
3298523baf5aSMartin Sperl 	for (i = 0; i < insert; i++) {
3299523baf5aSMartin Sperl 		/* we need to run in reverse order */
3300523baf5aSMartin Sperl 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3301523baf5aSMartin Sperl 
3302523baf5aSMartin Sperl 		/* copy all spi_transfer data */
3303523baf5aSMartin Sperl 		memcpy(xfer, xfer_first, sizeof(*xfer));
3304523baf5aSMartin Sperl 
3305523baf5aSMartin Sperl 		/* add to list */
3306523baf5aSMartin Sperl 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3307523baf5aSMartin Sperl 
3308bebcfd27SAlexandru Ardelean 		/* clear cs_change and delay for all but the last */
3309523baf5aSMartin Sperl 		if (i) {
3310523baf5aSMartin Sperl 			xfer->cs_change = false;
3311bebcfd27SAlexandru Ardelean 			xfer->delay.value = 0;
3312523baf5aSMartin Sperl 		}
3313523baf5aSMartin Sperl 	}
3314523baf5aSMartin Sperl 
3315523baf5aSMartin Sperl 	/* set up inserted */
3316523baf5aSMartin Sperl 	rxfer->inserted = insert;
3317523baf5aSMartin Sperl 
3318523baf5aSMartin Sperl 	/* and register it with spi_res/spi_message */
3319523baf5aSMartin Sperl 	spi_res_add(msg, rxfer);
3320523baf5aSMartin Sperl 
3321523baf5aSMartin Sperl 	return rxfer;
3322523baf5aSMartin Sperl }
3323523baf5aSMartin Sperl 
33248caab75fSGeert Uytterhoeven static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3325d9f12122SMartin Sperl 					struct spi_message *msg,
3326d9f12122SMartin Sperl 					struct spi_transfer **xferp,
3327d9f12122SMartin Sperl 					size_t maxsize,
3328d9f12122SMartin Sperl 					gfp_t gfp)
3329d9f12122SMartin Sperl {
3330d9f12122SMartin Sperl 	struct spi_transfer *xfer = *xferp, *xfers;
3331d9f12122SMartin Sperl 	struct spi_replaced_transfers *srt;
3332d9f12122SMartin Sperl 	size_t offset;
3333d9f12122SMartin Sperl 	size_t count, i;
3334d9f12122SMartin Sperl 
3335d9f12122SMartin Sperl 	/* calculate how many we have to replace */
3336d9f12122SMartin Sperl 	count = DIV_ROUND_UP(xfer->len, maxsize);
3337d9f12122SMartin Sperl 
3338d9f12122SMartin Sperl 	/* create replacement */
3339d9f12122SMartin Sperl 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3340657d32efSDan Carpenter 	if (IS_ERR(srt))
3341657d32efSDan Carpenter 		return PTR_ERR(srt);
3342d9f12122SMartin Sperl 	xfers = srt->inserted_transfers;
3343d9f12122SMartin Sperl 
3344350de7ceSAndy Shevchenko 	/*
3345350de7ceSAndy Shevchenko 	 * Now handle each of those newly inserted spi_transfers.
3346350de7ceSAndy Shevchenko 	 * Note that the replacements spi_transfers all are preset
3347d9f12122SMartin Sperl 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3348d9f12122SMartin Sperl 	 * are all identical (as well as most others)
3349d9f12122SMartin Sperl 	 * so we just have to fix up len and the pointers.
3350d9f12122SMartin Sperl 	 *
3351350de7ceSAndy Shevchenko 	 * This also includes support for the depreciated
3352350de7ceSAndy Shevchenko 	 * spi_message.is_dma_mapped interface.
3353d9f12122SMartin Sperl 	 */
3354d9f12122SMartin Sperl 
3355350de7ceSAndy Shevchenko 	/*
3356350de7ceSAndy Shevchenko 	 * The first transfer just needs the length modified, so we
3357350de7ceSAndy Shevchenko 	 * run it outside the loop.
3358d9f12122SMartin Sperl 	 */
3359c8dab77aSFabio Estevam 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3360d9f12122SMartin Sperl 
3361d9f12122SMartin Sperl 	/* all the others need rx_buf/tx_buf also set */
3362d9f12122SMartin Sperl 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3363d9f12122SMartin Sperl 		/* update rx_buf, tx_buf and dma */
3364d9f12122SMartin Sperl 		if (xfers[i].rx_buf)
3365d9f12122SMartin Sperl 			xfers[i].rx_buf += offset;
3366d9f12122SMartin Sperl 		if (xfers[i].rx_dma)
3367d9f12122SMartin Sperl 			xfers[i].rx_dma += offset;
3368d9f12122SMartin Sperl 		if (xfers[i].tx_buf)
3369d9f12122SMartin Sperl 			xfers[i].tx_buf += offset;
3370d9f12122SMartin Sperl 		if (xfers[i].tx_dma)
3371d9f12122SMartin Sperl 			xfers[i].tx_dma += offset;
3372d9f12122SMartin Sperl 
3373d9f12122SMartin Sperl 		/* update length */
3374d9f12122SMartin Sperl 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3375d9f12122SMartin Sperl 	}
3376d9f12122SMartin Sperl 
3377350de7ceSAndy Shevchenko 	/*
3378350de7ceSAndy Shevchenko 	 * We set up xferp to the last entry we have inserted,
3379350de7ceSAndy Shevchenko 	 * so that we skip those already split transfers.
3380d9f12122SMartin Sperl 	 */
3381d9f12122SMartin Sperl 	*xferp = &xfers[count - 1];
3382d9f12122SMartin Sperl 
3383d9f12122SMartin Sperl 	/* increment statistics counters */
33848caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3385d9f12122SMartin Sperl 				       transfers_split_maxsize);
3386d9f12122SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3387d9f12122SMartin Sperl 				       transfers_split_maxsize);
3388d9f12122SMartin Sperl 
3389d9f12122SMartin Sperl 	return 0;
3390d9f12122SMartin Sperl }
3391d9f12122SMartin Sperl 
3392d9f12122SMartin Sperl /**
3393ce2424d7SMauro Carvalho Chehab  * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3394d9f12122SMartin Sperl  *                               when an individual transfer exceeds a
3395d9f12122SMartin Sperl  *                               certain size
33968caab75fSGeert Uytterhoeven  * @ctlr:    the @spi_controller for this transfer
33973700ce95SMasanari Iida  * @msg:   the @spi_message to transform
33983700ce95SMasanari Iida  * @maxsize:  the maximum when to apply this
339910f11a22SJavier Martinez Canillas  * @gfp: GFP allocation flags
3400d9f12122SMartin Sperl  *
3401d9f12122SMartin Sperl  * Return: status of transformation
3402d9f12122SMartin Sperl  */
34038caab75fSGeert Uytterhoeven int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3404d9f12122SMartin Sperl 				struct spi_message *msg,
3405d9f12122SMartin Sperl 				size_t maxsize,
3406d9f12122SMartin Sperl 				gfp_t gfp)
3407d9f12122SMartin Sperl {
3408d9f12122SMartin Sperl 	struct spi_transfer *xfer;
3409d9f12122SMartin Sperl 	int ret;
3410d9f12122SMartin Sperl 
3411350de7ceSAndy Shevchenko 	/*
3412350de7ceSAndy Shevchenko 	 * Iterate over the transfer_list,
3413d9f12122SMartin Sperl 	 * but note that xfer is advanced to the last transfer inserted
3414d9f12122SMartin Sperl 	 * to avoid checking sizes again unnecessarily (also xfer does
3415350de7ceSAndy Shevchenko 	 * potentially belong to a different list by the time the
3416350de7ceSAndy Shevchenko 	 * replacement has happened).
3417d9f12122SMartin Sperl 	 */
3418d9f12122SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3419d9f12122SMartin Sperl 		if (xfer->len > maxsize) {
34208caab75fSGeert Uytterhoeven 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
34218caab75fSGeert Uytterhoeven 							   maxsize, gfp);
3422d9f12122SMartin Sperl 			if (ret)
3423d9f12122SMartin Sperl 				return ret;
3424d9f12122SMartin Sperl 		}
3425d9f12122SMartin Sperl 	}
3426d9f12122SMartin Sperl 
3427d9f12122SMartin Sperl 	return 0;
3428d9f12122SMartin Sperl }
3429d9f12122SMartin Sperl EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
34308ae12a0dSDavid Brownell 
34318ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
34328ae12a0dSDavid Brownell 
34338caab75fSGeert Uytterhoeven /* Core methods for SPI controller protocol drivers.  Some of the
34347d077197SDavid Brownell  * other core methods are currently defined as inline functions.
34357d077197SDavid Brownell  */
34367d077197SDavid Brownell 
34378caab75fSGeert Uytterhoeven static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
34388caab75fSGeert Uytterhoeven 					u8 bits_per_word)
343963ab645fSStefan Brüns {
34408caab75fSGeert Uytterhoeven 	if (ctlr->bits_per_word_mask) {
344163ab645fSStefan Brüns 		/* Only 32 bits fit in the mask */
344263ab645fSStefan Brüns 		if (bits_per_word > 32)
344363ab645fSStefan Brüns 			return -EINVAL;
34448caab75fSGeert Uytterhoeven 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
344563ab645fSStefan Brüns 			return -EINVAL;
344663ab645fSStefan Brüns 	}
344763ab645fSStefan Brüns 
344863ab645fSStefan Brüns 	return 0;
344963ab645fSStefan Brüns }
345063ab645fSStefan Brüns 
34517d077197SDavid Brownell /**
34527d077197SDavid Brownell  * spi_setup - setup SPI mode and clock rate
34537d077197SDavid Brownell  * @spi: the device whose settings are being modified
34547d077197SDavid Brownell  * Context: can sleep, and no requests are queued to the device
34557d077197SDavid Brownell  *
34567d077197SDavid Brownell  * SPI protocol drivers may need to update the transfer mode if the
34577d077197SDavid Brownell  * device doesn't work with its default.  They may likewise need
34587d077197SDavid Brownell  * to update clock rates or word sizes from initial values.  This function
34597d077197SDavid Brownell  * changes those settings, and must be called from a context that can sleep.
34607d077197SDavid Brownell  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
34617d077197SDavid Brownell  * effect the next time the device is selected and data is transferred to
34627d077197SDavid Brownell  * or from it.  When this function returns, the spi device is deselected.
34637d077197SDavid Brownell  *
34647d077197SDavid Brownell  * Note that this call will fail if the protocol driver specifies an option
34657d077197SDavid Brownell  * that the underlying controller or its driver does not support.  For
34667d077197SDavid Brownell  * example, not all hardware supports wire transfers using nine bit words,
34677d077197SDavid Brownell  * LSB-first wire encoding, or active-high chipselects.
346897d56dc6SJavier Martinez Canillas  *
346997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
34707d077197SDavid Brownell  */
34717d077197SDavid Brownell int spi_setup(struct spi_device *spi)
34727d077197SDavid Brownell {
347383596fbeSGeert Uytterhoeven 	unsigned	bad_bits, ugly_bits;
34745ab8d262SAndy Shevchenko 	int		status;
34757d077197SDavid Brownell 
3476d962608cSDragos Bogdan 	/*
3477350de7ceSAndy Shevchenko 	 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3478350de7ceSAndy Shevchenko 	 * are set at the same time.
3479f477b7fbSwangyuhang 	 */
3480d962608cSDragos Bogdan 	if ((hweight_long(spi->mode &
3481d962608cSDragos Bogdan 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3482d962608cSDragos Bogdan 	    (hweight_long(spi->mode &
3483d962608cSDragos Bogdan 		(SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3484f477b7fbSwangyuhang 		dev_err(&spi->dev,
3485d962608cSDragos Bogdan 		"setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3486f477b7fbSwangyuhang 		return -EINVAL;
3487f477b7fbSwangyuhang 	}
3488350de7ceSAndy Shevchenko 	/* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3489f477b7fbSwangyuhang 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
34906b03061fSYogesh Narayan Gaur 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
34916b03061fSYogesh Narayan Gaur 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3492f477b7fbSwangyuhang 		return -EINVAL;
3493350de7ceSAndy Shevchenko 	/*
3494350de7ceSAndy Shevchenko 	 * Help drivers fail *cleanly* when they need options
3495350de7ceSAndy Shevchenko 	 * that aren't supported with their current controller.
3496cbaa62e0SDavid Lechner 	 * SPI_CS_WORD has a fallback software implementation,
3497cbaa62e0SDavid Lechner 	 * so it is ignored here.
3498e7db06b5SDavid Brownell 	 */
3499d962608cSDragos Bogdan 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3500d962608cSDragos Bogdan 				 SPI_NO_TX | SPI_NO_RX);
350183596fbeSGeert Uytterhoeven 	ugly_bits = bad_bits &
35026b03061fSYogesh Narayan Gaur 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
35036b03061fSYogesh Narayan Gaur 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
350483596fbeSGeert Uytterhoeven 	if (ugly_bits) {
350583596fbeSGeert Uytterhoeven 		dev_warn(&spi->dev,
350683596fbeSGeert Uytterhoeven 			 "setup: ignoring unsupported mode bits %x\n",
350783596fbeSGeert Uytterhoeven 			 ugly_bits);
350883596fbeSGeert Uytterhoeven 		spi->mode &= ~ugly_bits;
350983596fbeSGeert Uytterhoeven 		bad_bits &= ~ugly_bits;
351083596fbeSGeert Uytterhoeven 	}
3511e7db06b5SDavid Brownell 	if (bad_bits) {
3512eb288a1fSLinus Walleij 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3513e7db06b5SDavid Brownell 			bad_bits);
3514e7db06b5SDavid Brownell 		return -EINVAL;
3515e7db06b5SDavid Brownell 	}
3516e7db06b5SDavid Brownell 
35177d077197SDavid Brownell 	if (!spi->bits_per_word)
35187d077197SDavid Brownell 		spi->bits_per_word = 8;
35197d077197SDavid Brownell 
35208caab75fSGeert Uytterhoeven 	status = __spi_validate_bits_per_word(spi->controller,
35218caab75fSGeert Uytterhoeven 					      spi->bits_per_word);
35225ab8d262SAndy Shevchenko 	if (status)
35235ab8d262SAndy Shevchenko 		return status;
352463ab645fSStefan Brüns 
35256820e812STudor Ambarus 	if (spi->controller->max_speed_hz &&
35266820e812STudor Ambarus 	    (!spi->max_speed_hz ||
35276820e812STudor Ambarus 	     spi->max_speed_hz > spi->controller->max_speed_hz))
35288caab75fSGeert Uytterhoeven 		spi->max_speed_hz = spi->controller->max_speed_hz;
3529052eb2d4SAxel Lin 
35304fae3a58SSerge Semin 	mutex_lock(&spi->controller->io_mutex);
35314fae3a58SSerge Semin 
3532c914dbf8SJoe Burmeister 	if (spi->controller->setup) {
35338caab75fSGeert Uytterhoeven 		status = spi->controller->setup(spi);
3534c914dbf8SJoe Burmeister 		if (status) {
3535c914dbf8SJoe Burmeister 			mutex_unlock(&spi->controller->io_mutex);
3536c914dbf8SJoe Burmeister 			dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3537c914dbf8SJoe Burmeister 				status);
3538c914dbf8SJoe Burmeister 			return status;
3539c914dbf8SJoe Burmeister 		}
3540c914dbf8SJoe Burmeister 	}
35417d077197SDavid Brownell 
3542d948e6caSLuhua Xu 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3543d948e6caSLuhua Xu 		status = pm_runtime_get_sync(spi->controller->dev.parent);
3544d948e6caSLuhua Xu 		if (status < 0) {
35454fae3a58SSerge Semin 			mutex_unlock(&spi->controller->io_mutex);
3546d948e6caSLuhua Xu 			pm_runtime_put_noidle(spi->controller->dev.parent);
3547d948e6caSLuhua Xu 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3548d948e6caSLuhua Xu 				status);
3549d948e6caSLuhua Xu 			return status;
3550d948e6caSLuhua Xu 		}
355157a94607STony Lindgren 
355257a94607STony Lindgren 		/*
355357a94607STony Lindgren 		 * We do not want to return positive value from pm_runtime_get,
355457a94607STony Lindgren 		 * there are many instances of devices calling spi_setup() and
355557a94607STony Lindgren 		 * checking for a non-zero return value instead of a negative
355657a94607STony Lindgren 		 * return value.
355757a94607STony Lindgren 		 */
355857a94607STony Lindgren 		status = 0;
355957a94607STony Lindgren 
3560d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
3561d948e6caSLuhua Xu 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3562d948e6caSLuhua Xu 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3563d948e6caSLuhua Xu 	} else {
3564d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
3565d948e6caSLuhua Xu 	}
3566abeedb01SFranklin S Cooper Jr 
35674fae3a58SSerge Semin 	mutex_unlock(&spi->controller->io_mutex);
35684fae3a58SSerge Semin 
3569924b5867SDouglas Anderson 	if (spi->rt && !spi->controller->rt) {
3570924b5867SDouglas Anderson 		spi->controller->rt = true;
3571924b5867SDouglas Anderson 		spi_set_thread_rt(spi->controller);
3572924b5867SDouglas Anderson 	}
3573924b5867SDouglas Anderson 
35745cb4e1f3SAndy Shevchenko 	trace_spi_setup(spi, status);
35755cb4e1f3SAndy Shevchenko 
357640b82c2dSAndy Shevchenko 	dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
357740b82c2dSAndy Shevchenko 			spi->mode & SPI_MODE_X_MASK,
35787d077197SDavid Brownell 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
35797d077197SDavid Brownell 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
35807d077197SDavid Brownell 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
35817d077197SDavid Brownell 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
35827d077197SDavid Brownell 			spi->bits_per_word, spi->max_speed_hz,
35837d077197SDavid Brownell 			status);
35847d077197SDavid Brownell 
35857d077197SDavid Brownell 	return status;
35867d077197SDavid Brownell }
35877d077197SDavid Brownell EXPORT_SYMBOL_GPL(spi_setup);
35887d077197SDavid Brownell 
35896c613f68SAlexandru Ardelean static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
35906c613f68SAlexandru Ardelean 				       struct spi_device *spi)
35916c613f68SAlexandru Ardelean {
35926c613f68SAlexandru Ardelean 	int delay1, delay2;
35936c613f68SAlexandru Ardelean 
35943984d39bSAlexandru Ardelean 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
35956c613f68SAlexandru Ardelean 	if (delay1 < 0)
35966c613f68SAlexandru Ardelean 		return delay1;
35976c613f68SAlexandru Ardelean 
35983984d39bSAlexandru Ardelean 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
35996c613f68SAlexandru Ardelean 	if (delay2 < 0)
36006c613f68SAlexandru Ardelean 		return delay2;
36016c613f68SAlexandru Ardelean 
36026c613f68SAlexandru Ardelean 	if (delay1 < delay2)
36036c613f68SAlexandru Ardelean 		memcpy(&xfer->word_delay, &spi->word_delay,
36046c613f68SAlexandru Ardelean 		       sizeof(xfer->word_delay));
36056c613f68SAlexandru Ardelean 
36066c613f68SAlexandru Ardelean 	return 0;
36076c613f68SAlexandru Ardelean }
36086c613f68SAlexandru Ardelean 
360990808738SMark Brown static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3610cf32b71eSErnst Schwab {
36118caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3612e6811d1dSLaxman Dewangan 	struct spi_transfer *xfer;
36136ea31293SAtsushi Nemoto 	int w_size;
3614cf32b71eSErnst Schwab 
361524a0013aSMark Brown 	if (list_empty(&message->transfers))
361624a0013aSMark Brown 		return -EINVAL;
361724a0013aSMark Brown 
3618350de7ceSAndy Shevchenko 	/*
3619350de7ceSAndy Shevchenko 	 * If an SPI controller does not support toggling the CS line on each
362071388b21SDavid Lechner 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
362171388b21SDavid Lechner 	 * for the CS line, we can emulate the CS-per-word hardware function by
3622cbaa62e0SDavid Lechner 	 * splitting transfers into one-word transfers and ensuring that
3623cbaa62e0SDavid Lechner 	 * cs_change is set for each transfer.
3624cbaa62e0SDavid Lechner 	 */
362571388b21SDavid Lechner 	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3626f48dc6b9SLinus Walleij 					  spi->cs_gpiod)) {
3627cbaa62e0SDavid Lechner 		size_t maxsize;
3628cbaa62e0SDavid Lechner 		int ret;
3629cbaa62e0SDavid Lechner 
3630cbaa62e0SDavid Lechner 		maxsize = (spi->bits_per_word + 7) / 8;
3631cbaa62e0SDavid Lechner 
3632cbaa62e0SDavid Lechner 		/* spi_split_transfers_maxsize() requires message->spi */
3633cbaa62e0SDavid Lechner 		message->spi = spi;
3634cbaa62e0SDavid Lechner 
3635cbaa62e0SDavid Lechner 		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3636cbaa62e0SDavid Lechner 						  GFP_KERNEL);
3637cbaa62e0SDavid Lechner 		if (ret)
3638cbaa62e0SDavid Lechner 			return ret;
3639cbaa62e0SDavid Lechner 
3640cbaa62e0SDavid Lechner 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3641cbaa62e0SDavid Lechner 			/* don't change cs_change on the last entry in the list */
3642cbaa62e0SDavid Lechner 			if (list_is_last(&xfer->transfer_list, &message->transfers))
3643cbaa62e0SDavid Lechner 				break;
3644cbaa62e0SDavid Lechner 			xfer->cs_change = 1;
3645cbaa62e0SDavid Lechner 		}
3646cbaa62e0SDavid Lechner 	}
3647cbaa62e0SDavid Lechner 
3648350de7ceSAndy Shevchenko 	/*
3649350de7ceSAndy Shevchenko 	 * Half-duplex links include original MicroWire, and ones with
3650cf32b71eSErnst Schwab 	 * only one data pin like SPI_3WIRE (switches direction) or where
3651cf32b71eSErnst Schwab 	 * either MOSI or MISO is missing.  They can also be caused by
3652cf32b71eSErnst Schwab 	 * software limitations.
3653cf32b71eSErnst Schwab 	 */
36548caab75fSGeert Uytterhoeven 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
36558caab75fSGeert Uytterhoeven 	    (spi->mode & SPI_3WIRE)) {
36568caab75fSGeert Uytterhoeven 		unsigned flags = ctlr->flags;
3657cf32b71eSErnst Schwab 
3658cf32b71eSErnst Schwab 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3659cf32b71eSErnst Schwab 			if (xfer->rx_buf && xfer->tx_buf)
3660cf32b71eSErnst Schwab 				return -EINVAL;
36618caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3662cf32b71eSErnst Schwab 				return -EINVAL;
36638caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3664cf32b71eSErnst Schwab 				return -EINVAL;
3665cf32b71eSErnst Schwab 		}
3666cf32b71eSErnst Schwab 	}
3667cf32b71eSErnst Schwab 
3668350de7ceSAndy Shevchenko 	/*
3669059b8ffeSLaxman Dewangan 	 * Set transfer bits_per_word and max speed as spi device default if
3670059b8ffeSLaxman Dewangan 	 * it is not set for this transfer.
3671f477b7fbSwangyuhang 	 * Set transfer tx_nbits and rx_nbits as single transfer default
3672f477b7fbSwangyuhang 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3673b7bb367aSJonas Bonn 	 * Ensure transfer word_delay is at least as long as that required by
3674b7bb367aSJonas Bonn 	 * device itself.
3675e6811d1dSLaxman Dewangan 	 */
367677e80588SMartin Sperl 	message->frame_length = 0;
3677e6811d1dSLaxman Dewangan 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
36785d7e2b5eSMartin Sperl 		xfer->effective_speed_hz = 0;
3679078726ceSSourav Poddar 		message->frame_length += xfer->len;
3680e6811d1dSLaxman Dewangan 		if (!xfer->bits_per_word)
3681e6811d1dSLaxman Dewangan 			xfer->bits_per_word = spi->bits_per_word;
3682a6f87fadSAxel Lin 
3683a6f87fadSAxel Lin 		if (!xfer->speed_hz)
3684059b8ffeSLaxman Dewangan 			xfer->speed_hz = spi->max_speed_hz;
3685a6f87fadSAxel Lin 
36868caab75fSGeert Uytterhoeven 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
36878caab75fSGeert Uytterhoeven 			xfer->speed_hz = ctlr->max_speed_hz;
368856ede94aSGabor Juhos 
36898caab75fSGeert Uytterhoeven 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3690543bb255SStephen Warren 			return -EINVAL;
3691a2fd4f9fSMark Brown 
36924d94bd21SIvan T. Ivanov 		/*
36934d94bd21SIvan T. Ivanov 		 * SPI transfer length should be multiple of SPI word size
3694350de7ceSAndy Shevchenko 		 * where SPI word size should be power-of-two multiple.
36954d94bd21SIvan T. Ivanov 		 */
36964d94bd21SIvan T. Ivanov 		if (xfer->bits_per_word <= 8)
36974d94bd21SIvan T. Ivanov 			w_size = 1;
36984d94bd21SIvan T. Ivanov 		else if (xfer->bits_per_word <= 16)
36994d94bd21SIvan T. Ivanov 			w_size = 2;
37004d94bd21SIvan T. Ivanov 		else
37014d94bd21SIvan T. Ivanov 			w_size = 4;
37024d94bd21SIvan T. Ivanov 
37034d94bd21SIvan T. Ivanov 		/* No partial transfers accepted */
37046ea31293SAtsushi Nemoto 		if (xfer->len % w_size)
37054d94bd21SIvan T. Ivanov 			return -EINVAL;
37064d94bd21SIvan T. Ivanov 
37078caab75fSGeert Uytterhoeven 		if (xfer->speed_hz && ctlr->min_speed_hz &&
37088caab75fSGeert Uytterhoeven 		    xfer->speed_hz < ctlr->min_speed_hz)
3709a2fd4f9fSMark Brown 			return -EINVAL;
3710f477b7fbSwangyuhang 
3711f477b7fbSwangyuhang 		if (xfer->tx_buf && !xfer->tx_nbits)
3712f477b7fbSwangyuhang 			xfer->tx_nbits = SPI_NBITS_SINGLE;
3713f477b7fbSwangyuhang 		if (xfer->rx_buf && !xfer->rx_nbits)
3714f477b7fbSwangyuhang 			xfer->rx_nbits = SPI_NBITS_SINGLE;
3715350de7ceSAndy Shevchenko 		/*
3716350de7ceSAndy Shevchenko 		 * Check transfer tx/rx_nbits:
37171afd9989SGeert Uytterhoeven 		 * 1. check the value matches one of single, dual and quad
37181afd9989SGeert Uytterhoeven 		 * 2. check tx/rx_nbits match the mode in spi_device
3719f477b7fbSwangyuhang 		 */
3720db90a441SSourav Poddar 		if (xfer->tx_buf) {
3721d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_TX)
3722d962608cSDragos Bogdan 				return -EINVAL;
3723f477b7fbSwangyuhang 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3724f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_DUAL &&
3725f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_QUAD)
3726a2fd4f9fSMark Brown 				return -EINVAL;
3727f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3728f477b7fbSwangyuhang 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3729f477b7fbSwangyuhang 				return -EINVAL;
3730f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3731f477b7fbSwangyuhang 				!(spi->mode & SPI_TX_QUAD))
3732f477b7fbSwangyuhang 				return -EINVAL;
3733db90a441SSourav Poddar 		}
3734f477b7fbSwangyuhang 		/* check transfer rx_nbits */
3735db90a441SSourav Poddar 		if (xfer->rx_buf) {
3736d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_RX)
3737d962608cSDragos Bogdan 				return -EINVAL;
3738f477b7fbSwangyuhang 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3739f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_DUAL &&
3740f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_QUAD)
3741f477b7fbSwangyuhang 				return -EINVAL;
3742f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3743f477b7fbSwangyuhang 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3744f477b7fbSwangyuhang 				return -EINVAL;
3745f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3746f477b7fbSwangyuhang 				!(spi->mode & SPI_RX_QUAD))
3747f477b7fbSwangyuhang 				return -EINVAL;
3748e6811d1dSLaxman Dewangan 		}
3749b7bb367aSJonas Bonn 
37506c613f68SAlexandru Ardelean 		if (_spi_xfer_word_delay_update(xfer, spi))
37516c613f68SAlexandru Ardelean 			return -EINVAL;
3752e6811d1dSLaxman Dewangan 	}
3753e6811d1dSLaxman Dewangan 
3754cf32b71eSErnst Schwab 	message->status = -EINPROGRESS;
375590808738SMark Brown 
375690808738SMark Brown 	return 0;
375790808738SMark Brown }
375890808738SMark Brown 
375990808738SMark Brown static int __spi_async(struct spi_device *spi, struct spi_message *message)
376090808738SMark Brown {
37618caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3762b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
376390808738SMark Brown 
3764b5932f5cSBoris Brezillon 	/*
3765b5932f5cSBoris Brezillon 	 * Some controllers do not support doing regular SPI transfers. Return
3766b5932f5cSBoris Brezillon 	 * ENOTSUPP when this is the case.
3767b5932f5cSBoris Brezillon 	 */
3768b5932f5cSBoris Brezillon 	if (!ctlr->transfer)
3769b5932f5cSBoris Brezillon 		return -ENOTSUPP;
3770b5932f5cSBoris Brezillon 
377190808738SMark Brown 	message->spi = spi;
377290808738SMark Brown 
37738caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3774eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3775eca2ebc7SMartin Sperl 
377690808738SMark Brown 	trace_spi_message_submit(message);
377790808738SMark Brown 
3778b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported) {
3779b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3780b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
3781b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
3782b42faeeeSVladimir Oltean 		}
3783b42faeeeSVladimir Oltean 	}
3784b42faeeeSVladimir Oltean 
37858caab75fSGeert Uytterhoeven 	return ctlr->transfer(spi, message);
3786cf32b71eSErnst Schwab }
3787cf32b71eSErnst Schwab 
3788568d0697SDavid Brownell /**
3789568d0697SDavid Brownell  * spi_async - asynchronous SPI transfer
3790568d0697SDavid Brownell  * @spi: device with which data will be exchanged
3791568d0697SDavid Brownell  * @message: describes the data transfers, including completion callback
3792568d0697SDavid Brownell  * Context: any (irqs may be blocked, etc)
3793568d0697SDavid Brownell  *
3794568d0697SDavid Brownell  * This call may be used in_irq and other contexts which can't sleep,
3795568d0697SDavid Brownell  * as well as from task contexts which can sleep.
3796568d0697SDavid Brownell  *
3797568d0697SDavid Brownell  * The completion callback is invoked in a context which can't sleep.
3798568d0697SDavid Brownell  * Before that invocation, the value of message->status is undefined.
3799568d0697SDavid Brownell  * When the callback is issued, message->status holds either zero (to
3800568d0697SDavid Brownell  * indicate complete success) or a negative error code.  After that
3801568d0697SDavid Brownell  * callback returns, the driver which issued the transfer request may
3802568d0697SDavid Brownell  * deallocate the associated memory; it's no longer in use by any SPI
3803568d0697SDavid Brownell  * core or controller driver code.
3804568d0697SDavid Brownell  *
3805568d0697SDavid Brownell  * Note that although all messages to a spi_device are handled in
3806568d0697SDavid Brownell  * FIFO order, messages may go to different devices in other orders.
3807568d0697SDavid Brownell  * Some device might be higher priority, or have various "hard" access
3808568d0697SDavid Brownell  * time requirements, for example.
3809568d0697SDavid Brownell  *
3810568d0697SDavid Brownell  * On detection of any fault during the transfer, processing of
3811568d0697SDavid Brownell  * the entire message is aborted, and the device is deselected.
3812568d0697SDavid Brownell  * Until returning from the associated message completion callback,
3813568d0697SDavid Brownell  * no other spi_message queued to that device will be processed.
3814568d0697SDavid Brownell  * (This rule applies equally to all the synchronous transfer calls,
3815568d0697SDavid Brownell  * which are wrappers around this core asynchronous primitive.)
381697d56dc6SJavier Martinez Canillas  *
381797d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3818568d0697SDavid Brownell  */
3819568d0697SDavid Brownell int spi_async(struct spi_device *spi, struct spi_message *message)
3820568d0697SDavid Brownell {
38218caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3822cf32b71eSErnst Schwab 	int ret;
3823cf32b71eSErnst Schwab 	unsigned long flags;
3824568d0697SDavid Brownell 
382590808738SMark Brown 	ret = __spi_validate(spi, message);
382690808738SMark Brown 	if (ret != 0)
382790808738SMark Brown 		return ret;
382890808738SMark Brown 
38298caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3830568d0697SDavid Brownell 
38318caab75fSGeert Uytterhoeven 	if (ctlr->bus_lock_flag)
3832cf32b71eSErnst Schwab 		ret = -EBUSY;
3833cf32b71eSErnst Schwab 	else
3834cf32b71eSErnst Schwab 		ret = __spi_async(spi, message);
3835568d0697SDavid Brownell 
38368caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3837cf32b71eSErnst Schwab 
3838cf32b71eSErnst Schwab 	return ret;
3839568d0697SDavid Brownell }
3840568d0697SDavid Brownell EXPORT_SYMBOL_GPL(spi_async);
3841568d0697SDavid Brownell 
3842cf32b71eSErnst Schwab /**
3843cf32b71eSErnst Schwab  * spi_async_locked - version of spi_async with exclusive bus usage
3844cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
3845cf32b71eSErnst Schwab  * @message: describes the data transfers, including completion callback
3846cf32b71eSErnst Schwab  * Context: any (irqs may be blocked, etc)
3847cf32b71eSErnst Schwab  *
3848cf32b71eSErnst Schwab  * This call may be used in_irq and other contexts which can't sleep,
3849cf32b71eSErnst Schwab  * as well as from task contexts which can sleep.
3850cf32b71eSErnst Schwab  *
3851cf32b71eSErnst Schwab  * The completion callback is invoked in a context which can't sleep.
3852cf32b71eSErnst Schwab  * Before that invocation, the value of message->status is undefined.
3853cf32b71eSErnst Schwab  * When the callback is issued, message->status holds either zero (to
3854cf32b71eSErnst Schwab  * indicate complete success) or a negative error code.  After that
3855cf32b71eSErnst Schwab  * callback returns, the driver which issued the transfer request may
3856cf32b71eSErnst Schwab  * deallocate the associated memory; it's no longer in use by any SPI
3857cf32b71eSErnst Schwab  * core or controller driver code.
3858cf32b71eSErnst Schwab  *
3859cf32b71eSErnst Schwab  * Note that although all messages to a spi_device are handled in
3860cf32b71eSErnst Schwab  * FIFO order, messages may go to different devices in other orders.
3861cf32b71eSErnst Schwab  * Some device might be higher priority, or have various "hard" access
3862cf32b71eSErnst Schwab  * time requirements, for example.
3863cf32b71eSErnst Schwab  *
3864cf32b71eSErnst Schwab  * On detection of any fault during the transfer, processing of
3865cf32b71eSErnst Schwab  * the entire message is aborted, and the device is deselected.
3866cf32b71eSErnst Schwab  * Until returning from the associated message completion callback,
3867cf32b71eSErnst Schwab  * no other spi_message queued to that device will be processed.
3868cf32b71eSErnst Schwab  * (This rule applies equally to all the synchronous transfer calls,
3869cf32b71eSErnst Schwab  * which are wrappers around this core asynchronous primitive.)
387097d56dc6SJavier Martinez Canillas  *
387197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3872cf32b71eSErnst Schwab  */
3873da21fde0SUwe Kleine-König static int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3874cf32b71eSErnst Schwab {
38758caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3876cf32b71eSErnst Schwab 	int ret;
3877cf32b71eSErnst Schwab 	unsigned long flags;
3878cf32b71eSErnst Schwab 
387990808738SMark Brown 	ret = __spi_validate(spi, message);
388090808738SMark Brown 	if (ret != 0)
388190808738SMark Brown 		return ret;
388290808738SMark Brown 
38838caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3884cf32b71eSErnst Schwab 
3885cf32b71eSErnst Schwab 	ret = __spi_async(spi, message);
3886cf32b71eSErnst Schwab 
38878caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3888cf32b71eSErnst Schwab 
3889cf32b71eSErnst Schwab 	return ret;
3890cf32b71eSErnst Schwab 
3891cf32b71eSErnst Schwab }
3892cf32b71eSErnst Schwab 
38937d077197SDavid Brownell /*-------------------------------------------------------------------------*/
38947d077197SDavid Brownell 
3895350de7ceSAndy Shevchenko /*
3896350de7ceSAndy Shevchenko  * Utility methods for SPI protocol drivers, layered on
38977d077197SDavid Brownell  * top of the core.  Some other utility methods are defined as
38987d077197SDavid Brownell  * inline functions.
38997d077197SDavid Brownell  */
39007d077197SDavid Brownell 
39015d870c8eSAndrew Morton static void spi_complete(void *arg)
39025d870c8eSAndrew Morton {
39035d870c8eSAndrew Morton 	complete(arg);
39045d870c8eSAndrew Morton }
39055d870c8eSAndrew Morton 
3906ef4d96ecSMark Brown static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3907cf32b71eSErnst Schwab {
3908cf32b71eSErnst Schwab 	DECLARE_COMPLETION_ONSTACK(done);
3909cf32b71eSErnst Schwab 	int status;
39108caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
39110461a414SMark Brown 	unsigned long flags;
39120461a414SMark Brown 
39130461a414SMark Brown 	status = __spi_validate(spi, message);
39140461a414SMark Brown 	if (status != 0)
39150461a414SMark Brown 		return status;
3916cf32b71eSErnst Schwab 
3917cf32b71eSErnst Schwab 	message->complete = spi_complete;
3918cf32b71eSErnst Schwab 	message->context = &done;
39190461a414SMark Brown 	message->spi = spi;
3920cf32b71eSErnst Schwab 
39218caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3922eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3923eca2ebc7SMartin Sperl 
3924350de7ceSAndy Shevchenko 	/*
3925350de7ceSAndy Shevchenko 	 * If we're not using the legacy transfer method then we will
39260461a414SMark Brown 	 * try to transfer in the calling context so special case.
39270461a414SMark Brown 	 * This code would be less tricky if we could remove the
39280461a414SMark Brown 	 * support for driver implemented message queues.
39290461a414SMark Brown 	 */
39308caab75fSGeert Uytterhoeven 	if (ctlr->transfer == spi_queued_transfer) {
39318caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
39320461a414SMark Brown 
39330461a414SMark Brown 		trace_spi_message_submit(message);
39340461a414SMark Brown 
39350461a414SMark Brown 		status = __spi_queued_transfer(spi, message, false);
39360461a414SMark Brown 
39378caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
39380461a414SMark Brown 	} else {
3939cf32b71eSErnst Schwab 		status = spi_async_locked(spi, message);
39400461a414SMark Brown 	}
3941cf32b71eSErnst Schwab 
3942cf32b71eSErnst Schwab 	if (status == 0) {
3943350de7ceSAndy Shevchenko 		/* Push out the messages in the calling context if we can */
39448caab75fSGeert Uytterhoeven 		if (ctlr->transfer == spi_queued_transfer) {
39458caab75fSGeert Uytterhoeven 			SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3946eca2ebc7SMartin Sperl 						       spi_sync_immediate);
3947eca2ebc7SMartin Sperl 			SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3948eca2ebc7SMartin Sperl 						       spi_sync_immediate);
39498caab75fSGeert Uytterhoeven 			__spi_pump_messages(ctlr, false);
3950eca2ebc7SMartin Sperl 		}
39510461a414SMark Brown 
3952cf32b71eSErnst Schwab 		wait_for_completion(&done);
3953cf32b71eSErnst Schwab 		status = message->status;
3954cf32b71eSErnst Schwab 	}
3955cf32b71eSErnst Schwab 	message->context = NULL;
3956cf32b71eSErnst Schwab 	return status;
3957cf32b71eSErnst Schwab }
3958cf32b71eSErnst Schwab 
39598ae12a0dSDavid Brownell /**
39608ae12a0dSDavid Brownell  * spi_sync - blocking/synchronous SPI data transfers
39618ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
39628ae12a0dSDavid Brownell  * @message: describes the data transfers
396333e34dc6SDavid Brownell  * Context: can sleep
39648ae12a0dSDavid Brownell  *
39658ae12a0dSDavid Brownell  * This call may only be used from a context that may sleep.  The sleep
39668ae12a0dSDavid Brownell  * is non-interruptible, and has no timeout.  Low-overhead controller
39678ae12a0dSDavid Brownell  * drivers may DMA directly into and out of the message buffers.
39688ae12a0dSDavid Brownell  *
39698ae12a0dSDavid Brownell  * Note that the SPI device's chip select is active during the message,
39708ae12a0dSDavid Brownell  * and then is normally disabled between messages.  Drivers for some
39718ae12a0dSDavid Brownell  * frequently-used devices may want to minimize costs of selecting a chip,
39728ae12a0dSDavid Brownell  * by leaving it selected in anticipation that the next message will go
39738ae12a0dSDavid Brownell  * to the same chip.  (That may increase power usage.)
39748ae12a0dSDavid Brownell  *
39750c868461SDavid Brownell  * Also, the caller is guaranteeing that the memory associated with the
39760c868461SDavid Brownell  * message will not be freed before this call returns.
39770c868461SDavid Brownell  *
397897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
39798ae12a0dSDavid Brownell  */
39808ae12a0dSDavid Brownell int spi_sync(struct spi_device *spi, struct spi_message *message)
39818ae12a0dSDavid Brownell {
3982ef4d96ecSMark Brown 	int ret;
3983ef4d96ecSMark Brown 
39848caab75fSGeert Uytterhoeven 	mutex_lock(&spi->controller->bus_lock_mutex);
3985ef4d96ecSMark Brown 	ret = __spi_sync(spi, message);
39868caab75fSGeert Uytterhoeven 	mutex_unlock(&spi->controller->bus_lock_mutex);
3987ef4d96ecSMark Brown 
3988ef4d96ecSMark Brown 	return ret;
39898ae12a0dSDavid Brownell }
39908ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_sync);
39918ae12a0dSDavid Brownell 
3992cf32b71eSErnst Schwab /**
3993cf32b71eSErnst Schwab  * spi_sync_locked - version of spi_sync with exclusive bus usage
3994cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
3995cf32b71eSErnst Schwab  * @message: describes the data transfers
3996cf32b71eSErnst Schwab  * Context: can sleep
3997cf32b71eSErnst Schwab  *
3998cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3999cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.  Low-overhead controller
4000cf32b71eSErnst Schwab  * drivers may DMA directly into and out of the message buffers.
4001cf32b71eSErnst Schwab  *
4002cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
400325985edcSLucas De Marchi  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4004cf32b71eSErnst Schwab  * be released by a spi_bus_unlock call when the exclusive access is over.
4005cf32b71eSErnst Schwab  *
400697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4007cf32b71eSErnst Schwab  */
4008cf32b71eSErnst Schwab int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4009cf32b71eSErnst Schwab {
4010ef4d96ecSMark Brown 	return __spi_sync(spi, message);
4011cf32b71eSErnst Schwab }
4012cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_sync_locked);
4013cf32b71eSErnst Schwab 
4014cf32b71eSErnst Schwab /**
4015cf32b71eSErnst Schwab  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
40168caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that should be locked for exclusive bus access
4017cf32b71eSErnst Schwab  * Context: can sleep
4018cf32b71eSErnst Schwab  *
4019cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4020cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4021cf32b71eSErnst Schwab  *
4022cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
4023cf32b71eSErnst Schwab  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4024cf32b71eSErnst Schwab  * exclusive access is over. Data transfer must be done by spi_sync_locked
4025cf32b71eSErnst Schwab  * and spi_async_locked calls when the SPI bus lock is held.
4026cf32b71eSErnst Schwab  *
402797d56dc6SJavier Martinez Canillas  * Return: always zero.
4028cf32b71eSErnst Schwab  */
40298caab75fSGeert Uytterhoeven int spi_bus_lock(struct spi_controller *ctlr)
4030cf32b71eSErnst Schwab {
4031cf32b71eSErnst Schwab 	unsigned long flags;
4032cf32b71eSErnst Schwab 
40338caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->bus_lock_mutex);
4034cf32b71eSErnst Schwab 
40358caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
40368caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 1;
40378caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4038cf32b71eSErnst Schwab 
4039cf32b71eSErnst Schwab 	/* mutex remains locked until spi_bus_unlock is called */
4040cf32b71eSErnst Schwab 
4041cf32b71eSErnst Schwab 	return 0;
4042cf32b71eSErnst Schwab }
4043cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_lock);
4044cf32b71eSErnst Schwab 
4045cf32b71eSErnst Schwab /**
4046cf32b71eSErnst Schwab  * spi_bus_unlock - release the lock for exclusive SPI bus usage
40478caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that was locked for exclusive bus access
4048cf32b71eSErnst Schwab  * Context: can sleep
4049cf32b71eSErnst Schwab  *
4050cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4051cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4052cf32b71eSErnst Schwab  *
4053cf32b71eSErnst Schwab  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4054cf32b71eSErnst Schwab  * call.
4055cf32b71eSErnst Schwab  *
405697d56dc6SJavier Martinez Canillas  * Return: always zero.
4057cf32b71eSErnst Schwab  */
40588caab75fSGeert Uytterhoeven int spi_bus_unlock(struct spi_controller *ctlr)
4059cf32b71eSErnst Schwab {
40608caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
4061cf32b71eSErnst Schwab 
40628caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->bus_lock_mutex);
4063cf32b71eSErnst Schwab 
4064cf32b71eSErnst Schwab 	return 0;
4065cf32b71eSErnst Schwab }
4066cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_unlock);
4067cf32b71eSErnst Schwab 
4068a9948b61SDavid Brownell /* portable code must never pass more than 32 bytes */
4069a9948b61SDavid Brownell #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
40708ae12a0dSDavid Brownell 
40718ae12a0dSDavid Brownell static u8	*buf;
40728ae12a0dSDavid Brownell 
40738ae12a0dSDavid Brownell /**
40748ae12a0dSDavid Brownell  * spi_write_then_read - SPI synchronous write followed by read
40758ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
40768ae12a0dSDavid Brownell  * @txbuf: data to be written (need not be dma-safe)
40778ae12a0dSDavid Brownell  * @n_tx: size of txbuf, in bytes
407827570497SJiri Pirko  * @rxbuf: buffer into which data will be read (need not be dma-safe)
407927570497SJiri Pirko  * @n_rx: size of rxbuf, in bytes
408033e34dc6SDavid Brownell  * Context: can sleep
40818ae12a0dSDavid Brownell  *
40828ae12a0dSDavid Brownell  * This performs a half duplex MicroWire style transaction with the
40838ae12a0dSDavid Brownell  * device, sending txbuf and then reading rxbuf.  The return value
40848ae12a0dSDavid Brownell  * is zero for success, else a negative errno status code.
4085b885244eSDavid Brownell  * This call may only be used from a context that may sleep.
40868ae12a0dSDavid Brownell  *
4087c373643bSMark Brown  * Parameters to this routine are always copied using a small buffer.
408833e34dc6SDavid Brownell  * Performance-sensitive or bulk transfer code should instead use
40890c868461SDavid Brownell  * spi_{async,sync}() calls with dma-safe buffers.
409097d56dc6SJavier Martinez Canillas  *
409197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
40928ae12a0dSDavid Brownell  */
40938ae12a0dSDavid Brownell int spi_write_then_read(struct spi_device *spi,
40940c4a1590SMark Brown 		const void *txbuf, unsigned n_tx,
40950c4a1590SMark Brown 		void *rxbuf, unsigned n_rx)
40968ae12a0dSDavid Brownell {
4097068f4070SDavid Brownell 	static DEFINE_MUTEX(lock);
40988ae12a0dSDavid Brownell 
40998ae12a0dSDavid Brownell 	int			status;
41008ae12a0dSDavid Brownell 	struct spi_message	message;
4101bdff549eSDavid Brownell 	struct spi_transfer	x[2];
41028ae12a0dSDavid Brownell 	u8			*local_buf;
41038ae12a0dSDavid Brownell 
4104350de7ceSAndy Shevchenko 	/*
4105350de7ceSAndy Shevchenko 	 * Use preallocated DMA-safe buffer if we can. We can't avoid
4106b3a223eeSMark Brown 	 * copying here, (as a pure convenience thing), but we can
4107b3a223eeSMark Brown 	 * keep heap costs out of the hot path unless someone else is
4108b3a223eeSMark Brown 	 * using the pre-allocated buffer or the transfer is too large.
41098ae12a0dSDavid Brownell 	 */
4110b3a223eeSMark Brown 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
41112cd94c8aSMark Brown 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
41122cd94c8aSMark Brown 				    GFP_KERNEL | GFP_DMA);
4113b3a223eeSMark Brown 		if (!local_buf)
4114b3a223eeSMark Brown 			return -ENOMEM;
4115b3a223eeSMark Brown 	} else {
4116b3a223eeSMark Brown 		local_buf = buf;
4117b3a223eeSMark Brown 	}
41188ae12a0dSDavid Brownell 
41198275c642SVitaly Wool 	spi_message_init(&message);
41205fe5f05eSJingoo Han 	memset(x, 0, sizeof(x));
4121bdff549eSDavid Brownell 	if (n_tx) {
4122bdff549eSDavid Brownell 		x[0].len = n_tx;
4123bdff549eSDavid Brownell 		spi_message_add_tail(&x[0], &message);
4124bdff549eSDavid Brownell 	}
4125bdff549eSDavid Brownell 	if (n_rx) {
4126bdff549eSDavid Brownell 		x[1].len = n_rx;
4127bdff549eSDavid Brownell 		spi_message_add_tail(&x[1], &message);
4128bdff549eSDavid Brownell 	}
41298275c642SVitaly Wool 
41308ae12a0dSDavid Brownell 	memcpy(local_buf, txbuf, n_tx);
4131bdff549eSDavid Brownell 	x[0].tx_buf = local_buf;
4132bdff549eSDavid Brownell 	x[1].rx_buf = local_buf + n_tx;
41338ae12a0dSDavid Brownell 
41348ae12a0dSDavid Brownell 	/* do the i/o */
41358ae12a0dSDavid Brownell 	status = spi_sync(spi, &message);
41369b938b74SMarc Pignat 	if (status == 0)
4137bdff549eSDavid Brownell 		memcpy(rxbuf, x[1].rx_buf, n_rx);
41388ae12a0dSDavid Brownell 
4139bdff549eSDavid Brownell 	if (x[0].tx_buf == buf)
4140068f4070SDavid Brownell 		mutex_unlock(&lock);
41418ae12a0dSDavid Brownell 	else
41428ae12a0dSDavid Brownell 		kfree(local_buf);
41438ae12a0dSDavid Brownell 
41448ae12a0dSDavid Brownell 	return status;
41458ae12a0dSDavid Brownell }
41468ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_write_then_read);
41478ae12a0dSDavid Brownell 
41488ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
41498ae12a0dSDavid Brownell 
4150da21fde0SUwe Kleine-König #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4151ce79d54aSPantelis Antoniou /* must call put_device() when done with returned spi_device device */
4152da21fde0SUwe Kleine-König static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4153ce79d54aSPantelis Antoniou {
4154cfba5de9SSuzuki K Poulose 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4155cfba5de9SSuzuki K Poulose 
4156ce79d54aSPantelis Antoniou 	return dev ? to_spi_device(dev) : NULL;
4157ce79d54aSPantelis Antoniou }
4158ce79d54aSPantelis Antoniou 
41598caab75fSGeert Uytterhoeven /* the spi controllers are not using spi_bus, so we find it with another way */
41608caab75fSGeert Uytterhoeven static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4161ce79d54aSPantelis Antoniou {
4162ce79d54aSPantelis Antoniou 	struct device *dev;
4163ce79d54aSPantelis Antoniou 
4164cfba5de9SSuzuki K Poulose 	dev = class_find_device_by_of_node(&spi_master_class, node);
41656c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4166cfba5de9SSuzuki K Poulose 		dev = class_find_device_by_of_node(&spi_slave_class, node);
4167ce79d54aSPantelis Antoniou 	if (!dev)
4168ce79d54aSPantelis Antoniou 		return NULL;
4169ce79d54aSPantelis Antoniou 
4170ce79d54aSPantelis Antoniou 	/* reference got in class_find_device */
41718caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
4172ce79d54aSPantelis Antoniou }
4173ce79d54aSPantelis Antoniou 
4174ce79d54aSPantelis Antoniou static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4175ce79d54aSPantelis Antoniou 			 void *arg)
4176ce79d54aSPantelis Antoniou {
4177ce79d54aSPantelis Antoniou 	struct of_reconfig_data *rd = arg;
41788caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
4179ce79d54aSPantelis Antoniou 	struct spi_device *spi;
4180ce79d54aSPantelis Antoniou 
4181ce79d54aSPantelis Antoniou 	switch (of_reconfig_get_state_change(action, arg)) {
4182ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_ADD:
41838caab75fSGeert Uytterhoeven 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
41848caab75fSGeert Uytterhoeven 		if (ctlr == NULL)
4185ce79d54aSPantelis Antoniou 			return NOTIFY_OK;	/* not for us */
4186ce79d54aSPantelis Antoniou 
4187bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
41888caab75fSGeert Uytterhoeven 			put_device(&ctlr->dev);
4189bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4190bd6c1644SGeert Uytterhoeven 		}
4191bd6c1644SGeert Uytterhoeven 
41928caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, rd->dn);
41938caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
4194ce79d54aSPantelis Antoniou 
4195ce79d54aSPantelis Antoniou 		if (IS_ERR(spi)) {
419625c56c88SRob Herring 			pr_err("%s: failed to create for '%pOF'\n",
419725c56c88SRob Herring 					__func__, rd->dn);
4198e0af98a7SRalf Ramsauer 			of_node_clear_flag(rd->dn, OF_POPULATED);
4199ce79d54aSPantelis Antoniou 			return notifier_from_errno(PTR_ERR(spi));
4200ce79d54aSPantelis Antoniou 		}
4201ce79d54aSPantelis Antoniou 		break;
4202ce79d54aSPantelis Antoniou 
4203ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_REMOVE:
4204bd6c1644SGeert Uytterhoeven 		/* already depopulated? */
4205bd6c1644SGeert Uytterhoeven 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4206bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4207bd6c1644SGeert Uytterhoeven 
4208ce79d54aSPantelis Antoniou 		/* find our device by node */
4209ce79d54aSPantelis Antoniou 		spi = of_find_spi_device_by_node(rd->dn);
4210ce79d54aSPantelis Antoniou 		if (spi == NULL)
4211ce79d54aSPantelis Antoniou 			return NOTIFY_OK;	/* no? not meant for us */
4212ce79d54aSPantelis Antoniou 
4213ce79d54aSPantelis Antoniou 		/* unregister takes one ref away */
4214ce79d54aSPantelis Antoniou 		spi_unregister_device(spi);
4215ce79d54aSPantelis Antoniou 
4216ce79d54aSPantelis Antoniou 		/* and put the reference of the find */
4217ce79d54aSPantelis Antoniou 		put_device(&spi->dev);
4218ce79d54aSPantelis Antoniou 		break;
4219ce79d54aSPantelis Antoniou 	}
4220ce79d54aSPantelis Antoniou 
4221ce79d54aSPantelis Antoniou 	return NOTIFY_OK;
4222ce79d54aSPantelis Antoniou }
4223ce79d54aSPantelis Antoniou 
4224ce79d54aSPantelis Antoniou static struct notifier_block spi_of_notifier = {
4225ce79d54aSPantelis Antoniou 	.notifier_call = of_spi_notify,
4226ce79d54aSPantelis Antoniou };
4227ce79d54aSPantelis Antoniou #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4228ce79d54aSPantelis Antoniou extern struct notifier_block spi_of_notifier;
4229ce79d54aSPantelis Antoniou #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4230ce79d54aSPantelis Antoniou 
42317f24467fSOctavian Purdila #if IS_ENABLED(CONFIG_ACPI)
42328caab75fSGeert Uytterhoeven static int spi_acpi_controller_match(struct device *dev, const void *data)
42337f24467fSOctavian Purdila {
42347f24467fSOctavian Purdila 	return ACPI_COMPANION(dev->parent) == data;
42357f24467fSOctavian Purdila }
42367f24467fSOctavian Purdila 
42378caab75fSGeert Uytterhoeven static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
42387f24467fSOctavian Purdila {
42397f24467fSOctavian Purdila 	struct device *dev;
42407f24467fSOctavian Purdila 
42417f24467fSOctavian Purdila 	dev = class_find_device(&spi_master_class, NULL, adev,
42428caab75fSGeert Uytterhoeven 				spi_acpi_controller_match);
42436c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
42446c364062SGeert Uytterhoeven 		dev = class_find_device(&spi_slave_class, NULL, adev,
42458caab75fSGeert Uytterhoeven 					spi_acpi_controller_match);
42467f24467fSOctavian Purdila 	if (!dev)
42477f24467fSOctavian Purdila 		return NULL;
42487f24467fSOctavian Purdila 
42498caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
42507f24467fSOctavian Purdila }
42517f24467fSOctavian Purdila 
42527f24467fSOctavian Purdila static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
42537f24467fSOctavian Purdila {
42547f24467fSOctavian Purdila 	struct device *dev;
42557f24467fSOctavian Purdila 
425600500147SSuzuki K Poulose 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
42575b16668eSWolfram Sang 	return to_spi_device(dev);
42587f24467fSOctavian Purdila }
42597f24467fSOctavian Purdila 
42607f24467fSOctavian Purdila static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
42617f24467fSOctavian Purdila 			   void *arg)
42627f24467fSOctavian Purdila {
42637f24467fSOctavian Purdila 	struct acpi_device *adev = arg;
42648caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
42657f24467fSOctavian Purdila 	struct spi_device *spi;
42667f24467fSOctavian Purdila 
42677f24467fSOctavian Purdila 	switch (value) {
42687f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_ADD:
42698caab75fSGeert Uytterhoeven 		ctlr = acpi_spi_find_controller_by_adev(adev->parent);
42708caab75fSGeert Uytterhoeven 		if (!ctlr)
42717f24467fSOctavian Purdila 			break;
42727f24467fSOctavian Purdila 
42738caab75fSGeert Uytterhoeven 		acpi_register_spi_device(ctlr, adev);
42748caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
42757f24467fSOctavian Purdila 		break;
42767f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_REMOVE:
42777f24467fSOctavian Purdila 		if (!acpi_device_enumerated(adev))
42787f24467fSOctavian Purdila 			break;
42797f24467fSOctavian Purdila 
42807f24467fSOctavian Purdila 		spi = acpi_spi_find_device_by_adev(adev);
42817f24467fSOctavian Purdila 		if (!spi)
42827f24467fSOctavian Purdila 			break;
42837f24467fSOctavian Purdila 
42847f24467fSOctavian Purdila 		spi_unregister_device(spi);
42857f24467fSOctavian Purdila 		put_device(&spi->dev);
42867f24467fSOctavian Purdila 		break;
42877f24467fSOctavian Purdila 	}
42887f24467fSOctavian Purdila 
42897f24467fSOctavian Purdila 	return NOTIFY_OK;
42907f24467fSOctavian Purdila }
42917f24467fSOctavian Purdila 
42927f24467fSOctavian Purdila static struct notifier_block spi_acpi_notifier = {
42937f24467fSOctavian Purdila 	.notifier_call = acpi_spi_notify,
42947f24467fSOctavian Purdila };
42957f24467fSOctavian Purdila #else
42967f24467fSOctavian Purdila extern struct notifier_block spi_acpi_notifier;
42977f24467fSOctavian Purdila #endif
42987f24467fSOctavian Purdila 
42998ae12a0dSDavid Brownell static int __init spi_init(void)
43008ae12a0dSDavid Brownell {
4301b885244eSDavid Brownell 	int	status;
43028ae12a0dSDavid Brownell 
4303e94b1766SChristoph Lameter 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4304b885244eSDavid Brownell 	if (!buf) {
4305b885244eSDavid Brownell 		status = -ENOMEM;
4306b885244eSDavid Brownell 		goto err0;
43078ae12a0dSDavid Brownell 	}
4308b885244eSDavid Brownell 
4309b885244eSDavid Brownell 	status = bus_register(&spi_bus_type);
4310b885244eSDavid Brownell 	if (status < 0)
4311b885244eSDavid Brownell 		goto err1;
4312b885244eSDavid Brownell 
4313b885244eSDavid Brownell 	status = class_register(&spi_master_class);
4314b885244eSDavid Brownell 	if (status < 0)
4315b885244eSDavid Brownell 		goto err2;
4316ce79d54aSPantelis Antoniou 
43176c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
43186c364062SGeert Uytterhoeven 		status = class_register(&spi_slave_class);
43196c364062SGeert Uytterhoeven 		if (status < 0)
43206c364062SGeert Uytterhoeven 			goto err3;
43216c364062SGeert Uytterhoeven 	}
43226c364062SGeert Uytterhoeven 
43235267720eSFabio Estevam 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4324ce79d54aSPantelis Antoniou 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
43257f24467fSOctavian Purdila 	if (IS_ENABLED(CONFIG_ACPI))
43267f24467fSOctavian Purdila 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4327ce79d54aSPantelis Antoniou 
4328b885244eSDavid Brownell 	return 0;
4329b885244eSDavid Brownell 
43306c364062SGeert Uytterhoeven err3:
43316c364062SGeert Uytterhoeven 	class_unregister(&spi_master_class);
4332b885244eSDavid Brownell err2:
4333b885244eSDavid Brownell 	bus_unregister(&spi_bus_type);
4334b885244eSDavid Brownell err1:
4335b885244eSDavid Brownell 	kfree(buf);
4336b885244eSDavid Brownell 	buf = NULL;
4337b885244eSDavid Brownell err0:
4338b885244eSDavid Brownell 	return status;
4339b885244eSDavid Brownell }
4340b885244eSDavid Brownell 
4341350de7ceSAndy Shevchenko /*
4342350de7ceSAndy Shevchenko  * A board_info is normally registered in arch_initcall(),
4343350de7ceSAndy Shevchenko  * but even essential drivers wait till later.
4344b885244eSDavid Brownell  *
4345350de7ceSAndy Shevchenko  * REVISIT only boardinfo really needs static linking. The rest (device and
4346350de7ceSAndy Shevchenko  * driver registration) _could_ be dynamically linked (modular) ... Costs
4347b885244eSDavid Brownell  * include needing to have boardinfo data structures be much more public.
43488ae12a0dSDavid Brownell  */
4349673c0c00SDavid Brownell postcore_initcall(spi_init);
4350