xref: /linux/drivers/spi/spi.c (revision 5827b31d858e399e0ba9fbd33da7a39b31769e11)
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>
366598b91bSDavid Jander #include <linux/percpu.h>
378ae12a0dSDavid Brownell 
3856ec1978SMark Brown #define CREATE_TRACE_POINTS
3956ec1978SMark Brown #include <trace/events/spi.h>
40ca1438dcSArnd Bergmann EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
41ca1438dcSArnd Bergmann EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
429b61e302SSuniel Mahesh 
4346336966SBoris Brezillon #include "internals.h"
4446336966SBoris Brezillon 
459b61e302SSuniel Mahesh static DEFINE_IDR(spi_master_idr);
4656ec1978SMark Brown 
478ae12a0dSDavid Brownell static void spidev_release(struct device *dev)
488ae12a0dSDavid Brownell {
490ffa0285SHans-Peter Nilsson 	struct spi_device	*spi = to_spi_device(dev);
508ae12a0dSDavid Brownell 
518caab75fSGeert Uytterhoeven 	spi_controller_put(spi->controller);
525039563eSTrent Piepho 	kfree(spi->driver_override);
536598b91bSDavid Jander 	free_percpu(spi->pcpu_statistics);
5407a389feSRoman Tereshonkov 	kfree(spi);
558ae12a0dSDavid Brownell }
568ae12a0dSDavid Brownell 
578ae12a0dSDavid Brownell static ssize_t
588ae12a0dSDavid Brownell modalias_show(struct device *dev, struct device_attribute *a, char *buf)
598ae12a0dSDavid Brownell {
608ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
618c4ff6d0SZhang Rui 	int len;
628c4ff6d0SZhang Rui 
638c4ff6d0SZhang Rui 	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
648c4ff6d0SZhang Rui 	if (len != -ENODEV)
658c4ff6d0SZhang Rui 		return len;
668ae12a0dSDavid Brownell 
67d8e328b3SGrant Likely 	return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
688ae12a0dSDavid Brownell }
69aa7da564SGreg Kroah-Hartman static DEVICE_ATTR_RO(modalias);
708ae12a0dSDavid Brownell 
715039563eSTrent Piepho static ssize_t driver_override_store(struct device *dev,
725039563eSTrent Piepho 				     struct device_attribute *a,
735039563eSTrent Piepho 				     const char *buf, size_t count)
745039563eSTrent Piepho {
755039563eSTrent Piepho 	struct spi_device *spi = to_spi_device(dev);
7619368f0fSKrzysztof Kozlowski 	int ret;
775039563eSTrent Piepho 
7819368f0fSKrzysztof Kozlowski 	ret = driver_set_override(dev, &spi->driver_override, buf, count);
7919368f0fSKrzysztof Kozlowski 	if (ret)
8019368f0fSKrzysztof Kozlowski 		return ret;
815039563eSTrent Piepho 
825039563eSTrent Piepho 	return count;
835039563eSTrent Piepho }
845039563eSTrent Piepho 
855039563eSTrent Piepho static ssize_t driver_override_show(struct device *dev,
865039563eSTrent Piepho 				    struct device_attribute *a, char *buf)
875039563eSTrent Piepho {
885039563eSTrent Piepho 	const struct spi_device *spi = to_spi_device(dev);
895039563eSTrent Piepho 	ssize_t len;
905039563eSTrent Piepho 
915039563eSTrent Piepho 	device_lock(dev);
925039563eSTrent Piepho 	len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
935039563eSTrent Piepho 	device_unlock(dev);
945039563eSTrent Piepho 	return len;
955039563eSTrent Piepho }
965039563eSTrent Piepho static DEVICE_ATTR_RW(driver_override);
975039563eSTrent Piepho 
98d501cc4cSDavid Jander static struct spi_statistics __percpu *spi_alloc_pcpu_stats(struct device *dev)
996598b91bSDavid Jander {
1006598b91bSDavid Jander 	struct spi_statistics __percpu *pcpu_stats;
1016598b91bSDavid Jander 
1026598b91bSDavid Jander 	if (dev)
1036598b91bSDavid Jander 		pcpu_stats = devm_alloc_percpu(dev, struct spi_statistics);
1046598b91bSDavid Jander 	else
1056598b91bSDavid Jander 		pcpu_stats = alloc_percpu_gfp(struct spi_statistics, GFP_KERNEL);
1066598b91bSDavid Jander 
1076598b91bSDavid Jander 	if (pcpu_stats) {
1086598b91bSDavid Jander 		int cpu;
1096598b91bSDavid Jander 
1106598b91bSDavid Jander 		for_each_possible_cpu(cpu) {
1116598b91bSDavid Jander 			struct spi_statistics *stat;
1126598b91bSDavid Jander 
1136598b91bSDavid Jander 			stat = per_cpu_ptr(pcpu_stats, cpu);
1146598b91bSDavid Jander 			u64_stats_init(&stat->syncp);
1156598b91bSDavid Jander 		}
1166598b91bSDavid Jander 	}
1176598b91bSDavid Jander 	return pcpu_stats;
1186598b91bSDavid Jander }
1196598b91bSDavid Jander 
1206598b91bSDavid Jander #define spi_pcpu_stats_totalize(ret, in, field)				\
1216598b91bSDavid Jander do {									\
1226598b91bSDavid Jander 	int i;								\
1236598b91bSDavid Jander 	ret = 0;							\
1246598b91bSDavid Jander 	for_each_possible_cpu(i) {					\
1256598b91bSDavid Jander 		const struct spi_statistics *pcpu_stats;		\
1266598b91bSDavid Jander 		u64 inc;						\
1276598b91bSDavid Jander 		unsigned int start;					\
1286598b91bSDavid Jander 		pcpu_stats = per_cpu_ptr(in, i);			\
1296598b91bSDavid Jander 		do {							\
13093cc2559SThomas Gleixner 			start = u64_stats_fetch_begin(		\
1316598b91bSDavid Jander 					&pcpu_stats->syncp);		\
1326598b91bSDavid Jander 			inc = u64_stats_read(&pcpu_stats->field);	\
13393cc2559SThomas Gleixner 		} while (u64_stats_fetch_retry(			\
1346598b91bSDavid Jander 					&pcpu_stats->syncp, start));	\
1356598b91bSDavid Jander 		ret += inc;						\
1366598b91bSDavid Jander 	}								\
1376598b91bSDavid Jander } while (0)
1386598b91bSDavid Jander 
139eca2ebc7SMartin Sperl #define SPI_STATISTICS_ATTRS(field, file)				\
1408caab75fSGeert Uytterhoeven static ssize_t spi_controller_##field##_show(struct device *dev,	\
141eca2ebc7SMartin Sperl 					     struct device_attribute *attr, \
142eca2ebc7SMartin Sperl 					     char *buf)			\
143eca2ebc7SMartin Sperl {									\
1448caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev,			\
1458caab75fSGeert Uytterhoeven 					 struct spi_controller, dev);	\
1466598b91bSDavid Jander 	return spi_statistics_##field##_show(ctlr->pcpu_statistics, buf); \
147eca2ebc7SMartin Sperl }									\
1488caab75fSGeert Uytterhoeven static struct device_attribute dev_attr_spi_controller_##field = {	\
149ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
1508caab75fSGeert Uytterhoeven 	.show = spi_controller_##field##_show,				\
151eca2ebc7SMartin Sperl };									\
152eca2ebc7SMartin Sperl static ssize_t spi_device_##field##_show(struct device *dev,		\
153eca2ebc7SMartin Sperl 					 struct device_attribute *attr,	\
154eca2ebc7SMartin Sperl 					char *buf)			\
155eca2ebc7SMartin Sperl {									\
156d1eba93bSGeliang Tang 	struct spi_device *spi = to_spi_device(dev);			\
1576598b91bSDavid Jander 	return spi_statistics_##field##_show(spi->pcpu_statistics, buf); \
158eca2ebc7SMartin Sperl }									\
159eca2ebc7SMartin Sperl static struct device_attribute dev_attr_spi_device_##field = {		\
160ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
161eca2ebc7SMartin Sperl 	.show = spi_device_##field##_show,				\
162eca2ebc7SMartin Sperl }
163eca2ebc7SMartin Sperl 
1646598b91bSDavid Jander #define SPI_STATISTICS_SHOW_NAME(name, file, field)			\
165d501cc4cSDavid Jander static ssize_t spi_statistics_##name##_show(struct spi_statistics __percpu *stat, \
166eca2ebc7SMartin Sperl 					    char *buf)			\
167eca2ebc7SMartin Sperl {									\
168eca2ebc7SMartin Sperl 	ssize_t len;							\
1696598b91bSDavid Jander 	u64 val;							\
1706598b91bSDavid Jander 	spi_pcpu_stats_totalize(val, stat, field);			\
1716598b91bSDavid Jander 	len = sysfs_emit(buf, "%llu\n", val);				\
172eca2ebc7SMartin Sperl 	return len;							\
173eca2ebc7SMartin Sperl }									\
174eca2ebc7SMartin Sperl SPI_STATISTICS_ATTRS(name, file)
175eca2ebc7SMartin Sperl 
1766598b91bSDavid Jander #define SPI_STATISTICS_SHOW(field)					\
177eca2ebc7SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(field, __stringify(field),		\
1786598b91bSDavid Jander 				 field)
179eca2ebc7SMartin Sperl 
1806598b91bSDavid Jander SPI_STATISTICS_SHOW(messages);
1816598b91bSDavid Jander SPI_STATISTICS_SHOW(transfers);
1826598b91bSDavid Jander SPI_STATISTICS_SHOW(errors);
1836598b91bSDavid Jander SPI_STATISTICS_SHOW(timedout);
184eca2ebc7SMartin Sperl 
1856598b91bSDavid Jander SPI_STATISTICS_SHOW(spi_sync);
1866598b91bSDavid Jander SPI_STATISTICS_SHOW(spi_sync_immediate);
1876598b91bSDavid Jander SPI_STATISTICS_SHOW(spi_async);
188eca2ebc7SMartin Sperl 
1896598b91bSDavid Jander SPI_STATISTICS_SHOW(bytes);
1906598b91bSDavid Jander SPI_STATISTICS_SHOW(bytes_rx);
1916598b91bSDavid Jander SPI_STATISTICS_SHOW(bytes_tx);
192eca2ebc7SMartin Sperl 
1936b7bc061SMartin Sperl #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number)		\
1946b7bc061SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index,		\
1956b7bc061SMartin Sperl 				 "transfer_bytes_histo_" number,	\
1966598b91bSDavid Jander 				 transfer_bytes_histo[index])
1976b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(0,  "0-1");
1986b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(1,  "2-3");
1996b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(2,  "4-7");
2006b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(3,  "8-15");
2016b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(4,  "16-31");
2026b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(5,  "32-63");
2036b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(6,  "64-127");
2046b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(7,  "128-255");
2056b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(8,  "256-511");
2066b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(9,  "512-1023");
2076b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
2086b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
2096b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
2106b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
2116b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
2126b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
2136b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
2146b7bc061SMartin Sperl 
2156598b91bSDavid Jander SPI_STATISTICS_SHOW(transfers_split_maxsize);
216d9f12122SMartin Sperl 
217aa7da564SGreg Kroah-Hartman static struct attribute *spi_dev_attrs[] = {
218aa7da564SGreg Kroah-Hartman 	&dev_attr_modalias.attr,
2195039563eSTrent Piepho 	&dev_attr_driver_override.attr,
220aa7da564SGreg Kroah-Hartman 	NULL,
2218ae12a0dSDavid Brownell };
222eca2ebc7SMartin Sperl 
223eca2ebc7SMartin Sperl static const struct attribute_group spi_dev_group = {
224eca2ebc7SMartin Sperl 	.attrs  = spi_dev_attrs,
225eca2ebc7SMartin Sperl };
226eca2ebc7SMartin Sperl 
227eca2ebc7SMartin Sperl static struct attribute *spi_device_statistics_attrs[] = {
228eca2ebc7SMartin Sperl 	&dev_attr_spi_device_messages.attr,
229eca2ebc7SMartin Sperl 	&dev_attr_spi_device_transfers.attr,
230eca2ebc7SMartin Sperl 	&dev_attr_spi_device_errors.attr,
231eca2ebc7SMartin Sperl 	&dev_attr_spi_device_timedout.attr,
232eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync.attr,
233eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync_immediate.attr,
234eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_async.attr,
235eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes.attr,
236eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_rx.attr,
237eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_tx.attr,
2386b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo0.attr,
2396b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo1.attr,
2406b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo2.attr,
2416b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo3.attr,
2426b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo4.attr,
2436b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo5.attr,
2446b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo6.attr,
2456b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo7.attr,
2466b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo8.attr,
2476b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo9.attr,
2486b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo10.attr,
2496b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo11.attr,
2506b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo12.attr,
2516b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo13.attr,
2526b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo14.attr,
2536b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo15.attr,
2546b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo16.attr,
255d9f12122SMartin Sperl 	&dev_attr_spi_device_transfers_split_maxsize.attr,
256eca2ebc7SMartin Sperl 	NULL,
257eca2ebc7SMartin Sperl };
258eca2ebc7SMartin Sperl 
259eca2ebc7SMartin Sperl static const struct attribute_group spi_device_statistics_group = {
260eca2ebc7SMartin Sperl 	.name  = "statistics",
261eca2ebc7SMartin Sperl 	.attrs  = spi_device_statistics_attrs,
262eca2ebc7SMartin Sperl };
263eca2ebc7SMartin Sperl 
264eca2ebc7SMartin Sperl static const struct attribute_group *spi_dev_groups[] = {
265eca2ebc7SMartin Sperl 	&spi_dev_group,
266eca2ebc7SMartin Sperl 	&spi_device_statistics_group,
267eca2ebc7SMartin Sperl 	NULL,
268eca2ebc7SMartin Sperl };
269eca2ebc7SMartin Sperl 
2708caab75fSGeert Uytterhoeven static struct attribute *spi_controller_statistics_attrs[] = {
2718caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_messages.attr,
2728caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers.attr,
2738caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_errors.attr,
2748caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_timedout.attr,
2758caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync.attr,
2768caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync_immediate.attr,
2778caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_async.attr,
2788caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes.attr,
2798caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_rx.attr,
2808caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_tx.attr,
2818caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo0.attr,
2828caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo1.attr,
2838caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo2.attr,
2848caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo3.attr,
2858caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo4.attr,
2868caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo5.attr,
2878caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo6.attr,
2888caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo7.attr,
2898caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo8.attr,
2908caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo9.attr,
2918caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo10.attr,
2928caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo11.attr,
2938caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo12.attr,
2948caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo13.attr,
2958caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo14.attr,
2968caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo15.attr,
2978caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo16.attr,
2988caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers_split_maxsize.attr,
299eca2ebc7SMartin Sperl 	NULL,
300eca2ebc7SMartin Sperl };
301eca2ebc7SMartin Sperl 
3028caab75fSGeert Uytterhoeven static const struct attribute_group spi_controller_statistics_group = {
303eca2ebc7SMartin Sperl 	.name  = "statistics",
3048caab75fSGeert Uytterhoeven 	.attrs  = spi_controller_statistics_attrs,
305eca2ebc7SMartin Sperl };
306eca2ebc7SMartin Sperl 
307eca2ebc7SMartin Sperl static const struct attribute_group *spi_master_groups[] = {
3088caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
309eca2ebc7SMartin Sperl 	NULL,
310eca2ebc7SMartin Sperl };
311eca2ebc7SMartin Sperl 
312d501cc4cSDavid Jander static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
313eca2ebc7SMartin Sperl 					      struct spi_transfer *xfer,
3148caab75fSGeert Uytterhoeven 					      struct spi_controller *ctlr)
315eca2ebc7SMartin Sperl {
3166b7bc061SMartin Sperl 	int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
31767b9d641SDavid Jander 	struct spi_statistics *stats;
3186b7bc061SMartin Sperl 
3196b7bc061SMartin Sperl 	if (l2len < 0)
3206b7bc061SMartin Sperl 		l2len = 0;
321eca2ebc7SMartin Sperl 
32267b9d641SDavid Jander 	get_cpu();
32367b9d641SDavid Jander 	stats = this_cpu_ptr(pcpu_stats);
3246598b91bSDavid Jander 	u64_stats_update_begin(&stats->syncp);
325eca2ebc7SMartin Sperl 
3266598b91bSDavid Jander 	u64_stats_inc(&stats->transfers);
3276598b91bSDavid Jander 	u64_stats_inc(&stats->transfer_bytes_histo[l2len]);
328eca2ebc7SMartin Sperl 
3296598b91bSDavid Jander 	u64_stats_add(&stats->bytes, xfer->len);
330eca2ebc7SMartin Sperl 	if ((xfer->tx_buf) &&
3318caab75fSGeert Uytterhoeven 	    (xfer->tx_buf != ctlr->dummy_tx))
3326598b91bSDavid Jander 		u64_stats_add(&stats->bytes_tx, xfer->len);
333eca2ebc7SMartin Sperl 	if ((xfer->rx_buf) &&
3348caab75fSGeert Uytterhoeven 	    (xfer->rx_buf != ctlr->dummy_rx))
3356598b91bSDavid Jander 		u64_stats_add(&stats->bytes_rx, xfer->len);
336eca2ebc7SMartin Sperl 
3376598b91bSDavid Jander 	u64_stats_update_end(&stats->syncp);
33867b9d641SDavid Jander 	put_cpu();
339eca2ebc7SMartin Sperl }
3408ae12a0dSDavid Brownell 
341350de7ceSAndy Shevchenko /*
342350de7ceSAndy Shevchenko  * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
3438ae12a0dSDavid Brownell  * and the sysfs version makes coldplug work too.
3448ae12a0dSDavid Brownell  */
3453f076575SAndy Shevchenko static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
34675368bf6SAnton Vorontsov {
34775368bf6SAnton Vorontsov 	while (id->name[0]) {
3483f076575SAndy Shevchenko 		if (!strcmp(name, id->name))
34975368bf6SAnton Vorontsov 			return id;
35075368bf6SAnton Vorontsov 		id++;
35175368bf6SAnton Vorontsov 	}
35275368bf6SAnton Vorontsov 	return NULL;
35375368bf6SAnton Vorontsov }
35475368bf6SAnton Vorontsov 
35575368bf6SAnton Vorontsov const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
35675368bf6SAnton Vorontsov {
35775368bf6SAnton Vorontsov 	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
35875368bf6SAnton Vorontsov 
3593f076575SAndy Shevchenko 	return spi_match_id(sdrv->id_table, sdev->modalias);
36075368bf6SAnton Vorontsov }
36175368bf6SAnton Vorontsov EXPORT_SYMBOL_GPL(spi_get_device_id);
36275368bf6SAnton Vorontsov 
363aea672d0SAndy Shevchenko const void *spi_get_device_match_data(const struct spi_device *sdev)
364aea672d0SAndy Shevchenko {
365aea672d0SAndy Shevchenko 	const void *match;
366aea672d0SAndy Shevchenko 
367aea672d0SAndy Shevchenko 	match = device_get_match_data(&sdev->dev);
368aea672d0SAndy Shevchenko 	if (match)
369aea672d0SAndy Shevchenko 		return match;
370aea672d0SAndy Shevchenko 
371aea672d0SAndy Shevchenko 	return (const void *)spi_get_device_id(sdev)->driver_data;
372aea672d0SAndy Shevchenko }
373aea672d0SAndy Shevchenko EXPORT_SYMBOL_GPL(spi_get_device_match_data);
374aea672d0SAndy Shevchenko 
3758ae12a0dSDavid Brownell static int spi_match_device(struct device *dev, struct device_driver *drv)
3768ae12a0dSDavid Brownell {
3778ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
37875368bf6SAnton Vorontsov 	const struct spi_driver	*sdrv = to_spi_driver(drv);
37975368bf6SAnton Vorontsov 
3805039563eSTrent Piepho 	/* Check override first, and if set, only use the named driver */
3815039563eSTrent Piepho 	if (spi->driver_override)
3825039563eSTrent Piepho 		return strcmp(spi->driver_override, drv->name) == 0;
3835039563eSTrent Piepho 
3842b7a32f7SSinan Akman 	/* Attempt an OF style match */
3852b7a32f7SSinan Akman 	if (of_driver_match_device(dev, drv))
3862b7a32f7SSinan Akman 		return 1;
3872b7a32f7SSinan Akman 
38864bee4d2SMika Westerberg 	/* Then try ACPI */
38964bee4d2SMika Westerberg 	if (acpi_driver_match_device(dev, drv))
39064bee4d2SMika Westerberg 		return 1;
39164bee4d2SMika Westerberg 
39275368bf6SAnton Vorontsov 	if (sdrv->id_table)
3933f076575SAndy Shevchenko 		return !!spi_match_id(sdrv->id_table, spi->modalias);
3948ae12a0dSDavid Brownell 
39535f74fcaSKay Sievers 	return strcmp(spi->modalias, drv->name) == 0;
3968ae12a0dSDavid Brownell }
3978ae12a0dSDavid Brownell 
3987eff2e7aSKay Sievers static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
3998ae12a0dSDavid Brownell {
4008ae12a0dSDavid Brownell 	const struct spi_device		*spi = to_spi_device(dev);
4018c4ff6d0SZhang Rui 	int rc;
4028c4ff6d0SZhang Rui 
4038c4ff6d0SZhang Rui 	rc = acpi_device_uevent_modalias(dev, env);
4048c4ff6d0SZhang Rui 	if (rc != -ENODEV)
4058c4ff6d0SZhang Rui 		return rc;
4068ae12a0dSDavid Brownell 
4072856670fSAndy Shevchenko 	return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
4088ae12a0dSDavid Brownell }
4098ae12a0dSDavid Brownell 
4109db34ee6SUwe Kleine-König static int spi_probe(struct device *dev)
411b885244eSDavid Brownell {
412b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
41344af7927SJon Hunter 	struct spi_device		*spi = to_spi_device(dev);
41433cf00e5SMika Westerberg 	int ret;
415b885244eSDavid Brownell 
41686be408bSSylwester Nawrocki 	ret = of_clk_set_defaults(dev->of_node, false);
41786be408bSSylwester Nawrocki 	if (ret)
41886be408bSSylwester Nawrocki 		return ret;
41986be408bSSylwester Nawrocki 
42044af7927SJon Hunter 	if (dev->of_node) {
42144af7927SJon Hunter 		spi->irq = of_irq_get(dev->of_node, 0);
42244af7927SJon Hunter 		if (spi->irq == -EPROBE_DEFER)
42344af7927SJon Hunter 			return -EPROBE_DEFER;
42444af7927SJon Hunter 		if (spi->irq < 0)
42544af7927SJon Hunter 			spi->irq = 0;
42644af7927SJon Hunter 	}
42744af7927SJon Hunter 
428676e7c25SUlf Hansson 	ret = dev_pm_domain_attach(dev, true);
42971f277a7SUlf Hansson 	if (ret)
43071f277a7SUlf Hansson 		return ret;
43171f277a7SUlf Hansson 
432440408dbSUwe Kleine-König 	if (sdrv->probe) {
43344af7927SJon Hunter 		ret = sdrv->probe(spi);
43433cf00e5SMika Westerberg 		if (ret)
435676e7c25SUlf Hansson 			dev_pm_domain_detach(dev, true);
436440408dbSUwe Kleine-König 	}
43733cf00e5SMika Westerberg 
43833cf00e5SMika Westerberg 	return ret;
439b885244eSDavid Brownell }
440b885244eSDavid Brownell 
441fc7a6209SUwe Kleine-König static void spi_remove(struct device *dev)
442b885244eSDavid Brownell {
443b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
444b885244eSDavid Brownell 
445a0386bbaSUwe Kleine-König 	if (sdrv->remove)
446a0386bbaSUwe Kleine-König 		sdrv->remove(to_spi_device(dev));
4477795d475SUwe Kleine-König 
448676e7c25SUlf Hansson 	dev_pm_domain_detach(dev, true);
449b885244eSDavid Brownell }
450b885244eSDavid Brownell 
4519db34ee6SUwe Kleine-König static void spi_shutdown(struct device *dev)
452b885244eSDavid Brownell {
453a6f483b2SMarek Szyprowski 	if (dev->driver) {
454b885244eSDavid Brownell 		const struct spi_driver	*sdrv = to_spi_driver(dev->driver);
455b885244eSDavid Brownell 
4569db34ee6SUwe Kleine-König 		if (sdrv->shutdown)
457b885244eSDavid Brownell 			sdrv->shutdown(to_spi_device(dev));
458b885244eSDavid Brownell 	}
459a6f483b2SMarek Szyprowski }
460b885244eSDavid Brownell 
4619db34ee6SUwe Kleine-König struct bus_type spi_bus_type = {
4629db34ee6SUwe Kleine-König 	.name		= "spi",
4639db34ee6SUwe Kleine-König 	.dev_groups	= spi_dev_groups,
4649db34ee6SUwe Kleine-König 	.match		= spi_match_device,
4659db34ee6SUwe Kleine-König 	.uevent		= spi_uevent,
4669db34ee6SUwe Kleine-König 	.probe		= spi_probe,
4679db34ee6SUwe Kleine-König 	.remove		= spi_remove,
4689db34ee6SUwe Kleine-König 	.shutdown	= spi_shutdown,
4699db34ee6SUwe Kleine-König };
4709db34ee6SUwe Kleine-König EXPORT_SYMBOL_GPL(spi_bus_type);
4719db34ee6SUwe Kleine-König 
47233e34dc6SDavid Brownell /**
473ca5d2485SAndrew F. Davis  * __spi_register_driver - register a SPI driver
47488c9321dSThierry Reding  * @owner: owner module of the driver to register
47533e34dc6SDavid Brownell  * @sdrv: the driver to register
47633e34dc6SDavid Brownell  * Context: can sleep
47797d56dc6SJavier Martinez Canillas  *
47897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
47933e34dc6SDavid Brownell  */
480ca5d2485SAndrew F. Davis int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
481b885244eSDavid Brownell {
482ca5d2485SAndrew F. Davis 	sdrv->driver.owner = owner;
483b885244eSDavid Brownell 	sdrv->driver.bus = &spi_bus_type;
4845fa6863bSMark Brown 
4855fa6863bSMark Brown 	/*
4865fa6863bSMark Brown 	 * For Really Good Reasons we use spi: modaliases not of:
4875fa6863bSMark Brown 	 * modaliases for DT so module autoloading won't work if we
4885fa6863bSMark Brown 	 * don't have a spi_device_id as well as a compatible string.
4895fa6863bSMark Brown 	 */
4905fa6863bSMark Brown 	if (sdrv->driver.of_match_table) {
4915fa6863bSMark Brown 		const struct of_device_id *of_id;
4925fa6863bSMark Brown 
4935fa6863bSMark Brown 		for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
4945fa6863bSMark Brown 		     of_id++) {
4955fa6863bSMark Brown 			const char *of_name;
4965fa6863bSMark Brown 
4975fa6863bSMark Brown 			/* Strip off any vendor prefix */
4985fa6863bSMark Brown 			of_name = strnchr(of_id->compatible,
4995fa6863bSMark Brown 					  sizeof(of_id->compatible), ',');
5005fa6863bSMark Brown 			if (of_name)
5015fa6863bSMark Brown 				of_name++;
5025fa6863bSMark Brown 			else
5035fa6863bSMark Brown 				of_name = of_id->compatible;
5045fa6863bSMark Brown 
5055fa6863bSMark Brown 			if (sdrv->id_table) {
5065fa6863bSMark Brown 				const struct spi_device_id *spi_id;
5075fa6863bSMark Brown 
5083f076575SAndy Shevchenko 				spi_id = spi_match_id(sdrv->id_table, of_name);
509b79332efSAndy Shevchenko 				if (spi_id)
5105fa6863bSMark Brown 					continue;
5115fa6863bSMark Brown 			} else {
5125fa6863bSMark Brown 				if (strcmp(sdrv->driver.name, of_name) == 0)
5135fa6863bSMark Brown 					continue;
5145fa6863bSMark Brown 			}
5155fa6863bSMark Brown 
5165fa6863bSMark Brown 			pr_warn("SPI driver %s has no spi_device_id for %s\n",
5175fa6863bSMark Brown 				sdrv->driver.name, of_id->compatible);
5185fa6863bSMark Brown 		}
5195fa6863bSMark Brown 	}
5205fa6863bSMark Brown 
521b885244eSDavid Brownell 	return driver_register(&sdrv->driver);
522b885244eSDavid Brownell }
523ca5d2485SAndrew F. Davis EXPORT_SYMBOL_GPL(__spi_register_driver);
524b885244eSDavid Brownell 
5258ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
5268ae12a0dSDavid Brownell 
527350de7ceSAndy Shevchenko /*
528350de7ceSAndy Shevchenko  * SPI devices should normally not be created by SPI device drivers; that
5298caab75fSGeert Uytterhoeven  * would make them board-specific.  Similarly with SPI controller drivers.
5308ae12a0dSDavid Brownell  * Device registration normally goes into like arch/.../mach.../board-YYY.c
5318ae12a0dSDavid Brownell  * with other readonly (flashable) information about mainboard devices.
5328ae12a0dSDavid Brownell  */
5338ae12a0dSDavid Brownell 
5348ae12a0dSDavid Brownell struct boardinfo {
5358ae12a0dSDavid Brownell 	struct list_head	list;
5362b9603a0SFeng Tang 	struct spi_board_info	board_info;
5378ae12a0dSDavid Brownell };
5388ae12a0dSDavid Brownell 
5398ae12a0dSDavid Brownell static LIST_HEAD(board_list);
5408caab75fSGeert Uytterhoeven static LIST_HEAD(spi_controller_list);
5412b9603a0SFeng Tang 
5422b9603a0SFeng Tang /*
543be73e323SAndy Shevchenko  * Used to protect add/del operation for board_info list and
544350de7ceSAndy Shevchenko  * spi_controller list, and their matching process also used
545350de7ceSAndy Shevchenko  * to protect object of type struct idr.
5462b9603a0SFeng Tang  */
54794040828SMatthias Kaehlcke static DEFINE_MUTEX(board_lock);
5488ae12a0dSDavid Brownell 
549dc87c98eSGrant Likely /**
550dc87c98eSGrant Likely  * spi_alloc_device - Allocate a new SPI device
5518caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
552dc87c98eSGrant Likely  * Context: can sleep
553dc87c98eSGrant Likely  *
554dc87c98eSGrant Likely  * Allows a driver to allocate and initialize a spi_device without
555dc87c98eSGrant Likely  * registering it immediately.  This allows a driver to directly
556dc87c98eSGrant Likely  * fill the spi_device with device parameters before calling
557dc87c98eSGrant Likely  * spi_add_device() on it.
558dc87c98eSGrant Likely  *
559dc87c98eSGrant Likely  * Caller is responsible to call spi_add_device() on the returned
5608caab75fSGeert Uytterhoeven  * spi_device structure to add it to the SPI controller.  If the caller
561dc87c98eSGrant Likely  * needs to discard the spi_device without adding it, then it should
562dc87c98eSGrant Likely  * call spi_dev_put() on it.
563dc87c98eSGrant Likely  *
56497d56dc6SJavier Martinez Canillas  * Return: a pointer to the new device, or NULL.
565dc87c98eSGrant Likely  */
566e3dc1399SStefan Binding struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
567dc87c98eSGrant Likely {
568dc87c98eSGrant Likely 	struct spi_device	*spi;
569dc87c98eSGrant Likely 
5708caab75fSGeert Uytterhoeven 	if (!spi_controller_get(ctlr))
571dc87c98eSGrant Likely 		return NULL;
572dc87c98eSGrant Likely 
5735fe5f05eSJingoo Han 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
574dc87c98eSGrant Likely 	if (!spi) {
5758caab75fSGeert Uytterhoeven 		spi_controller_put(ctlr);
576dc87c98eSGrant Likely 		return NULL;
577dc87c98eSGrant Likely 	}
578dc87c98eSGrant Likely 
5796598b91bSDavid Jander 	spi->pcpu_statistics = spi_alloc_pcpu_stats(NULL);
5806598b91bSDavid Jander 	if (!spi->pcpu_statistics) {
5816598b91bSDavid Jander 		kfree(spi);
5826598b91bSDavid Jander 		spi_controller_put(ctlr);
5836598b91bSDavid Jander 		return NULL;
5846598b91bSDavid Jander 	}
5856598b91bSDavid Jander 
5868caab75fSGeert Uytterhoeven 	spi->master = spi->controller = ctlr;
5878caab75fSGeert Uytterhoeven 	spi->dev.parent = &ctlr->dev;
588dc87c98eSGrant Likely 	spi->dev.bus = &spi_bus_type;
589dc87c98eSGrant Likely 	spi->dev.release = spidev_release;
590ea235786SJohn Garry 	spi->mode = ctlr->buswidth_override_bits;
591eca2ebc7SMartin Sperl 
592dc87c98eSGrant Likely 	device_initialize(&spi->dev);
593dc87c98eSGrant Likely 	return spi;
594dc87c98eSGrant Likely }
595e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_alloc_device);
596dc87c98eSGrant Likely 
597e13ac47bSJarkko Nikula static void spi_dev_set_name(struct spi_device *spi)
598e13ac47bSJarkko Nikula {
599e13ac47bSJarkko Nikula 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
600e13ac47bSJarkko Nikula 
601e13ac47bSJarkko Nikula 	if (adev) {
602e13ac47bSJarkko Nikula 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
603e13ac47bSJarkko Nikula 		return;
604e13ac47bSJarkko Nikula 	}
605e13ac47bSJarkko Nikula 
6068caab75fSGeert Uytterhoeven 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
607e13ac47bSJarkko Nikula 		     spi->chip_select);
608e13ac47bSJarkko Nikula }
609e13ac47bSJarkko Nikula 
610b6fb8d3aSMika Westerberg static int spi_dev_check(struct device *dev, void *data)
611b6fb8d3aSMika Westerberg {
612b6fb8d3aSMika Westerberg 	struct spi_device *spi = to_spi_device(dev);
613b6fb8d3aSMika Westerberg 	struct spi_device *new_spi = data;
614b6fb8d3aSMika Westerberg 
6158caab75fSGeert Uytterhoeven 	if (spi->controller == new_spi->controller &&
616b6fb8d3aSMika Westerberg 	    spi->chip_select == new_spi->chip_select)
617b6fb8d3aSMika Westerberg 		return -EBUSY;
618b6fb8d3aSMika Westerberg 	return 0;
619b6fb8d3aSMika Westerberg }
620b6fb8d3aSMika Westerberg 
621c7299feaSSaravana Kannan static void spi_cleanup(struct spi_device *spi)
622c7299feaSSaravana Kannan {
623c7299feaSSaravana Kannan 	if (spi->controller->cleanup)
624c7299feaSSaravana Kannan 		spi->controller->cleanup(spi);
625c7299feaSSaravana Kannan }
626c7299feaSSaravana Kannan 
6270c79378cSSebastian Reichel static int __spi_add_device(struct spi_device *spi)
6280c79378cSSebastian Reichel {
6290c79378cSSebastian Reichel 	struct spi_controller *ctlr = spi->controller;
6300c79378cSSebastian Reichel 	struct device *dev = ctlr->dev.parent;
6310c79378cSSebastian Reichel 	int status;
6320c79378cSSebastian Reichel 
6336bfb15f3SUwe Kleine-König 	/*
6346bfb15f3SUwe Kleine-König 	 * We need to make sure there's no other device with this
6356bfb15f3SUwe Kleine-König 	 * chipselect **BEFORE** we call setup(), else we'll trash
6366bfb15f3SUwe Kleine-König 	 * its configuration.
6376bfb15f3SUwe Kleine-König 	 */
6380c79378cSSebastian Reichel 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
6390c79378cSSebastian Reichel 	if (status) {
6400c79378cSSebastian Reichel 		dev_err(dev, "chipselect %d already in use\n",
6410c79378cSSebastian Reichel 				spi->chip_select);
6420c79378cSSebastian Reichel 		return status;
6430c79378cSSebastian Reichel 	}
6440c79378cSSebastian Reichel 
6450c79378cSSebastian Reichel 	/* Controller may unregister concurrently */
6460c79378cSSebastian Reichel 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
6470c79378cSSebastian Reichel 	    !device_is_registered(&ctlr->dev)) {
6480c79378cSSebastian Reichel 		return -ENODEV;
6490c79378cSSebastian Reichel 	}
6500c79378cSSebastian Reichel 
6510c79378cSSebastian Reichel 	if (ctlr->cs_gpiods)
6520c79378cSSebastian Reichel 		spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
6530c79378cSSebastian Reichel 
654350de7ceSAndy Shevchenko 	/*
655350de7ceSAndy Shevchenko 	 * Drivers may modify this initial i/o setup, but will
6560c79378cSSebastian Reichel 	 * normally rely on the device being setup.  Devices
6570c79378cSSebastian Reichel 	 * using SPI_CS_HIGH can't coexist well otherwise...
6580c79378cSSebastian Reichel 	 */
6590c79378cSSebastian Reichel 	status = spi_setup(spi);
6600c79378cSSebastian Reichel 	if (status < 0) {
6610c79378cSSebastian Reichel 		dev_err(dev, "can't setup %s, status %d\n",
6620c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
6630c79378cSSebastian Reichel 		return status;
6640c79378cSSebastian Reichel 	}
6650c79378cSSebastian Reichel 
6660c79378cSSebastian Reichel 	/* Device may be bound to an active driver when this returns */
6670c79378cSSebastian Reichel 	status = device_add(&spi->dev);
6680c79378cSSebastian Reichel 	if (status < 0) {
6690c79378cSSebastian Reichel 		dev_err(dev, "can't add %s, status %d\n",
6700c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
6710c79378cSSebastian Reichel 		spi_cleanup(spi);
6720c79378cSSebastian Reichel 	} else {
6730c79378cSSebastian Reichel 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
6740c79378cSSebastian Reichel 	}
6750c79378cSSebastian Reichel 
6760c79378cSSebastian Reichel 	return status;
6770c79378cSSebastian Reichel }
6780c79378cSSebastian Reichel 
679dc87c98eSGrant Likely /**
680dc87c98eSGrant Likely  * spi_add_device - Add spi_device allocated with spi_alloc_device
681dc87c98eSGrant Likely  * @spi: spi_device to register
682dc87c98eSGrant Likely  *
683dc87c98eSGrant Likely  * Companion function to spi_alloc_device.  Devices allocated with
684dc87c98eSGrant Likely  * spi_alloc_device can be added onto the spi bus with this function.
685dc87c98eSGrant Likely  *
68697d56dc6SJavier Martinez Canillas  * Return: 0 on success; negative errno on failure
687dc87c98eSGrant Likely  */
688e3dc1399SStefan Binding int spi_add_device(struct spi_device *spi)
689dc87c98eSGrant Likely {
6908caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
6918caab75fSGeert Uytterhoeven 	struct device *dev = ctlr->dev.parent;
692dc87c98eSGrant Likely 	int status;
693dc87c98eSGrant Likely 
694dc87c98eSGrant Likely 	/* Chipselects are numbered 0..max; validate. */
6958caab75fSGeert Uytterhoeven 	if (spi->chip_select >= ctlr->num_chipselect) {
6968caab75fSGeert Uytterhoeven 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
6978caab75fSGeert Uytterhoeven 			ctlr->num_chipselect);
698dc87c98eSGrant Likely 		return -EINVAL;
699dc87c98eSGrant Likely 	}
700dc87c98eSGrant Likely 
701dc87c98eSGrant Likely 	/* Set the bus ID string */
702e13ac47bSJarkko Nikula 	spi_dev_set_name(spi);
703e48880e0SDavid Brownell 
7046098475dSMark Brown 	mutex_lock(&ctlr->add_lock);
7050c79378cSSebastian Reichel 	status = __spi_add_device(spi);
7066098475dSMark Brown 	mutex_unlock(&ctlr->add_lock);
707e48880e0SDavid Brownell 	return status;
708dc87c98eSGrant Likely }
709e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_add_device);
7108ae12a0dSDavid Brownell 
7110c79378cSSebastian Reichel static int spi_add_device_locked(struct spi_device *spi)
7120c79378cSSebastian Reichel {
7130c79378cSSebastian Reichel 	struct spi_controller *ctlr = spi->controller;
7140c79378cSSebastian Reichel 	struct device *dev = ctlr->dev.parent;
7150c79378cSSebastian Reichel 
7160c79378cSSebastian Reichel 	/* Chipselects are numbered 0..max; validate. */
7170c79378cSSebastian Reichel 	if (spi->chip_select >= ctlr->num_chipselect) {
7180c79378cSSebastian Reichel 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
7190c79378cSSebastian Reichel 			ctlr->num_chipselect);
7200c79378cSSebastian Reichel 		return -EINVAL;
7210c79378cSSebastian Reichel 	}
7220c79378cSSebastian Reichel 
7230c79378cSSebastian Reichel 	/* Set the bus ID string */
7240c79378cSSebastian Reichel 	spi_dev_set_name(spi);
7250c79378cSSebastian Reichel 
7266098475dSMark Brown 	WARN_ON(!mutex_is_locked(&ctlr->add_lock));
7270c79378cSSebastian Reichel 	return __spi_add_device(spi);
7280c79378cSSebastian Reichel }
7290c79378cSSebastian Reichel 
73033e34dc6SDavid Brownell /**
73133e34dc6SDavid Brownell  * spi_new_device - instantiate one new SPI device
7328caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
73333e34dc6SDavid Brownell  * @chip: Describes the SPI device
73433e34dc6SDavid Brownell  * Context: can sleep
73533e34dc6SDavid Brownell  *
73633e34dc6SDavid Brownell  * On typical mainboards, this is purely internal; and it's not needed
7378ae12a0dSDavid Brownell  * after board init creates the hard-wired devices.  Some development
7388ae12a0dSDavid Brownell  * platforms may not be able to use spi_register_board_info though, and
7398ae12a0dSDavid Brownell  * this is exported so that for example a USB or parport based adapter
7408ae12a0dSDavid Brownell  * driver could add devices (which it would learn about out-of-band).
741082c8cb4SDavid Brownell  *
74297d56dc6SJavier Martinez Canillas  * Return: the new device, or NULL.
7438ae12a0dSDavid Brownell  */
7448caab75fSGeert Uytterhoeven struct spi_device *spi_new_device(struct spi_controller *ctlr,
745e9d5a461SAdrian Bunk 				  struct spi_board_info *chip)
7468ae12a0dSDavid Brownell {
7478ae12a0dSDavid Brownell 	struct spi_device	*proxy;
7488ae12a0dSDavid Brownell 	int			status;
7498ae12a0dSDavid Brownell 
750350de7ceSAndy Shevchenko 	/*
751350de7ceSAndy Shevchenko 	 * NOTE:  caller did any chip->bus_num checks necessary.
752082c8cb4SDavid Brownell 	 *
753082c8cb4SDavid Brownell 	 * Also, unless we change the return value convention to use
754082c8cb4SDavid Brownell 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
755082c8cb4SDavid Brownell 	 * suggests syslogged diagnostics are best here (ugh).
756082c8cb4SDavid Brownell 	 */
757082c8cb4SDavid Brownell 
7588caab75fSGeert Uytterhoeven 	proxy = spi_alloc_device(ctlr);
759dc87c98eSGrant Likely 	if (!proxy)
7608ae12a0dSDavid Brownell 		return NULL;
7618ae12a0dSDavid Brownell 
762102eb975SGrant Likely 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
763102eb975SGrant Likely 
7648ae12a0dSDavid Brownell 	proxy->chip_select = chip->chip_select;
7658ae12a0dSDavid Brownell 	proxy->max_speed_hz = chip->max_speed_hz;
766980a01c9SDavid Brownell 	proxy->mode = chip->mode;
7678ae12a0dSDavid Brownell 	proxy->irq = chip->irq;
76851e99de5SWolfram Sang 	strscpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
7698ae12a0dSDavid Brownell 	proxy->dev.platform_data = (void *) chip->platform_data;
7708ae12a0dSDavid Brownell 	proxy->controller_data = chip->controller_data;
7718ae12a0dSDavid Brownell 	proxy->controller_state = NULL;
7728ae12a0dSDavid Brownell 
77347afc77bSHeikki Krogerus 	if (chip->swnode) {
77447afc77bSHeikki Krogerus 		status = device_add_software_node(&proxy->dev, chip->swnode);
775826cf175SDmitry Torokhov 		if (status) {
7769d902c2aSColin Ian King 			dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
777826cf175SDmitry Torokhov 				chip->modalias, status);
778826cf175SDmitry Torokhov 			goto err_dev_put;
779826cf175SDmitry Torokhov 		}
7808ae12a0dSDavid Brownell 	}
781dc87c98eSGrant Likely 
782826cf175SDmitry Torokhov 	status = spi_add_device(proxy);
783826cf175SDmitry Torokhov 	if (status < 0)
784df41a5daSHeikki Krogerus 		goto err_dev_put;
785826cf175SDmitry Torokhov 
786dc87c98eSGrant Likely 	return proxy;
787826cf175SDmitry Torokhov 
788826cf175SDmitry Torokhov err_dev_put:
789df41a5daSHeikki Krogerus 	device_remove_software_node(&proxy->dev);
790826cf175SDmitry Torokhov 	spi_dev_put(proxy);
791826cf175SDmitry Torokhov 	return NULL;
792dc87c98eSGrant Likely }
7938ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_new_device);
7948ae12a0dSDavid Brownell 
7953b1884c2SGeert Uytterhoeven /**
7963b1884c2SGeert Uytterhoeven  * spi_unregister_device - unregister a single SPI device
7973b1884c2SGeert Uytterhoeven  * @spi: spi_device to unregister
7983b1884c2SGeert Uytterhoeven  *
7993b1884c2SGeert Uytterhoeven  * Start making the passed SPI device vanish. Normally this would be handled
8008caab75fSGeert Uytterhoeven  * by spi_unregister_controller().
8013b1884c2SGeert Uytterhoeven  */
8023b1884c2SGeert Uytterhoeven void spi_unregister_device(struct spi_device *spi)
8033b1884c2SGeert Uytterhoeven {
804bd6c1644SGeert Uytterhoeven 	if (!spi)
805bd6c1644SGeert Uytterhoeven 		return;
806bd6c1644SGeert Uytterhoeven 
8078324147fSJohan Hovold 	if (spi->dev.of_node) {
808bd6c1644SGeert Uytterhoeven 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
8098324147fSJohan Hovold 		of_node_put(spi->dev.of_node);
8108324147fSJohan Hovold 	}
8117f24467fSOctavian Purdila 	if (ACPI_COMPANION(&spi->dev))
8127f24467fSOctavian Purdila 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
81347afc77bSHeikki Krogerus 	device_remove_software_node(&spi->dev);
81427e7db56SSaravana Kannan 	device_del(&spi->dev);
81527e7db56SSaravana Kannan 	spi_cleanup(spi);
81627e7db56SSaravana Kannan 	put_device(&spi->dev);
8173b1884c2SGeert Uytterhoeven }
8183b1884c2SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_device);
8193b1884c2SGeert Uytterhoeven 
8208caab75fSGeert Uytterhoeven static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
8212b9603a0SFeng Tang 					      struct spi_board_info *bi)
8222b9603a0SFeng Tang {
8232b9603a0SFeng Tang 	struct spi_device *dev;
8242b9603a0SFeng Tang 
8258caab75fSGeert Uytterhoeven 	if (ctlr->bus_num != bi->bus_num)
8262b9603a0SFeng Tang 		return;
8272b9603a0SFeng Tang 
8288caab75fSGeert Uytterhoeven 	dev = spi_new_device(ctlr, bi);
8292b9603a0SFeng Tang 	if (!dev)
8308caab75fSGeert Uytterhoeven 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
8312b9603a0SFeng Tang 			bi->modalias);
8322b9603a0SFeng Tang }
8332b9603a0SFeng Tang 
83433e34dc6SDavid Brownell /**
83533e34dc6SDavid Brownell  * spi_register_board_info - register SPI devices for a given board
83633e34dc6SDavid Brownell  * @info: array of chip descriptors
83733e34dc6SDavid Brownell  * @n: how many descriptors are provided
83833e34dc6SDavid Brownell  * Context: can sleep
83933e34dc6SDavid Brownell  *
8408ae12a0dSDavid Brownell  * Board-specific early init code calls this (probably during arch_initcall)
8418ae12a0dSDavid Brownell  * with segments of the SPI device table.  Any device nodes are created later,
8428ae12a0dSDavid Brownell  * after the relevant parent SPI controller (bus_num) is defined.  We keep
8438ae12a0dSDavid Brownell  * this table of devices forever, so that reloading a controller driver will
8448ae12a0dSDavid Brownell  * not make Linux forget about these hard-wired devices.
8458ae12a0dSDavid Brownell  *
8468ae12a0dSDavid Brownell  * Other code can also call this, e.g. a particular add-on board might provide
8478ae12a0dSDavid Brownell  * SPI devices through its expansion connector, so code initializing that board
8488ae12a0dSDavid Brownell  * would naturally declare its SPI devices.
8498ae12a0dSDavid Brownell  *
8508ae12a0dSDavid Brownell  * The board info passed can safely be __initdata ... but be careful of
8518ae12a0dSDavid Brownell  * any embedded pointers (platform_data, etc), they're copied as-is.
85297d56dc6SJavier Martinez Canillas  *
85397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
8548ae12a0dSDavid Brownell  */
855fd4a319bSGrant Likely int spi_register_board_info(struct spi_board_info const *info, unsigned n)
8568ae12a0dSDavid Brownell {
8578ae12a0dSDavid Brownell 	struct boardinfo *bi;
8582b9603a0SFeng Tang 	int i;
8598ae12a0dSDavid Brownell 
860c7908a37SXiubo Li 	if (!n)
861f974cf57SDmitry Torokhov 		return 0;
862c7908a37SXiubo Li 
863f9bdb7fdSMarkus Elfring 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
8648ae12a0dSDavid Brownell 	if (!bi)
8658ae12a0dSDavid Brownell 		return -ENOMEM;
8668ae12a0dSDavid Brownell 
8672b9603a0SFeng Tang 	for (i = 0; i < n; i++, bi++, info++) {
8688caab75fSGeert Uytterhoeven 		struct spi_controller *ctlr;
8692b9603a0SFeng Tang 
8702b9603a0SFeng Tang 		memcpy(&bi->board_info, info, sizeof(*info));
871826cf175SDmitry Torokhov 
87294040828SMatthias Kaehlcke 		mutex_lock(&board_lock);
8738ae12a0dSDavid Brownell 		list_add_tail(&bi->list, &board_list);
8748caab75fSGeert Uytterhoeven 		list_for_each_entry(ctlr, &spi_controller_list, list)
8758caab75fSGeert Uytterhoeven 			spi_match_controller_to_boardinfo(ctlr,
8768caab75fSGeert Uytterhoeven 							  &bi->board_info);
87794040828SMatthias Kaehlcke 		mutex_unlock(&board_lock);
8782b9603a0SFeng Tang 	}
8792b9603a0SFeng Tang 
8808ae12a0dSDavid Brownell 	return 0;
8818ae12a0dSDavid Brownell }
8828ae12a0dSDavid Brownell 
8838ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
8848ae12a0dSDavid Brownell 
885fb51601bSUwe Kleine-König /* Core methods for SPI resource management */
886fb51601bSUwe Kleine-König 
887fb51601bSUwe Kleine-König /**
888fb51601bSUwe Kleine-König  * spi_res_alloc - allocate a spi resource that is life-cycle managed
889fb51601bSUwe Kleine-König  *                 during the processing of a spi_message while using
890fb51601bSUwe Kleine-König  *                 spi_transfer_one
891fb51601bSUwe Kleine-König  * @spi:     the spi device for which we allocate memory
892fb51601bSUwe Kleine-König  * @release: the release code to execute for this resource
893fb51601bSUwe Kleine-König  * @size:    size to alloc and return
894fb51601bSUwe Kleine-König  * @gfp:     GFP allocation flags
895fb51601bSUwe Kleine-König  *
896fb51601bSUwe Kleine-König  * Return: the pointer to the allocated data
897fb51601bSUwe Kleine-König  *
898fb51601bSUwe Kleine-König  * This may get enhanced in the future to allocate from a memory pool
899fb51601bSUwe Kleine-König  * of the @spi_device or @spi_controller to avoid repeated allocations.
900fb51601bSUwe Kleine-König  */
901da21fde0SUwe Kleine-König static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
902fb51601bSUwe Kleine-König 			   size_t size, gfp_t gfp)
903fb51601bSUwe Kleine-König {
904fb51601bSUwe Kleine-König 	struct spi_res *sres;
905fb51601bSUwe Kleine-König 
906fb51601bSUwe Kleine-König 	sres = kzalloc(sizeof(*sres) + size, gfp);
907fb51601bSUwe Kleine-König 	if (!sres)
908fb51601bSUwe Kleine-König 		return NULL;
909fb51601bSUwe Kleine-König 
910fb51601bSUwe Kleine-König 	INIT_LIST_HEAD(&sres->entry);
911fb51601bSUwe Kleine-König 	sres->release = release;
912fb51601bSUwe Kleine-König 
913fb51601bSUwe Kleine-König 	return sres->data;
914fb51601bSUwe Kleine-König }
915fb51601bSUwe Kleine-König 
916fb51601bSUwe Kleine-König /**
917fb51601bSUwe Kleine-König  * spi_res_free - free an spi resource
918fb51601bSUwe Kleine-König  * @res: pointer to the custom data of a resource
919fb51601bSUwe Kleine-König  */
920da21fde0SUwe Kleine-König static void spi_res_free(void *res)
921fb51601bSUwe Kleine-König {
922fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
923fb51601bSUwe Kleine-König 
924fb51601bSUwe Kleine-König 	if (!res)
925fb51601bSUwe Kleine-König 		return;
926fb51601bSUwe Kleine-König 
927fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
928fb51601bSUwe Kleine-König 	kfree(sres);
929fb51601bSUwe Kleine-König }
930fb51601bSUwe Kleine-König 
931fb51601bSUwe Kleine-König /**
932fb51601bSUwe Kleine-König  * spi_res_add - add a spi_res to the spi_message
933fb51601bSUwe Kleine-König  * @message: the spi message
934fb51601bSUwe Kleine-König  * @res:     the spi_resource
935fb51601bSUwe Kleine-König  */
936da21fde0SUwe Kleine-König static void spi_res_add(struct spi_message *message, void *res)
937fb51601bSUwe Kleine-König {
938fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
939fb51601bSUwe Kleine-König 
940fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
941fb51601bSUwe Kleine-König 	list_add_tail(&sres->entry, &message->resources);
942fb51601bSUwe Kleine-König }
943fb51601bSUwe Kleine-König 
944fb51601bSUwe Kleine-König /**
945fb51601bSUwe Kleine-König  * spi_res_release - release all spi resources for this message
946fb51601bSUwe Kleine-König  * @ctlr:  the @spi_controller
947fb51601bSUwe Kleine-König  * @message: the @spi_message
948fb51601bSUwe Kleine-König  */
949da21fde0SUwe Kleine-König static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
950fb51601bSUwe Kleine-König {
951fb51601bSUwe Kleine-König 	struct spi_res *res, *tmp;
952fb51601bSUwe Kleine-König 
953fb51601bSUwe Kleine-König 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
954fb51601bSUwe Kleine-König 		if (res->release)
955fb51601bSUwe Kleine-König 			res->release(ctlr, message, res->data);
956fb51601bSUwe Kleine-König 
957fb51601bSUwe Kleine-König 		list_del(&res->entry);
958fb51601bSUwe Kleine-König 
959fb51601bSUwe Kleine-König 		kfree(res);
960fb51601bSUwe Kleine-König 	}
961fb51601bSUwe Kleine-König }
962fb51601bSUwe Kleine-König 
963fb51601bSUwe Kleine-König /*-------------------------------------------------------------------------*/
964fb51601bSUwe Kleine-König 
965d347b4aaSDavid Bauer static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
966b158935fSMark Brown {
96786527bcbSAndy Shevchenko 	bool activate = enable;
96825093bdeSAlexandru Ardelean 
969d40f0b6fSDouglas Anderson 	/*
970d40f0b6fSDouglas Anderson 	 * Avoid calling into the driver (or doing delays) if the chip select
971d40f0b6fSDouglas Anderson 	 * isn't actually changing from the last time this was called.
972d40f0b6fSDouglas Anderson 	 */
9736bb477dfSYun Zhou 	if (!force && ((enable && spi->controller->last_cs == spi->chip_select) ||
9746bb477dfSYun Zhou 				(!enable && spi->controller->last_cs != spi->chip_select)) &&
975d40f0b6fSDouglas Anderson 	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
976d40f0b6fSDouglas Anderson 		return;
977d40f0b6fSDouglas Anderson 
9785cb4e1f3SAndy Shevchenko 	trace_spi_set_cs(spi, activate);
9795cb4e1f3SAndy Shevchenko 
9806bb477dfSYun Zhou 	spi->controller->last_cs = enable ? spi->chip_select : -1;
981d40f0b6fSDouglas Anderson 	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
982d40f0b6fSDouglas Anderson 
983f48dc6b9SLinus Walleij 	if ((spi->cs_gpiod || !spi->controller->set_cs_timing) && !activate) {
9848c33ebfeSMason Zhang 		spi_delay_exec(&spi->cs_hold, NULL);
98525093bdeSAlexandru Ardelean 	}
98625093bdeSAlexandru Ardelean 
987b158935fSMark Brown 	if (spi->mode & SPI_CS_HIGH)
988b158935fSMark Brown 		enable = !enable;
989b158935fSMark Brown 
9906b695469SAndy Shevchenko 	if (spi->cs_gpiod) {
991f48dc6b9SLinus Walleij 		if (!(spi->mode & SPI_NO_CS)) {
9926b695469SAndy Shevchenko 			/*
9936b695469SAndy Shevchenko 			 * Historically ACPI has no means of the GPIO polarity and
9946b695469SAndy Shevchenko 			 * thus the SPISerialBus() resource defines it on the per-chip
9956b695469SAndy Shevchenko 			 * basis. In order to avoid a chain of negations, the GPIO
9966b695469SAndy Shevchenko 			 * polarity is considered being Active High. Even for the cases
9976b695469SAndy Shevchenko 			 * when _DSD() is involved (in the updated versions of ACPI)
9986b695469SAndy Shevchenko 			 * the GPIO CS polarity must be defined Active High to avoid
9996b695469SAndy Shevchenko 			 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
10006b695469SAndy Shevchenko 			 * into account.
10016b695469SAndy Shevchenko 			 */
10026b695469SAndy Shevchenko 			if (has_acpi_companion(&spi->dev))
10036b695469SAndy Shevchenko 				gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
1004f3186dd8SLinus Walleij 			else
10056b695469SAndy Shevchenko 				/* Polarity handled by GPIO library */
10066b695469SAndy Shevchenko 				gpiod_set_value_cansleep(spi->cs_gpiod, activate);
10076b695469SAndy Shevchenko 		}
10088eee6b9dSThor Thayer 		/* Some SPI masters need both GPIO CS & slave_select */
10098caab75fSGeert Uytterhoeven 		if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
10108caab75fSGeert Uytterhoeven 		    spi->controller->set_cs)
10118caab75fSGeert Uytterhoeven 			spi->controller->set_cs(spi, !enable);
10128caab75fSGeert Uytterhoeven 	} else if (spi->controller->set_cs) {
10138caab75fSGeert Uytterhoeven 		spi->controller->set_cs(spi, !enable);
10148eee6b9dSThor Thayer 	}
101525093bdeSAlexandru Ardelean 
1016f48dc6b9SLinus Walleij 	if (spi->cs_gpiod || !spi->controller->set_cs_timing) {
101795c07247SHector Martin 		if (activate)
101895c07247SHector Martin 			spi_delay_exec(&spi->cs_setup, NULL);
101995c07247SHector Martin 		else
10208c33ebfeSMason Zhang 			spi_delay_exec(&spi->cs_inactive, NULL);
102125093bdeSAlexandru Ardelean 	}
1022b158935fSMark Brown }
1023b158935fSMark Brown 
10242de440f5SGeert Uytterhoeven #ifdef CONFIG_HAS_DMA
10250c17ba73SVincent Whitchurch static int spi_map_buf_attrs(struct spi_controller *ctlr, struct device *dev,
10266ad45a27SMark Brown 			     struct sg_table *sgt, void *buf, size_t len,
10270c17ba73SVincent Whitchurch 			     enum dma_data_direction dir, unsigned long attrs)
10286ad45a27SMark Brown {
10296ad45a27SMark Brown 	const bool vmalloced_buf = is_vmalloc_addr(buf);
1030df88e91bSAndy Shevchenko 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
1031b1b8153cSVignesh R #ifdef CONFIG_HIGHMEM
1032b1b8153cSVignesh R 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
1033b1b8153cSVignesh R 				(unsigned long)buf < (PKMAP_BASE +
1034b1b8153cSVignesh R 					(LAST_PKMAP * PAGE_SIZE)));
1035b1b8153cSVignesh R #else
1036b1b8153cSVignesh R 	const bool kmap_buf = false;
1037b1b8153cSVignesh R #endif
103865598c13SAndrew Gabbasov 	int desc_len;
103965598c13SAndrew Gabbasov 	int sgs;
10406ad45a27SMark Brown 	struct page *vm_page;
10418dd4a016SJuan Gutierrez 	struct scatterlist *sg;
10426ad45a27SMark Brown 	void *sg_buf;
10436ad45a27SMark Brown 	size_t min;
10446ad45a27SMark Brown 	int i, ret;
10456ad45a27SMark Brown 
1046b1b8153cSVignesh R 	if (vmalloced_buf || kmap_buf) {
1047ebc4cb43SBiju Das 		desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
104865598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
10490569a88fSVignesh R 	} else if (virt_addr_valid(buf)) {
1050ebc4cb43SBiju Das 		desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
105165598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len, desc_len);
10520569a88fSVignesh R 	} else {
10530569a88fSVignesh R 		return -EINVAL;
105465598c13SAndrew Gabbasov 	}
105565598c13SAndrew Gabbasov 
10566ad45a27SMark Brown 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
10576ad45a27SMark Brown 	if (ret != 0)
10586ad45a27SMark Brown 		return ret;
10596ad45a27SMark Brown 
10608dd4a016SJuan Gutierrez 	sg = &sgt->sgl[0];
10616ad45a27SMark Brown 	for (i = 0; i < sgs; i++) {
10626ad45a27SMark Brown 
1063b1b8153cSVignesh R 		if (vmalloced_buf || kmap_buf) {
1064ce99319aSMaxime Chevallier 			/*
1065ce99319aSMaxime Chevallier 			 * Next scatterlist entry size is the minimum between
1066ce99319aSMaxime Chevallier 			 * the desc_len and the remaining buffer length that
1067ce99319aSMaxime Chevallier 			 * fits in a page.
1068ce99319aSMaxime Chevallier 			 */
1069ce99319aSMaxime Chevallier 			min = min_t(size_t, desc_len,
1070ce99319aSMaxime Chevallier 				    min_t(size_t, len,
1071ce99319aSMaxime Chevallier 					  PAGE_SIZE - offset_in_page(buf)));
1072b1b8153cSVignesh R 			if (vmalloced_buf)
10736ad45a27SMark Brown 				vm_page = vmalloc_to_page(buf);
1074b1b8153cSVignesh R 			else
1075b1b8153cSVignesh R 				vm_page = kmap_to_page(buf);
10766ad45a27SMark Brown 			if (!vm_page) {
10776ad45a27SMark Brown 				sg_free_table(sgt);
10786ad45a27SMark Brown 				return -ENOMEM;
10796ad45a27SMark Brown 			}
10808dd4a016SJuan Gutierrez 			sg_set_page(sg, vm_page,
1081c1aefbddSCharles Keepax 				    min, offset_in_page(buf));
10826ad45a27SMark Brown 		} else {
108365598c13SAndrew Gabbasov 			min = min_t(size_t, len, desc_len);
10846ad45a27SMark Brown 			sg_buf = buf;
10858dd4a016SJuan Gutierrez 			sg_set_buf(sg, sg_buf, min);
10866ad45a27SMark Brown 		}
10876ad45a27SMark Brown 
10886ad45a27SMark Brown 		buf += min;
10896ad45a27SMark Brown 		len -= min;
10908dd4a016SJuan Gutierrez 		sg = sg_next(sg);
10916ad45a27SMark Brown 	}
10926ad45a27SMark Brown 
10930c17ba73SVincent Whitchurch 	ret = dma_map_sgtable(dev, sgt, dir, attrs);
10946ad45a27SMark Brown 	if (ret < 0) {
10956ad45a27SMark Brown 		sg_free_table(sgt);
10966ad45a27SMark Brown 		return ret;
10976ad45a27SMark Brown 	}
10986ad45a27SMark Brown 
10996ad45a27SMark Brown 	return 0;
11006ad45a27SMark Brown }
11016ad45a27SMark Brown 
11020c17ba73SVincent Whitchurch int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
11030c17ba73SVincent Whitchurch 		struct sg_table *sgt, void *buf, size_t len,
11040c17ba73SVincent Whitchurch 		enum dma_data_direction dir)
11050c17ba73SVincent Whitchurch {
11060c17ba73SVincent Whitchurch 	return spi_map_buf_attrs(ctlr, dev, sgt, buf, len, dir, 0);
11070c17ba73SVincent Whitchurch }
11080c17ba73SVincent Whitchurch 
11090c17ba73SVincent Whitchurch static void spi_unmap_buf_attrs(struct spi_controller *ctlr,
11100c17ba73SVincent Whitchurch 				struct device *dev, struct sg_table *sgt,
11110c17ba73SVincent Whitchurch 				enum dma_data_direction dir,
11120c17ba73SVincent Whitchurch 				unsigned long attrs)
11130c17ba73SVincent Whitchurch {
11140c17ba73SVincent Whitchurch 	if (sgt->orig_nents) {
11150c17ba73SVincent Whitchurch 		dma_unmap_sgtable(dev, sgt, dir, attrs);
11160c17ba73SVincent Whitchurch 		sg_free_table(sgt);
11178e9204cdSMarek Szyprowski 		sgt->orig_nents = 0;
11188e9204cdSMarek Szyprowski 		sgt->nents = 0;
11190c17ba73SVincent Whitchurch 	}
11200c17ba73SVincent Whitchurch }
11210c17ba73SVincent Whitchurch 
112246336966SBoris Brezillon void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
11236ad45a27SMark Brown 		   struct sg_table *sgt, enum dma_data_direction dir)
11246ad45a27SMark Brown {
11250c17ba73SVincent Whitchurch 	spi_unmap_buf_attrs(ctlr, dev, sgt, dir, 0);
11266ad45a27SMark Brown }
11276ad45a27SMark Brown 
11288caab75fSGeert Uytterhoeven static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
112999adef31SMark Brown {
113099adef31SMark Brown 	struct device *tx_dev, *rx_dev;
113199adef31SMark Brown 	struct spi_transfer *xfer;
11326ad45a27SMark Brown 	int ret;
11333a2eba9bSMark Brown 
11348caab75fSGeert Uytterhoeven 	if (!ctlr->can_dma)
113599adef31SMark Brown 		return 0;
113699adef31SMark Brown 
11378caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
11388caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
1139b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1140b470e10eSVinod Koul 		tx_dev = ctlr->dma_map_dev;
1141c37f45b5SLeilk Liu 	else
11428caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
1143c37f45b5SLeilk Liu 
11448caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
11458caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
1146b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1147b470e10eSVinod Koul 		rx_dev = ctlr->dma_map_dev;
1148c37f45b5SLeilk Liu 	else
11498caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
115099adef31SMark Brown 
115199adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11520c17ba73SVincent Whitchurch 		/* The sync is done before each transfer. */
11530c17ba73SVincent Whitchurch 		unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
11540c17ba73SVincent Whitchurch 
11558caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
115699adef31SMark Brown 			continue;
115799adef31SMark Brown 
115899adef31SMark Brown 		if (xfer->tx_buf != NULL) {
11590c17ba73SVincent Whitchurch 			ret = spi_map_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
11600c17ba73SVincent Whitchurch 						(void *)xfer->tx_buf,
11610c17ba73SVincent Whitchurch 						xfer->len, DMA_TO_DEVICE,
11620c17ba73SVincent Whitchurch 						attrs);
11636ad45a27SMark Brown 			if (ret != 0)
11646ad45a27SMark Brown 				return ret;
116599adef31SMark Brown 		}
116699adef31SMark Brown 
116799adef31SMark Brown 		if (xfer->rx_buf != NULL) {
11680c17ba73SVincent Whitchurch 			ret = spi_map_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
116999adef31SMark Brown 						xfer->rx_buf, xfer->len,
11700c17ba73SVincent Whitchurch 						DMA_FROM_DEVICE, attrs);
11716ad45a27SMark Brown 			if (ret != 0) {
11720c17ba73SVincent Whitchurch 				spi_unmap_buf_attrs(ctlr, tx_dev,
11730c17ba73SVincent Whitchurch 						&xfer->tx_sg, DMA_TO_DEVICE,
11740c17ba73SVincent Whitchurch 						attrs);
11750c17ba73SVincent Whitchurch 
11766ad45a27SMark Brown 				return ret;
117799adef31SMark Brown 			}
117899adef31SMark Brown 		}
117999adef31SMark Brown 	}
118099adef31SMark Brown 
1181f25723dcSVincent Whitchurch 	ctlr->cur_rx_dma_dev = rx_dev;
1182f25723dcSVincent Whitchurch 	ctlr->cur_tx_dma_dev = tx_dev;
11838caab75fSGeert Uytterhoeven 	ctlr->cur_msg_mapped = true;
118499adef31SMark Brown 
118599adef31SMark Brown 	return 0;
118699adef31SMark Brown }
118799adef31SMark Brown 
11888caab75fSGeert Uytterhoeven static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
118999adef31SMark Brown {
1190f25723dcSVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
1191f25723dcSVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
119299adef31SMark Brown 	struct spi_transfer *xfer;
119399adef31SMark Brown 
11948caab75fSGeert Uytterhoeven 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
119599adef31SMark Brown 		return 0;
119699adef31SMark Brown 
119799adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11980c17ba73SVincent Whitchurch 		/* The sync has already been done after each transfer. */
11990c17ba73SVincent Whitchurch 		unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
12000c17ba73SVincent Whitchurch 
12018caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
120299adef31SMark Brown 			continue;
120399adef31SMark Brown 
12040c17ba73SVincent Whitchurch 		spi_unmap_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
12050c17ba73SVincent Whitchurch 				    DMA_FROM_DEVICE, attrs);
12060c17ba73SVincent Whitchurch 		spi_unmap_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
12070c17ba73SVincent Whitchurch 				    DMA_TO_DEVICE, attrs);
120899adef31SMark Brown 	}
120999adef31SMark Brown 
1210809b1b04SRobin Gong 	ctlr->cur_msg_mapped = false;
1211809b1b04SRobin Gong 
121299adef31SMark Brown 	return 0;
121399adef31SMark Brown }
12140c17ba73SVincent Whitchurch 
12150c17ba73SVincent Whitchurch static void spi_dma_sync_for_device(struct spi_controller *ctlr,
12160c17ba73SVincent Whitchurch 				    struct spi_transfer *xfer)
12170c17ba73SVincent Whitchurch {
12180c17ba73SVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
12190c17ba73SVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
12200c17ba73SVincent Whitchurch 
12210c17ba73SVincent Whitchurch 	if (!ctlr->cur_msg_mapped)
12220c17ba73SVincent Whitchurch 		return;
12230c17ba73SVincent Whitchurch 
12240c17ba73SVincent Whitchurch 	if (xfer->tx_sg.orig_nents)
12250c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_device(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
12260c17ba73SVincent Whitchurch 	if (xfer->rx_sg.orig_nents)
12270c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
12280c17ba73SVincent Whitchurch }
12290c17ba73SVincent Whitchurch 
12300c17ba73SVincent Whitchurch static void spi_dma_sync_for_cpu(struct spi_controller *ctlr,
12310c17ba73SVincent Whitchurch 				 struct spi_transfer *xfer)
12320c17ba73SVincent Whitchurch {
12330c17ba73SVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
12340c17ba73SVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
12350c17ba73SVincent Whitchurch 
12360c17ba73SVincent Whitchurch 	if (!ctlr->cur_msg_mapped)
12370c17ba73SVincent Whitchurch 		return;
12380c17ba73SVincent Whitchurch 
12390c17ba73SVincent Whitchurch 	if (xfer->rx_sg.orig_nents)
12400c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
12410c17ba73SVincent Whitchurch 	if (xfer->tx_sg.orig_nents)
12420c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_cpu(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
12430c17ba73SVincent Whitchurch }
12442de440f5SGeert Uytterhoeven #else /* !CONFIG_HAS_DMA */
12458caab75fSGeert Uytterhoeven static inline int __spi_map_msg(struct spi_controller *ctlr,
12462de440f5SGeert Uytterhoeven 				struct spi_message *msg)
12472de440f5SGeert Uytterhoeven {
12482de440f5SGeert Uytterhoeven 	return 0;
12492de440f5SGeert Uytterhoeven }
12502de440f5SGeert Uytterhoeven 
12518caab75fSGeert Uytterhoeven static inline int __spi_unmap_msg(struct spi_controller *ctlr,
12522de440f5SGeert Uytterhoeven 				  struct spi_message *msg)
12532de440f5SGeert Uytterhoeven {
12542de440f5SGeert Uytterhoeven 	return 0;
12552de440f5SGeert Uytterhoeven }
12560c17ba73SVincent Whitchurch 
12570c17ba73SVincent Whitchurch static void spi_dma_sync_for_device(struct spi_controller *ctrl,
12580c17ba73SVincent Whitchurch 				    struct spi_transfer *xfer)
12590c17ba73SVincent Whitchurch {
12600c17ba73SVincent Whitchurch }
12610c17ba73SVincent Whitchurch 
12620c17ba73SVincent Whitchurch static void spi_dma_sync_for_cpu(struct spi_controller *ctrl,
12630c17ba73SVincent Whitchurch 				 struct spi_transfer *xfer)
12640c17ba73SVincent Whitchurch {
12650c17ba73SVincent Whitchurch }
12662de440f5SGeert Uytterhoeven #endif /* !CONFIG_HAS_DMA */
12672de440f5SGeert Uytterhoeven 
12688caab75fSGeert Uytterhoeven static inline int spi_unmap_msg(struct spi_controller *ctlr,
12694b786458SMartin Sperl 				struct spi_message *msg)
12704b786458SMartin Sperl {
12714b786458SMartin Sperl 	struct spi_transfer *xfer;
12724b786458SMartin Sperl 
12734b786458SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
12744b786458SMartin Sperl 		/*
12754b786458SMartin Sperl 		 * Restore the original value of tx_buf or rx_buf if they are
12764b786458SMartin Sperl 		 * NULL.
12774b786458SMartin Sperl 		 */
12788caab75fSGeert Uytterhoeven 		if (xfer->tx_buf == ctlr->dummy_tx)
12794b786458SMartin Sperl 			xfer->tx_buf = NULL;
12808caab75fSGeert Uytterhoeven 		if (xfer->rx_buf == ctlr->dummy_rx)
12814b786458SMartin Sperl 			xfer->rx_buf = NULL;
12824b786458SMartin Sperl 	}
12834b786458SMartin Sperl 
12848caab75fSGeert Uytterhoeven 	return __spi_unmap_msg(ctlr, msg);
12854b786458SMartin Sperl }
12864b786458SMartin Sperl 
12878caab75fSGeert Uytterhoeven static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
12882de440f5SGeert Uytterhoeven {
12892de440f5SGeert Uytterhoeven 	struct spi_transfer *xfer;
12902de440f5SGeert Uytterhoeven 	void *tmp;
12912de440f5SGeert Uytterhoeven 	unsigned int max_tx, max_rx;
12922de440f5SGeert Uytterhoeven 
1293aee67fe8Sdillon min 	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1294aee67fe8Sdillon min 		&& !(msg->spi->mode & SPI_3WIRE)) {
12952de440f5SGeert Uytterhoeven 		max_tx = 0;
12962de440f5SGeert Uytterhoeven 		max_rx = 0;
12972de440f5SGeert Uytterhoeven 
12982de440f5SGeert Uytterhoeven 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
12998caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
13002de440f5SGeert Uytterhoeven 			    !xfer->tx_buf)
13012de440f5SGeert Uytterhoeven 				max_tx = max(xfer->len, max_tx);
13028caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
13032de440f5SGeert Uytterhoeven 			    !xfer->rx_buf)
13042de440f5SGeert Uytterhoeven 				max_rx = max(xfer->len, max_rx);
13052de440f5SGeert Uytterhoeven 		}
13062de440f5SGeert Uytterhoeven 
13072de440f5SGeert Uytterhoeven 		if (max_tx) {
13088caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_tx, max_tx,
1309b00bab9dSAndy Shevchenko 				       GFP_KERNEL | GFP_DMA | __GFP_ZERO);
13102de440f5SGeert Uytterhoeven 			if (!tmp)
13112de440f5SGeert Uytterhoeven 				return -ENOMEM;
13128caab75fSGeert Uytterhoeven 			ctlr->dummy_tx = tmp;
13132de440f5SGeert Uytterhoeven 		}
13142de440f5SGeert Uytterhoeven 
13152de440f5SGeert Uytterhoeven 		if (max_rx) {
13168caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_rx, max_rx,
13172de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
13182de440f5SGeert Uytterhoeven 			if (!tmp)
13192de440f5SGeert Uytterhoeven 				return -ENOMEM;
13208caab75fSGeert Uytterhoeven 			ctlr->dummy_rx = tmp;
13212de440f5SGeert Uytterhoeven 		}
13222de440f5SGeert Uytterhoeven 
13232de440f5SGeert Uytterhoeven 		if (max_tx || max_rx) {
13242de440f5SGeert Uytterhoeven 			list_for_each_entry(xfer, &msg->transfers,
13252de440f5SGeert Uytterhoeven 					    transfer_list) {
13265442dcaaSChris Lesiak 				if (!xfer->len)
13275442dcaaSChris Lesiak 					continue;
13282de440f5SGeert Uytterhoeven 				if (!xfer->tx_buf)
13298caab75fSGeert Uytterhoeven 					xfer->tx_buf = ctlr->dummy_tx;
13302de440f5SGeert Uytterhoeven 				if (!xfer->rx_buf)
13318caab75fSGeert Uytterhoeven 					xfer->rx_buf = ctlr->dummy_rx;
13322de440f5SGeert Uytterhoeven 			}
13332de440f5SGeert Uytterhoeven 		}
13342de440f5SGeert Uytterhoeven 	}
13352de440f5SGeert Uytterhoeven 
13368caab75fSGeert Uytterhoeven 	return __spi_map_msg(ctlr, msg);
13372de440f5SGeert Uytterhoeven }
133899adef31SMark Brown 
1339810923f3SLubomir Rintel static int spi_transfer_wait(struct spi_controller *ctlr,
1340810923f3SLubomir Rintel 			     struct spi_message *msg,
1341810923f3SLubomir Rintel 			     struct spi_transfer *xfer)
1342810923f3SLubomir Rintel {
1343d501cc4cSDavid Jander 	struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1344d501cc4cSDavid Jander 	struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
13456170d077SXu Yilun 	u32 speed_hz = xfer->speed_hz;
134649686df5SColin Ian King 	unsigned long long ms;
1347810923f3SLubomir Rintel 
1348810923f3SLubomir Rintel 	if (spi_controller_is_slave(ctlr)) {
1349810923f3SLubomir Rintel 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1350810923f3SLubomir Rintel 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1351810923f3SLubomir Rintel 			return -EINTR;
1352810923f3SLubomir Rintel 		}
1353810923f3SLubomir Rintel 	} else {
13546170d077SXu Yilun 		if (!speed_hz)
13556170d077SXu Yilun 			speed_hz = 100000;
13566170d077SXu Yilun 
135786b8bff7SAndy Shevchenko 		/*
135886b8bff7SAndy Shevchenko 		 * For each byte we wait for 8 cycles of the SPI clock.
135986b8bff7SAndy Shevchenko 		 * Since speed is defined in Hz and we want milliseconds,
136086b8bff7SAndy Shevchenko 		 * use respective multiplier, but before the division,
136186b8bff7SAndy Shevchenko 		 * otherwise we may get 0 for short transfers.
136286b8bff7SAndy Shevchenko 		 */
136386b8bff7SAndy Shevchenko 		ms = 8LL * MSEC_PER_SEC * xfer->len;
13646170d077SXu Yilun 		do_div(ms, speed_hz);
1365810923f3SLubomir Rintel 
136686b8bff7SAndy Shevchenko 		/*
136786b8bff7SAndy Shevchenko 		 * Increase it twice and add 200 ms tolerance, use
136886b8bff7SAndy Shevchenko 		 * predefined maximum in case of overflow.
136986b8bff7SAndy Shevchenko 		 */
137086b8bff7SAndy Shevchenko 		ms += ms + 200;
1371810923f3SLubomir Rintel 		if (ms > UINT_MAX)
1372810923f3SLubomir Rintel 			ms = UINT_MAX;
1373810923f3SLubomir Rintel 
1374810923f3SLubomir Rintel 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1375810923f3SLubomir Rintel 						 msecs_to_jiffies(ms));
1376810923f3SLubomir Rintel 
1377810923f3SLubomir Rintel 		if (ms == 0) {
1378810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1379810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1380810923f3SLubomir Rintel 			dev_err(&msg->spi->dev,
1381810923f3SLubomir Rintel 				"SPI transfer timed out\n");
1382810923f3SLubomir Rintel 			return -ETIMEDOUT;
1383810923f3SLubomir Rintel 		}
1384810923f3SLubomir Rintel 	}
1385810923f3SLubomir Rintel 
1386810923f3SLubomir Rintel 	return 0;
1387810923f3SLubomir Rintel }
1388810923f3SLubomir Rintel 
13890ff2de8bSMartin Sperl static void _spi_transfer_delay_ns(u32 ns)
13900ff2de8bSMartin Sperl {
13910ff2de8bSMartin Sperl 	if (!ns)
13920ff2de8bSMartin Sperl 		return;
139386b8bff7SAndy Shevchenko 	if (ns <= NSEC_PER_USEC) {
13940ff2de8bSMartin Sperl 		ndelay(ns);
13950ff2de8bSMartin Sperl 	} else {
139686b8bff7SAndy Shevchenko 		u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
13970ff2de8bSMartin Sperl 
13980ff2de8bSMartin Sperl 		if (us <= 10)
13990ff2de8bSMartin Sperl 			udelay(us);
14000ff2de8bSMartin Sperl 		else
14010ff2de8bSMartin Sperl 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
14020ff2de8bSMartin Sperl 	}
14030ff2de8bSMartin Sperl }
14040ff2de8bSMartin Sperl 
14053984d39bSAlexandru Ardelean int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
14060ff2de8bSMartin Sperl {
1407b2c98153SAlexandru Ardelean 	u32 delay = _delay->value;
1408b2c98153SAlexandru Ardelean 	u32 unit = _delay->unit;
1409d5864e5bSMartin Sperl 	u32 hz;
14100ff2de8bSMartin Sperl 
1411b2c98153SAlexandru Ardelean 	if (!delay)
1412b2c98153SAlexandru Ardelean 		return 0;
14130ff2de8bSMartin Sperl 
14140ff2de8bSMartin Sperl 	switch (unit) {
14150ff2de8bSMartin Sperl 	case SPI_DELAY_UNIT_USECS:
141686b8bff7SAndy Shevchenko 		delay *= NSEC_PER_USEC;
14170ff2de8bSMartin Sperl 		break;
141886b8bff7SAndy Shevchenko 	case SPI_DELAY_UNIT_NSECS:
141986b8bff7SAndy Shevchenko 		/* Nothing to do here */
14200ff2de8bSMartin Sperl 		break;
1421d5864e5bSMartin Sperl 	case SPI_DELAY_UNIT_SCK:
142295c8222fSDavid Jander 		/* Clock cycles need to be obtained from spi_transfer */
1423b2c98153SAlexandru Ardelean 		if (!xfer)
1424b2c98153SAlexandru Ardelean 			return -EINVAL;
142586b8bff7SAndy Shevchenko 		/*
142686b8bff7SAndy Shevchenko 		 * If there is unknown effective speed, approximate it
142786b8bff7SAndy Shevchenko 		 * by underestimating with half of the requested hz.
1428d5864e5bSMartin Sperl 		 */
1429d5864e5bSMartin Sperl 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1430b2c98153SAlexandru Ardelean 		if (!hz)
1431b2c98153SAlexandru Ardelean 			return -EINVAL;
143286b8bff7SAndy Shevchenko 
143386b8bff7SAndy Shevchenko 		/* Convert delay to nanoseconds */
143486b8bff7SAndy Shevchenko 		delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1435d5864e5bSMartin Sperl 		break;
14360ff2de8bSMartin Sperl 	default:
1437b2c98153SAlexandru Ardelean 		return -EINVAL;
1438b2c98153SAlexandru Ardelean 	}
1439b2c98153SAlexandru Ardelean 
1440b2c98153SAlexandru Ardelean 	return delay;
1441b2c98153SAlexandru Ardelean }
14423984d39bSAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1443b2c98153SAlexandru Ardelean 
1444b2c98153SAlexandru Ardelean int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1445b2c98153SAlexandru Ardelean {
1446b2c98153SAlexandru Ardelean 	int delay;
1447b2c98153SAlexandru Ardelean 
14488fede89fSMark Brown 	might_sleep();
14498fede89fSMark Brown 
1450b2c98153SAlexandru Ardelean 	if (!_delay)
1451b2c98153SAlexandru Ardelean 		return -EINVAL;
1452b2c98153SAlexandru Ardelean 
14533984d39bSAlexandru Ardelean 	delay = spi_delay_to_ns(_delay, xfer);
1454b2c98153SAlexandru Ardelean 	if (delay < 0)
1455b2c98153SAlexandru Ardelean 		return delay;
1456b2c98153SAlexandru Ardelean 
1457b2c98153SAlexandru Ardelean 	_spi_transfer_delay_ns(delay);
1458b2c98153SAlexandru Ardelean 
1459b2c98153SAlexandru Ardelean 	return 0;
1460b2c98153SAlexandru Ardelean }
1461b2c98153SAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_exec);
1462b2c98153SAlexandru Ardelean 
14630ff2de8bSMartin Sperl static void _spi_transfer_cs_change_delay(struct spi_message *msg,
14640ff2de8bSMartin Sperl 					  struct spi_transfer *xfer)
14650ff2de8bSMartin Sperl {
146686b8bff7SAndy Shevchenko 	u32 default_delay_ns = 10 * NSEC_PER_USEC;
1467329f0dacSAlexandru Ardelean 	u32 delay = xfer->cs_change_delay.value;
1468329f0dacSAlexandru Ardelean 	u32 unit = xfer->cs_change_delay.unit;
1469329f0dacSAlexandru Ardelean 	int ret;
14700ff2de8bSMartin Sperl 
147195c8222fSDavid Jander 	/* Return early on "fast" mode - for everything but USECS */
14726b3f236aSAlexandru Ardelean 	if (!delay) {
14736b3f236aSAlexandru Ardelean 		if (unit == SPI_DELAY_UNIT_USECS)
147486b8bff7SAndy Shevchenko 			_spi_transfer_delay_ns(default_delay_ns);
14750ff2de8bSMartin Sperl 		return;
14766b3f236aSAlexandru Ardelean 	}
14770ff2de8bSMartin Sperl 
1478329f0dacSAlexandru Ardelean 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1479329f0dacSAlexandru Ardelean 	if (ret) {
14800ff2de8bSMartin Sperl 		dev_err_once(&msg->spi->dev,
148186b8bff7SAndy Shevchenko 			     "Use of unsupported delay unit %i, using default of %luus\n",
148286b8bff7SAndy Shevchenko 			     unit, default_delay_ns / NSEC_PER_USEC);
148386b8bff7SAndy Shevchenko 		_spi_transfer_delay_ns(default_delay_ns);
14840ff2de8bSMartin Sperl 	}
14850ff2de8bSMartin Sperl }
14860ff2de8bSMartin Sperl 
1487b158935fSMark Brown /*
1488b158935fSMark Brown  * spi_transfer_one_message - Default implementation of transfer_one_message()
1489b158935fSMark Brown  *
1490b158935fSMark Brown  * This is a standard implementation of transfer_one_message() for
14918ba811a7SMoritz Fischer  * drivers which implement a transfer_one() operation.  It provides
1492b158935fSMark Brown  * standard handling of delays and chip select management.
1493b158935fSMark Brown  */
14948caab75fSGeert Uytterhoeven static int spi_transfer_one_message(struct spi_controller *ctlr,
1495b158935fSMark Brown 				    struct spi_message *msg)
1496b158935fSMark Brown {
1497b158935fSMark Brown 	struct spi_transfer *xfer;
1498b158935fSMark Brown 	bool keep_cs = false;
1499b158935fSMark Brown 	int ret = 0;
1500d501cc4cSDavid Jander 	struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1501d501cc4cSDavid Jander 	struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1502b158935fSMark Brown 
15035e0531f6SChristophe Leroy 	xfer = list_first_entry(&msg->transfers, struct spi_transfer, transfer_list);
15045e0531f6SChristophe Leroy 	spi_set_cs(msg->spi, !xfer->cs_off, false);
1505b158935fSMark Brown 
1506eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1507eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1508eca2ebc7SMartin Sperl 
1509b158935fSMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1510b158935fSMark Brown 		trace_spi_transfer_start(msg, xfer);
1511b158935fSMark Brown 
15128caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
15138caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1514eca2ebc7SMartin Sperl 
1515b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1516b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1517b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1518b42faeeeSVladimir Oltean 		}
1519b42faeeeSVladimir Oltean 
1520b3063203SNicolas Saenz Julienne 		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
15218caab75fSGeert Uytterhoeven 			reinit_completion(&ctlr->xfer_completion);
1522b158935fSMark Brown 
1523809b1b04SRobin Gong fallback_pio:
15240c17ba73SVincent Whitchurch 			spi_dma_sync_for_device(ctlr, xfer);
15258caab75fSGeert Uytterhoeven 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1526b158935fSMark Brown 			if (ret < 0) {
15270c17ba73SVincent Whitchurch 				spi_dma_sync_for_cpu(ctlr, xfer);
15280c17ba73SVincent Whitchurch 
1529809b1b04SRobin Gong 				if (ctlr->cur_msg_mapped &&
1530809b1b04SRobin Gong 				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1531809b1b04SRobin Gong 					__spi_unmap_msg(ctlr, msg);
1532809b1b04SRobin Gong 					ctlr->fallback = true;
1533809b1b04SRobin Gong 					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1534809b1b04SRobin Gong 					goto fallback_pio;
1535809b1b04SRobin Gong 				}
1536809b1b04SRobin Gong 
1537eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1538eca2ebc7SMartin Sperl 							       errors);
1539eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1540eca2ebc7SMartin Sperl 							       errors);
1541b158935fSMark Brown 				dev_err(&msg->spi->dev,
1542b158935fSMark Brown 					"SPI transfer failed: %d\n", ret);
1543b158935fSMark Brown 				goto out;
1544b158935fSMark Brown 			}
1545b158935fSMark Brown 
1546d57e7960SMark Brown 			if (ret > 0) {
1547810923f3SLubomir Rintel 				ret = spi_transfer_wait(ctlr, msg, xfer);
1548810923f3SLubomir Rintel 				if (ret < 0)
1549810923f3SLubomir Rintel 					msg->status = ret;
1550d57e7960SMark Brown 			}
15510c17ba73SVincent Whitchurch 
15520c17ba73SVincent Whitchurch 			spi_dma_sync_for_cpu(ctlr, xfer);
155338ec10f6SMark Brown 		} else {
155438ec10f6SMark Brown 			if (xfer->len)
155538ec10f6SMark Brown 				dev_err(&msg->spi->dev,
155638ec10f6SMark Brown 					"Bufferless transfer has length %u\n",
155738ec10f6SMark Brown 					xfer->len);
155838ec10f6SMark Brown 		}
1559b158935fSMark Brown 
1560b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1561b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1562b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1563b42faeeeSVladimir Oltean 		}
1564b42faeeeSVladimir Oltean 
1565b158935fSMark Brown 		trace_spi_transfer_stop(msg, xfer);
1566b158935fSMark Brown 
1567b158935fSMark Brown 		if (msg->status != -EINPROGRESS)
1568b158935fSMark Brown 			goto out;
1569b158935fSMark Brown 
1570bebcfd27SAlexandru Ardelean 		spi_transfer_delay_exec(xfer);
1571b158935fSMark Brown 
1572b158935fSMark Brown 		if (xfer->cs_change) {
1573b158935fSMark Brown 			if (list_is_last(&xfer->transfer_list,
1574b158935fSMark Brown 					 &msg->transfers)) {
1575b158935fSMark Brown 				keep_cs = true;
1576b158935fSMark Brown 			} else {
15775e0531f6SChristophe Leroy 				if (!xfer->cs_off)
1578d347b4aaSDavid Bauer 					spi_set_cs(msg->spi, false, false);
15790ff2de8bSMartin Sperl 				_spi_transfer_cs_change_delay(msg, xfer);
15805e0531f6SChristophe Leroy 				if (!list_next_entry(xfer, transfer_list)->cs_off)
1581d347b4aaSDavid Bauer 					spi_set_cs(msg->spi, true, false);
1582b158935fSMark Brown 			}
15835e0531f6SChristophe Leroy 		} else if (!list_is_last(&xfer->transfer_list, &msg->transfers) &&
15845e0531f6SChristophe Leroy 			   xfer->cs_off != list_next_entry(xfer, transfer_list)->cs_off) {
15855e0531f6SChristophe Leroy 			spi_set_cs(msg->spi, xfer->cs_off, false);
1586b158935fSMark Brown 		}
1587b158935fSMark Brown 
1588b158935fSMark Brown 		msg->actual_length += xfer->len;
1589b158935fSMark Brown 	}
1590b158935fSMark Brown 
1591b158935fSMark Brown out:
1592b158935fSMark Brown 	if (ret != 0 || !keep_cs)
1593d347b4aaSDavid Bauer 		spi_set_cs(msg->spi, false, false);
1594b158935fSMark Brown 
1595b158935fSMark Brown 	if (msg->status == -EINPROGRESS)
1596b158935fSMark Brown 		msg->status = ret;
1597b158935fSMark Brown 
15988caab75fSGeert Uytterhoeven 	if (msg->status && ctlr->handle_err)
15998caab75fSGeert Uytterhoeven 		ctlr->handle_err(ctlr, msg);
1600b716c4ffSAndy Shevchenko 
16010ed56252SMark Brown 	spi_finalize_current_message(ctlr);
16020ed56252SMark Brown 
1603b158935fSMark Brown 	return ret;
1604b158935fSMark Brown }
1605b158935fSMark Brown 
1606b158935fSMark Brown /**
1607b158935fSMark Brown  * spi_finalize_current_transfer - report completion of a transfer
16088caab75fSGeert Uytterhoeven  * @ctlr: the controller reporting completion
1609b158935fSMark Brown  *
1610b158935fSMark Brown  * Called by SPI drivers using the core transfer_one_message()
1611b158935fSMark Brown  * implementation to notify it that the current interrupt driven
16129e8f4882SGeert Uytterhoeven  * transfer has finished and the next one may be scheduled.
1613b158935fSMark Brown  */
16148caab75fSGeert Uytterhoeven void spi_finalize_current_transfer(struct spi_controller *ctlr)
1615b158935fSMark Brown {
16168caab75fSGeert Uytterhoeven 	complete(&ctlr->xfer_completion);
1617b158935fSMark Brown }
1618b158935fSMark Brown EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1619b158935fSMark Brown 
1620e1268597SMark Brown static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1621e1268597SMark Brown {
1622e1268597SMark Brown 	if (ctlr->auto_runtime_pm) {
1623e1268597SMark Brown 		pm_runtime_mark_last_busy(ctlr->dev.parent);
1624e1268597SMark Brown 		pm_runtime_put_autosuspend(ctlr->dev.parent);
1625e1268597SMark Brown 	}
1626e1268597SMark Brown }
1627e1268597SMark Brown 
1628ae7d2346SDavid Jander static int __spi_pump_transfer_message(struct spi_controller *ctlr,
1629ae7d2346SDavid Jander 		struct spi_message *msg, bool was_busy)
1630ae7d2346SDavid Jander {
1631ae7d2346SDavid Jander 	struct spi_transfer *xfer;
1632ae7d2346SDavid Jander 	int ret;
1633ae7d2346SDavid Jander 
1634ae7d2346SDavid Jander 	if (!was_busy && ctlr->auto_runtime_pm) {
1635ae7d2346SDavid Jander 		ret = pm_runtime_get_sync(ctlr->dev.parent);
1636ae7d2346SDavid Jander 		if (ret < 0) {
1637ae7d2346SDavid Jander 			pm_runtime_put_noidle(ctlr->dev.parent);
1638ae7d2346SDavid Jander 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
1639ae7d2346SDavid Jander 				ret);
1640ae7d2346SDavid Jander 			return ret;
1641ae7d2346SDavid Jander 		}
1642ae7d2346SDavid Jander 	}
1643ae7d2346SDavid Jander 
1644ae7d2346SDavid Jander 	if (!was_busy)
1645ae7d2346SDavid Jander 		trace_spi_controller_busy(ctlr);
1646ae7d2346SDavid Jander 
1647ae7d2346SDavid Jander 	if (!was_busy && ctlr->prepare_transfer_hardware) {
1648ae7d2346SDavid Jander 		ret = ctlr->prepare_transfer_hardware(ctlr);
1649ae7d2346SDavid Jander 		if (ret) {
1650ae7d2346SDavid Jander 			dev_err(&ctlr->dev,
1651ae7d2346SDavid Jander 				"failed to prepare transfer hardware: %d\n",
1652ae7d2346SDavid Jander 				ret);
1653ae7d2346SDavid Jander 
1654ae7d2346SDavid Jander 			if (ctlr->auto_runtime_pm)
1655ae7d2346SDavid Jander 				pm_runtime_put(ctlr->dev.parent);
1656ae7d2346SDavid Jander 
1657ae7d2346SDavid Jander 			msg->status = ret;
1658ae7d2346SDavid Jander 			spi_finalize_current_message(ctlr);
1659ae7d2346SDavid Jander 
1660ae7d2346SDavid Jander 			return ret;
1661ae7d2346SDavid Jander 		}
1662ae7d2346SDavid Jander 	}
1663ae7d2346SDavid Jander 
1664ae7d2346SDavid Jander 	trace_spi_message_start(msg);
1665ae7d2346SDavid Jander 
16668d699ff9SVincent Whitchurch 	ret = spi_split_transfers_maxsize(ctlr, msg,
16678d699ff9SVincent Whitchurch 					  spi_max_transfer_size(msg->spi),
16688d699ff9SVincent Whitchurch 					  GFP_KERNEL | GFP_DMA);
16698d699ff9SVincent Whitchurch 	if (ret) {
16708d699ff9SVincent Whitchurch 		msg->status = ret;
16718d699ff9SVincent Whitchurch 		spi_finalize_current_message(ctlr);
16728d699ff9SVincent Whitchurch 		return ret;
16738d699ff9SVincent Whitchurch 	}
16748d699ff9SVincent Whitchurch 
1675ae7d2346SDavid Jander 	if (ctlr->prepare_message) {
1676ae7d2346SDavid Jander 		ret = ctlr->prepare_message(ctlr, msg);
1677ae7d2346SDavid Jander 		if (ret) {
1678ae7d2346SDavid Jander 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1679ae7d2346SDavid Jander 				ret);
1680ae7d2346SDavid Jander 			msg->status = ret;
1681ae7d2346SDavid Jander 			spi_finalize_current_message(ctlr);
1682ae7d2346SDavid Jander 			return ret;
1683ae7d2346SDavid Jander 		}
1684ae7d2346SDavid Jander 		msg->prepared = true;
1685ae7d2346SDavid Jander 	}
1686ae7d2346SDavid Jander 
1687ae7d2346SDavid Jander 	ret = spi_map_msg(ctlr, msg);
1688ae7d2346SDavid Jander 	if (ret) {
1689ae7d2346SDavid Jander 		msg->status = ret;
1690ae7d2346SDavid Jander 		spi_finalize_current_message(ctlr);
1691ae7d2346SDavid Jander 		return ret;
1692ae7d2346SDavid Jander 	}
1693ae7d2346SDavid Jander 
1694ae7d2346SDavid Jander 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1695ae7d2346SDavid Jander 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1696ae7d2346SDavid Jander 			xfer->ptp_sts_word_pre = 0;
1697ae7d2346SDavid Jander 			ptp_read_system_prets(xfer->ptp_sts);
1698ae7d2346SDavid Jander 		}
1699ae7d2346SDavid Jander 	}
1700ae7d2346SDavid Jander 
1701dc302905SDavid Jander 	/*
1702dc302905SDavid Jander 	 * Drivers implementation of transfer_one_message() must arrange for
1703dc302905SDavid Jander 	 * spi_finalize_current_message() to get called. Most drivers will do
1704dc302905SDavid Jander 	 * this in the calling context, but some don't. For those cases, a
1705dc302905SDavid Jander 	 * completion is used to guarantee that this function does not return
1706dc302905SDavid Jander 	 * until spi_finalize_current_message() is done accessing
1707dc302905SDavid Jander 	 * ctlr->cur_msg.
1708dc302905SDavid Jander 	 * Use of the following two flags enable to opportunistically skip the
1709dc302905SDavid Jander 	 * use of the completion since its use involves expensive spin locks.
1710dc302905SDavid Jander 	 * In case of a race with the context that calls
1711dc302905SDavid Jander 	 * spi_finalize_current_message() the completion will always be used,
1712dc302905SDavid Jander 	 * due to strict ordering of these flags using barriers.
1713dc302905SDavid Jander 	 */
1714dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_incomplete, true);
1715dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_need_completion, false);
171669fa9590SDavid Jander 	reinit_completion(&ctlr->cur_msg_completion);
171795c8222fSDavid Jander 	smp_wmb(); /* Make these available to spi_finalize_current_message() */
1718dc302905SDavid Jander 
1719ae7d2346SDavid Jander 	ret = ctlr->transfer_one_message(ctlr, msg);
1720ae7d2346SDavid Jander 	if (ret) {
1721ae7d2346SDavid Jander 		dev_err(&ctlr->dev,
1722ae7d2346SDavid Jander 			"failed to transfer one message from queue\n");
1723ae7d2346SDavid Jander 		return ret;
172431d4c1bdSDavid Jander 	}
172531d4c1bdSDavid Jander 
1726dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_need_completion, true);
172731d4c1bdSDavid Jander 	smp_mb(); /* See spi_finalize_current_message()... */
1728dc302905SDavid Jander 	if (READ_ONCE(ctlr->cur_msg_incomplete))
172969fa9590SDavid Jander 		wait_for_completion(&ctlr->cur_msg_completion);
1730ae7d2346SDavid Jander 
1731ae7d2346SDavid Jander 	return 0;
1732ae7d2346SDavid Jander }
1733ae7d2346SDavid Jander 
1734ffbbdd21SLinus Walleij /**
1735fc9e0f71SMark Brown  * __spi_pump_messages - function which processes spi message queue
17368caab75fSGeert Uytterhoeven  * @ctlr: controller to process queue for
1737fc9e0f71SMark Brown  * @in_kthread: true if we are in the context of the message pump thread
1738ffbbdd21SLinus Walleij  *
1739ffbbdd21SLinus Walleij  * This function checks if there is any spi message in the queue that
1740ffbbdd21SLinus Walleij  * needs processing and if so call out to the driver to initialize hardware
1741ffbbdd21SLinus Walleij  * and transfer each message.
1742ffbbdd21SLinus Walleij  *
17430461a414SMark Brown  * Note that it is called both from the kthread itself and also from
17440461a414SMark Brown  * inside spi_sync(); the queue extraction handling at the top of the
17450461a414SMark Brown  * function should deal with this safely.
1746ffbbdd21SLinus Walleij  */
17478caab75fSGeert Uytterhoeven static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1748ffbbdd21SLinus Walleij {
1749d1c44c93SVladimir Oltean 	struct spi_message *msg;
1750ffbbdd21SLinus Walleij 	bool was_busy = false;
1751d1c44c93SVladimir Oltean 	unsigned long flags;
1752ffbbdd21SLinus Walleij 	int ret;
1753ffbbdd21SLinus Walleij 
1754c1038165SDavid Jander 	/* Take the IO mutex */
1755c1038165SDavid Jander 	mutex_lock(&ctlr->io_mutex);
1756c1038165SDavid Jander 
1757983aee5dSMark Brown 	/* Lock queue */
17588caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1759983aee5dSMark Brown 
1760983aee5dSMark Brown 	/* Make sure we are not already running a message */
17618711a2abSDavid Jander 	if (ctlr->cur_msg)
1762c1038165SDavid Jander 		goto out_unlock;
1763983aee5dSMark Brown 
1764983aee5dSMark Brown 	/* Check if the queue is idle */
17658caab75fSGeert Uytterhoeven 	if (list_empty(&ctlr->queue) || !ctlr->running) {
17668711a2abSDavid Jander 		if (!ctlr->busy)
1767c1038165SDavid Jander 			goto out_unlock;
1768fc9e0f71SMark Brown 
1769e1268597SMark Brown 		/* Defer any non-atomic teardown to the thread */
1770f0125f1aSMark Brown 		if (!in_kthread) {
1771e1268597SMark Brown 			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1772e1268597SMark Brown 			    !ctlr->unprepare_transfer_hardware) {
1773e1268597SMark Brown 				spi_idle_runtime_pm(ctlr);
1774e1268597SMark Brown 				ctlr->busy = false;
1775ae7d2346SDavid Jander 				ctlr->queue_empty = true;
1776e1268597SMark Brown 				trace_spi_controller_idle(ctlr);
1777e1268597SMark Brown 			} else {
177860a883d1SMarek Szyprowski 				kthread_queue_work(ctlr->kworker,
1779f0125f1aSMark Brown 						   &ctlr->pump_messages);
1780e1268597SMark Brown 			}
1781c1038165SDavid Jander 			goto out_unlock;
1782f0125f1aSMark Brown 		}
1783f0125f1aSMark Brown 
1784f0125f1aSMark Brown 		ctlr->busy = false;
1785f0125f1aSMark Brown 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1786f0125f1aSMark Brown 
1787f0125f1aSMark Brown 		kfree(ctlr->dummy_rx);
1788f0125f1aSMark Brown 		ctlr->dummy_rx = NULL;
1789f0125f1aSMark Brown 		kfree(ctlr->dummy_tx);
1790f0125f1aSMark Brown 		ctlr->dummy_tx = NULL;
1791f0125f1aSMark Brown 		if (ctlr->unprepare_transfer_hardware &&
1792f0125f1aSMark Brown 		    ctlr->unprepare_transfer_hardware(ctlr))
1793f0125f1aSMark Brown 			dev_err(&ctlr->dev,
1794f0125f1aSMark Brown 				"failed to unprepare transfer hardware\n");
1795e1268597SMark Brown 		spi_idle_runtime_pm(ctlr);
1796f0125f1aSMark Brown 		trace_spi_controller_idle(ctlr);
1797f0125f1aSMark Brown 
1798f0125f1aSMark Brown 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1799ae7d2346SDavid Jander 		ctlr->queue_empty = true;
1800c1038165SDavid Jander 		goto out_unlock;
1801ffbbdd21SLinus Walleij 	}
1802ffbbdd21SLinus Walleij 
1803ffbbdd21SLinus Walleij 	/* Extract head of queue */
1804d1c44c93SVladimir Oltean 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1805d1c44c93SVladimir Oltean 	ctlr->cur_msg = msg;
1806ffbbdd21SLinus Walleij 
1807d1c44c93SVladimir Oltean 	list_del_init(&msg->queue);
18088caab75fSGeert Uytterhoeven 	if (ctlr->busy)
1809ffbbdd21SLinus Walleij 		was_busy = true;
1810ffbbdd21SLinus Walleij 	else
18118caab75fSGeert Uytterhoeven 		ctlr->busy = true;
18128caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1813ffbbdd21SLinus Walleij 
1814ae7d2346SDavid Jander 	ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
181569fa9590SDavid Jander 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1816c191543eSDavid Jander 
181769fa9590SDavid Jander 	ctlr->cur_msg = NULL;
181869fa9590SDavid Jander 	ctlr->fallback = false;
181969fa9590SDavid Jander 
18208caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->io_mutex);
182162826970SMark Brown 
182262826970SMark Brown 	/* Prod the scheduler in case transfer_one() was busy waiting */
182349023d2eSJon Hunter 	if (!ret)
182462826970SMark Brown 		cond_resched();
1825c1038165SDavid Jander 	return;
1826c1038165SDavid Jander 
1827c1038165SDavid Jander out_unlock:
18288711a2abSDavid Jander 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1829c1038165SDavid Jander 	mutex_unlock(&ctlr->io_mutex);
1830ffbbdd21SLinus Walleij }
1831ffbbdd21SLinus Walleij 
1832fc9e0f71SMark Brown /**
1833fc9e0f71SMark Brown  * spi_pump_messages - kthread work function which processes spi message queue
18348caab75fSGeert Uytterhoeven  * @work: pointer to kthread work struct contained in the controller struct
1835fc9e0f71SMark Brown  */
1836fc9e0f71SMark Brown static void spi_pump_messages(struct kthread_work *work)
1837fc9e0f71SMark Brown {
18388caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr =
18398caab75fSGeert Uytterhoeven 		container_of(work, struct spi_controller, pump_messages);
1840fc9e0f71SMark Brown 
18418caab75fSGeert Uytterhoeven 	__spi_pump_messages(ctlr, true);
1842fc9e0f71SMark Brown }
1843fc9e0f71SMark Brown 
1844924b5867SDouglas Anderson /**
1845350de7ceSAndy Shevchenko  * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1846b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1847b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1848862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1849b42faeeeSVladimir Oltean  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1850b42faeeeSVladimir Oltean  *	      transfer, for less jitter in time measurement. Only compatible
1851b42faeeeSVladimir Oltean  *	      with PIO drivers. If true, must follow up with
1852b42faeeeSVladimir Oltean  *	      spi_take_timestamp_post or otherwise system will crash.
1853b42faeeeSVladimir Oltean  *	      WARNING: for fully predictable results, the CPU frequency must
1854b42faeeeSVladimir Oltean  *	      also be under control (governor).
1855350de7ceSAndy Shevchenko  *
1856350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the beginning of the TX timestamp
1857350de7ceSAndy Shevchenko  * for the requested byte from the SPI transfer. The frequency with which this
1858350de7ceSAndy Shevchenko  * function must be called (once per word, once for the whole transfer, once
1859350de7ceSAndy Shevchenko  * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1860350de7ceSAndy Shevchenko  * greater than or equal to the requested byte at the time of the call. The
1861350de7ceSAndy Shevchenko  * timestamp is only taken once, at the first such call. It is assumed that
1862350de7ceSAndy Shevchenko  * the driver advances its @tx buffer pointer monotonically.
1863b42faeeeSVladimir Oltean  */
1864b42faeeeSVladimir Oltean void spi_take_timestamp_pre(struct spi_controller *ctlr,
1865b42faeeeSVladimir Oltean 			    struct spi_transfer *xfer,
1866862dd2a9SVladimir Oltean 			    size_t progress, bool irqs_off)
1867b42faeeeSVladimir Oltean {
1868b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1869b42faeeeSVladimir Oltean 		return;
1870b42faeeeSVladimir Oltean 
18716a726824SVladimir Oltean 	if (xfer->timestamped)
1872b42faeeeSVladimir Oltean 		return;
1873b42faeeeSVladimir Oltean 
18746a726824SVladimir Oltean 	if (progress > xfer->ptp_sts_word_pre)
1875b42faeeeSVladimir Oltean 		return;
1876b42faeeeSVladimir Oltean 
1877b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1878862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_pre = progress;
1879b42faeeeSVladimir Oltean 
1880b42faeeeSVladimir Oltean 	if (irqs_off) {
1881b42faeeeSVladimir Oltean 		local_irq_save(ctlr->irq_flags);
1882b42faeeeSVladimir Oltean 		preempt_disable();
1883b42faeeeSVladimir Oltean 	}
1884b42faeeeSVladimir Oltean 
1885b42faeeeSVladimir Oltean 	ptp_read_system_prets(xfer->ptp_sts);
1886b42faeeeSVladimir Oltean }
1887b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1888b42faeeeSVladimir Oltean 
1889b42faeeeSVladimir Oltean /**
1890350de7ceSAndy Shevchenko  * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1891b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1892b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1893862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1894b42faeeeSVladimir Oltean  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1895350de7ceSAndy Shevchenko  *
1896350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the end of the TX timestamp for
1897350de7ceSAndy Shevchenko  * the requested byte from the SPI transfer. Can be called with an arbitrary
1898350de7ceSAndy Shevchenko  * frequency: only the first call where @tx exceeds or is equal to the
1899350de7ceSAndy Shevchenko  * requested word will be timestamped.
1900b42faeeeSVladimir Oltean  */
1901b42faeeeSVladimir Oltean void spi_take_timestamp_post(struct spi_controller *ctlr,
1902b42faeeeSVladimir Oltean 			     struct spi_transfer *xfer,
1903862dd2a9SVladimir Oltean 			     size_t progress, bool irqs_off)
1904b42faeeeSVladimir Oltean {
1905b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1906b42faeeeSVladimir Oltean 		return;
1907b42faeeeSVladimir Oltean 
19086a726824SVladimir Oltean 	if (xfer->timestamped)
1909b42faeeeSVladimir Oltean 		return;
1910b42faeeeSVladimir Oltean 
1911862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_post)
1912b42faeeeSVladimir Oltean 		return;
1913b42faeeeSVladimir Oltean 
1914b42faeeeSVladimir Oltean 	ptp_read_system_postts(xfer->ptp_sts);
1915b42faeeeSVladimir Oltean 
1916b42faeeeSVladimir Oltean 	if (irqs_off) {
1917b42faeeeSVladimir Oltean 		local_irq_restore(ctlr->irq_flags);
1918b42faeeeSVladimir Oltean 		preempt_enable();
1919b42faeeeSVladimir Oltean 	}
1920b42faeeeSVladimir Oltean 
1921b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1922862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_post = progress;
1923b42faeeeSVladimir Oltean 
19246a726824SVladimir Oltean 	xfer->timestamped = true;
1925b42faeeeSVladimir Oltean }
1926b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1927b42faeeeSVladimir Oltean 
1928b42faeeeSVladimir Oltean /**
1929924b5867SDouglas Anderson  * spi_set_thread_rt - set the controller to pump at realtime priority
1930924b5867SDouglas Anderson  * @ctlr: controller to boost priority of
1931924b5867SDouglas Anderson  *
1932924b5867SDouglas Anderson  * This can be called because the controller requested realtime priority
1933924b5867SDouglas Anderson  * (by setting the ->rt value before calling spi_register_controller()) or
1934924b5867SDouglas Anderson  * because a device on the bus said that its transfers needed realtime
1935924b5867SDouglas Anderson  * priority.
1936924b5867SDouglas Anderson  *
1937924b5867SDouglas Anderson  * NOTE: at the moment if any device on a bus says it needs realtime then
1938924b5867SDouglas Anderson  * the thread will be at realtime priority for all transfers on that
1939924b5867SDouglas Anderson  * controller.  If this eventually becomes a problem we may see if we can
1940924b5867SDouglas Anderson  * find a way to boost the priority only temporarily during relevant
1941924b5867SDouglas Anderson  * transfers.
1942924b5867SDouglas Anderson  */
1943924b5867SDouglas Anderson static void spi_set_thread_rt(struct spi_controller *ctlr)
1944ffbbdd21SLinus Walleij {
1945924b5867SDouglas Anderson 	dev_info(&ctlr->dev,
1946924b5867SDouglas Anderson 		"will run message pump with realtime priority\n");
19476d2b84a4SLinus Torvalds 	sched_set_fifo(ctlr->kworker->task);
1948924b5867SDouglas Anderson }
1949924b5867SDouglas Anderson 
1950924b5867SDouglas Anderson static int spi_init_queue(struct spi_controller *ctlr)
1951924b5867SDouglas Anderson {
19528caab75fSGeert Uytterhoeven 	ctlr->running = false;
19538caab75fSGeert Uytterhoeven 	ctlr->busy = false;
1954ae7d2346SDavid Jander 	ctlr->queue_empty = true;
1955ffbbdd21SLinus Walleij 
195660a883d1SMarek Szyprowski 	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
195760a883d1SMarek Szyprowski 	if (IS_ERR(ctlr->kworker)) {
195860a883d1SMarek Szyprowski 		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
195960a883d1SMarek Szyprowski 		return PTR_ERR(ctlr->kworker);
1960ffbbdd21SLinus Walleij 	}
196160a883d1SMarek Szyprowski 
19628caab75fSGeert Uytterhoeven 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1963f0125f1aSMark Brown 
1964ffbbdd21SLinus Walleij 	/*
19658caab75fSGeert Uytterhoeven 	 * Controller config will indicate if this controller should run the
1966ffbbdd21SLinus Walleij 	 * message pump with high (realtime) priority to reduce the transfer
1967ffbbdd21SLinus Walleij 	 * latency on the bus by minimising the delay between a transfer
1968ffbbdd21SLinus Walleij 	 * request and the scheduling of the message pump thread. Without this
1969ffbbdd21SLinus Walleij 	 * setting the message pump thread will remain at default priority.
1970ffbbdd21SLinus Walleij 	 */
1971924b5867SDouglas Anderson 	if (ctlr->rt)
1972924b5867SDouglas Anderson 		spi_set_thread_rt(ctlr);
1973ffbbdd21SLinus Walleij 
1974ffbbdd21SLinus Walleij 	return 0;
1975ffbbdd21SLinus Walleij }
1976ffbbdd21SLinus Walleij 
1977ffbbdd21SLinus Walleij /**
1978ffbbdd21SLinus Walleij  * spi_get_next_queued_message() - called by driver to check for queued
1979ffbbdd21SLinus Walleij  * messages
19808caab75fSGeert Uytterhoeven  * @ctlr: the controller to check for queued messages
1981ffbbdd21SLinus Walleij  *
1982ffbbdd21SLinus Walleij  * If there are more messages in the queue, the next message is returned from
1983ffbbdd21SLinus Walleij  * this call.
198497d56dc6SJavier Martinez Canillas  *
198597d56dc6SJavier Martinez Canillas  * Return: the next message in the queue, else NULL if the queue is empty.
1986ffbbdd21SLinus Walleij  */
19878caab75fSGeert Uytterhoeven struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1988ffbbdd21SLinus Walleij {
1989ffbbdd21SLinus Walleij 	struct spi_message *next;
1990ffbbdd21SLinus Walleij 	unsigned long flags;
1991ffbbdd21SLinus Walleij 
199295c8222fSDavid Jander 	/* Get a pointer to the next message, if any */
19938caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
19948caab75fSGeert Uytterhoeven 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
19951cfd97f9SAxel Lin 					queue);
19968caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1997ffbbdd21SLinus Walleij 
1998ffbbdd21SLinus Walleij 	return next;
1999ffbbdd21SLinus Walleij }
2000ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
2001ffbbdd21SLinus Walleij 
2002ffbbdd21SLinus Walleij /**
2003ffbbdd21SLinus Walleij  * spi_finalize_current_message() - the current message is complete
20048caab75fSGeert Uytterhoeven  * @ctlr: the controller to return the message to
2005ffbbdd21SLinus Walleij  *
2006ffbbdd21SLinus Walleij  * Called by the driver to notify the core that the message in the front of the
2007ffbbdd21SLinus Walleij  * queue is complete and can be removed from the queue.
2008ffbbdd21SLinus Walleij  */
20098caab75fSGeert Uytterhoeven void spi_finalize_current_message(struct spi_controller *ctlr)
2010ffbbdd21SLinus Walleij {
2011b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
2012ffbbdd21SLinus Walleij 	struct spi_message *mesg;
20132841a5fcSMark Brown 	int ret;
2014ffbbdd21SLinus Walleij 
20158caab75fSGeert Uytterhoeven 	mesg = ctlr->cur_msg;
2016ffbbdd21SLinus Walleij 
2017b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
2018b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
2019b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
2020b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
2021b42faeeeSVladimir Oltean 		}
2022b42faeeeSVladimir Oltean 	}
2023b42faeeeSVladimir Oltean 
20246a726824SVladimir Oltean 	if (unlikely(ctlr->ptp_sts_supported))
20256a726824SVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
20266a726824SVladimir Oltean 			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
2027f971a207SVladimir Oltean 
20288caab75fSGeert Uytterhoeven 	spi_unmap_msg(ctlr, mesg);
202999adef31SMark Brown 
2030350de7ceSAndy Shevchenko 	/*
2031350de7ceSAndy Shevchenko 	 * In the prepare_messages callback the SPI bus has the opportunity
2032350de7ceSAndy Shevchenko 	 * to split a transfer to smaller chunks.
2033350de7ceSAndy Shevchenko 	 *
2034350de7ceSAndy Shevchenko 	 * Release the split transfers here since spi_map_msg() is done on
2035350de7ceSAndy Shevchenko 	 * the split transfers.
2036b59a7ca1SGustav Wiklander 	 */
2037b59a7ca1SGustav Wiklander 	spi_res_release(ctlr, mesg);
2038b59a7ca1SGustav Wiklander 
20391714582aSDavid Jander 	if (mesg->prepared && ctlr->unprepare_message) {
20408caab75fSGeert Uytterhoeven 		ret = ctlr->unprepare_message(ctlr, mesg);
20412841a5fcSMark Brown 		if (ret) {
20428caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
20438caab75fSGeert Uytterhoeven 				ret);
20442841a5fcSMark Brown 		}
20452841a5fcSMark Brown 	}
2046391949b6SUwe Kleine-König 
20471714582aSDavid Jander 	mesg->prepared = false;
20481714582aSDavid Jander 
2049dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_incomplete, false);
2050dc302905SDavid Jander 	smp_mb(); /* See __spi_pump_transfer_message()... */
2051dc302905SDavid Jander 	if (READ_ONCE(ctlr->cur_msg_need_completion))
205269fa9590SDavid Jander 		complete(&ctlr->cur_msg_completion);
20538e76ef88SMartin Sperl 
20548e76ef88SMartin Sperl 	trace_spi_message_done(mesg);
20552841a5fcSMark Brown 
2056ffbbdd21SLinus Walleij 	mesg->state = NULL;
2057ffbbdd21SLinus Walleij 	if (mesg->complete)
2058ffbbdd21SLinus Walleij 		mesg->complete(mesg->context);
2059ffbbdd21SLinus Walleij }
2060ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_finalize_current_message);
2061ffbbdd21SLinus Walleij 
20628caab75fSGeert Uytterhoeven static int spi_start_queue(struct spi_controller *ctlr)
2063ffbbdd21SLinus Walleij {
2064ffbbdd21SLinus Walleij 	unsigned long flags;
2065ffbbdd21SLinus Walleij 
20668caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2067ffbbdd21SLinus Walleij 
20688caab75fSGeert Uytterhoeven 	if (ctlr->running || ctlr->busy) {
20698caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2070ffbbdd21SLinus Walleij 		return -EBUSY;
2071ffbbdd21SLinus Walleij 	}
2072ffbbdd21SLinus Walleij 
20738caab75fSGeert Uytterhoeven 	ctlr->running = true;
20748caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
20758caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2076ffbbdd21SLinus Walleij 
207760a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2078ffbbdd21SLinus Walleij 
2079ffbbdd21SLinus Walleij 	return 0;
2080ffbbdd21SLinus Walleij }
2081ffbbdd21SLinus Walleij 
20828caab75fSGeert Uytterhoeven static int spi_stop_queue(struct spi_controller *ctlr)
2083ffbbdd21SLinus Walleij {
2084ffbbdd21SLinus Walleij 	unsigned long flags;
2085ffbbdd21SLinus Walleij 	unsigned limit = 500;
2086ffbbdd21SLinus Walleij 	int ret = 0;
2087ffbbdd21SLinus Walleij 
20888caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2089ffbbdd21SLinus Walleij 
2090ffbbdd21SLinus Walleij 	/*
2091ffbbdd21SLinus Walleij 	 * This is a bit lame, but is optimized for the common execution path.
20928caab75fSGeert Uytterhoeven 	 * A wait_queue on the ctlr->busy could be used, but then the common
2093ffbbdd21SLinus Walleij 	 * execution path (pump_messages) would be required to call wake_up or
2094ffbbdd21SLinus Walleij 	 * friends on every SPI message. Do this instead.
2095ffbbdd21SLinus Walleij 	 */
20968caab75fSGeert Uytterhoeven 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
20978caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2098f97b26b0SAxel Lin 		usleep_range(10000, 11000);
20998caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->queue_lock, flags);
2100ffbbdd21SLinus Walleij 	}
2101ffbbdd21SLinus Walleij 
21028caab75fSGeert Uytterhoeven 	if (!list_empty(&ctlr->queue) || ctlr->busy)
2103ffbbdd21SLinus Walleij 		ret = -EBUSY;
2104ffbbdd21SLinus Walleij 	else
21058caab75fSGeert Uytterhoeven 		ctlr->running = false;
2106ffbbdd21SLinus Walleij 
21078caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2108ffbbdd21SLinus Walleij 
2109ffbbdd21SLinus Walleij 	if (ret) {
21108caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "could not stop message queue\n");
2111ffbbdd21SLinus Walleij 		return ret;
2112ffbbdd21SLinus Walleij 	}
2113ffbbdd21SLinus Walleij 	return ret;
2114ffbbdd21SLinus Walleij }
2115ffbbdd21SLinus Walleij 
21168caab75fSGeert Uytterhoeven static int spi_destroy_queue(struct spi_controller *ctlr)
2117ffbbdd21SLinus Walleij {
2118ffbbdd21SLinus Walleij 	int ret;
2119ffbbdd21SLinus Walleij 
21208caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
2121ffbbdd21SLinus Walleij 
2122ffbbdd21SLinus Walleij 	/*
21233989144fSPetr Mladek 	 * kthread_flush_worker will block until all work is done.
2124ffbbdd21SLinus Walleij 	 * If the reason that stop_queue timed out is that the work will never
2125ffbbdd21SLinus Walleij 	 * finish, then it does no good to call flush/stop thread, so
2126ffbbdd21SLinus Walleij 	 * return anyway.
2127ffbbdd21SLinus Walleij 	 */
2128ffbbdd21SLinus Walleij 	if (ret) {
21298caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem destroying queue\n");
2130ffbbdd21SLinus Walleij 		return ret;
2131ffbbdd21SLinus Walleij 	}
2132ffbbdd21SLinus Walleij 
213360a883d1SMarek Szyprowski 	kthread_destroy_worker(ctlr->kworker);
2134ffbbdd21SLinus Walleij 
2135ffbbdd21SLinus Walleij 	return 0;
2136ffbbdd21SLinus Walleij }
2137ffbbdd21SLinus Walleij 
21380461a414SMark Brown static int __spi_queued_transfer(struct spi_device *spi,
21390461a414SMark Brown 				 struct spi_message *msg,
21400461a414SMark Brown 				 bool need_pump)
2141ffbbdd21SLinus Walleij {
21428caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
2143ffbbdd21SLinus Walleij 	unsigned long flags;
2144ffbbdd21SLinus Walleij 
21458caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2146ffbbdd21SLinus Walleij 
21478caab75fSGeert Uytterhoeven 	if (!ctlr->running) {
21488caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2149ffbbdd21SLinus Walleij 		return -ESHUTDOWN;
2150ffbbdd21SLinus Walleij 	}
2151ffbbdd21SLinus Walleij 	msg->actual_length = 0;
2152ffbbdd21SLinus Walleij 	msg->status = -EINPROGRESS;
2153ffbbdd21SLinus Walleij 
21548caab75fSGeert Uytterhoeven 	list_add_tail(&msg->queue, &ctlr->queue);
2155ae7d2346SDavid Jander 	ctlr->queue_empty = false;
2156f0125f1aSMark Brown 	if (!ctlr->busy && need_pump)
215760a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2158ffbbdd21SLinus Walleij 
21598caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2160ffbbdd21SLinus Walleij 	return 0;
2161ffbbdd21SLinus Walleij }
2162ffbbdd21SLinus Walleij 
21630461a414SMark Brown /**
21640461a414SMark Brown  * spi_queued_transfer - transfer function for queued transfers
21650461a414SMark Brown  * @spi: spi device which is requesting transfer
21660461a414SMark Brown  * @msg: spi message which is to handled is queued to driver queue
216797d56dc6SJavier Martinez Canillas  *
216897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
21690461a414SMark Brown  */
21700461a414SMark Brown static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
21710461a414SMark Brown {
21720461a414SMark Brown 	return __spi_queued_transfer(spi, msg, true);
21730461a414SMark Brown }
21740461a414SMark Brown 
21758caab75fSGeert Uytterhoeven static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2176ffbbdd21SLinus Walleij {
2177ffbbdd21SLinus Walleij 	int ret;
2178ffbbdd21SLinus Walleij 
21798caab75fSGeert Uytterhoeven 	ctlr->transfer = spi_queued_transfer;
21808caab75fSGeert Uytterhoeven 	if (!ctlr->transfer_one_message)
21818caab75fSGeert Uytterhoeven 		ctlr->transfer_one_message = spi_transfer_one_message;
2182ffbbdd21SLinus Walleij 
2183ffbbdd21SLinus Walleij 	/* Initialize and start queue */
21848caab75fSGeert Uytterhoeven 	ret = spi_init_queue(ctlr);
2185ffbbdd21SLinus Walleij 	if (ret) {
21868caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem initializing queue\n");
2187ffbbdd21SLinus Walleij 		goto err_init_queue;
2188ffbbdd21SLinus Walleij 	}
21898caab75fSGeert Uytterhoeven 	ctlr->queued = true;
21908caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
2191ffbbdd21SLinus Walleij 	if (ret) {
21928caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem starting queue\n");
2193ffbbdd21SLinus Walleij 		goto err_start_queue;
2194ffbbdd21SLinus Walleij 	}
2195ffbbdd21SLinus Walleij 
2196ffbbdd21SLinus Walleij 	return 0;
2197ffbbdd21SLinus Walleij 
2198ffbbdd21SLinus Walleij err_start_queue:
21998caab75fSGeert Uytterhoeven 	spi_destroy_queue(ctlr);
2200c3676d5cSMark Brown err_init_queue:
2201ffbbdd21SLinus Walleij 	return ret;
2202ffbbdd21SLinus Walleij }
2203ffbbdd21SLinus Walleij 
2204988f259bSBoris Brezillon /**
2205988f259bSBoris Brezillon  * spi_flush_queue - Send all pending messages in the queue from the callers'
2206988f259bSBoris Brezillon  *		     context
2207988f259bSBoris Brezillon  * @ctlr: controller to process queue for
2208988f259bSBoris Brezillon  *
2209988f259bSBoris Brezillon  * This should be used when one wants to ensure all pending messages have been
2210988f259bSBoris Brezillon  * sent before doing something. Is used by the spi-mem code to make sure SPI
2211988f259bSBoris Brezillon  * memory operations do not preempt regular SPI transfers that have been queued
2212988f259bSBoris Brezillon  * before the spi-mem operation.
2213988f259bSBoris Brezillon  */
2214988f259bSBoris Brezillon void spi_flush_queue(struct spi_controller *ctlr)
2215988f259bSBoris Brezillon {
2216988f259bSBoris Brezillon 	if (ctlr->transfer == spi_queued_transfer)
2217988f259bSBoris Brezillon 		__spi_pump_messages(ctlr, false);
2218988f259bSBoris Brezillon }
2219988f259bSBoris Brezillon 
2220ffbbdd21SLinus Walleij /*-------------------------------------------------------------------------*/
2221ffbbdd21SLinus Walleij 
22227cb94361SAndreas Larsson #if defined(CONFIG_OF)
2223f276aacfSJanne Grunau static void of_spi_parse_dt_cs_delay(struct device_node *nc,
2224f276aacfSJanne Grunau 				     struct spi_delay *delay, const char *prop)
2225f276aacfSJanne Grunau {
2226f276aacfSJanne Grunau 	u32 value;
2227f276aacfSJanne Grunau 
2228f276aacfSJanne Grunau 	if (!of_property_read_u32(nc, prop, &value)) {
2229f276aacfSJanne Grunau 		if (value > U16_MAX) {
2230f276aacfSJanne Grunau 			delay->value = DIV_ROUND_UP(value, 1000);
2231f276aacfSJanne Grunau 			delay->unit = SPI_DELAY_UNIT_USECS;
2232f276aacfSJanne Grunau 		} else {
2233f276aacfSJanne Grunau 			delay->value = value;
2234f276aacfSJanne Grunau 			delay->unit = SPI_DELAY_UNIT_NSECS;
2235f276aacfSJanne Grunau 		}
2236f276aacfSJanne Grunau 	}
2237f276aacfSJanne Grunau }
2238f276aacfSJanne Grunau 
22398caab75fSGeert Uytterhoeven static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2240c2e51ac3SGeert Uytterhoeven 			   struct device_node *nc)
2241d57a4282SGrant Likely {
224289da4293STrent Piepho 	u32 value;
2243c2e51ac3SGeert Uytterhoeven 	int rc;
2244d57a4282SGrant Likely 
2245d57a4282SGrant Likely 	/* Mode (clock phase/polarity/etc.) */
2246e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpha"))
2247d57a4282SGrant Likely 		spi->mode |= SPI_CPHA;
2248e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpol"))
2249d57a4282SGrant Likely 		spi->mode |= SPI_CPOL;
2250e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-3wire"))
2251c20151dfSLars-Peter Clausen 		spi->mode |= SPI_3WIRE;
2252e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-lsb-first"))
2253cd6339e6SZhao Qiang 		spi->mode |= SPI_LSB_FIRST;
22543e5ec1dbSGregory CLEMENT 	if (of_property_read_bool(nc, "spi-cs-high"))
2255f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
2256f3186dd8SLinus Walleij 
2257f477b7fbSwangyuhang 	/* Device DUAL/QUAD mode */
225889da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
225989da4293STrent Piepho 		switch (value) {
2260d962608cSDragos Bogdan 		case 0:
2261d962608cSDragos Bogdan 			spi->mode |= SPI_NO_TX;
2262d962608cSDragos Bogdan 			break;
226389da4293STrent Piepho 		case 1:
2264f477b7fbSwangyuhang 			break;
226589da4293STrent Piepho 		case 2:
2266f477b7fbSwangyuhang 			spi->mode |= SPI_TX_DUAL;
2267f477b7fbSwangyuhang 			break;
226889da4293STrent Piepho 		case 4:
2269f477b7fbSwangyuhang 			spi->mode |= SPI_TX_QUAD;
2270f477b7fbSwangyuhang 			break;
22716b03061fSYogesh Narayan Gaur 		case 8:
22726b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_TX_OCTAL;
22736b03061fSYogesh Narayan Gaur 			break;
2274f477b7fbSwangyuhang 		default:
22758caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2276a110f93dSwangyuhang 				"spi-tx-bus-width %d not supported\n",
227789da4293STrent Piepho 				value);
227880874d8cSGeert Uytterhoeven 			break;
2279f477b7fbSwangyuhang 		}
2280a822e99cSMark Brown 	}
2281f477b7fbSwangyuhang 
228289da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
228389da4293STrent Piepho 		switch (value) {
2284d962608cSDragos Bogdan 		case 0:
2285d962608cSDragos Bogdan 			spi->mode |= SPI_NO_RX;
2286d962608cSDragos Bogdan 			break;
228789da4293STrent Piepho 		case 1:
2288f477b7fbSwangyuhang 			break;
228989da4293STrent Piepho 		case 2:
2290f477b7fbSwangyuhang 			spi->mode |= SPI_RX_DUAL;
2291f477b7fbSwangyuhang 			break;
229289da4293STrent Piepho 		case 4:
2293f477b7fbSwangyuhang 			spi->mode |= SPI_RX_QUAD;
2294f477b7fbSwangyuhang 			break;
22956b03061fSYogesh Narayan Gaur 		case 8:
22966b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_RX_OCTAL;
22976b03061fSYogesh Narayan Gaur 			break;
2298f477b7fbSwangyuhang 		default:
22998caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2300a110f93dSwangyuhang 				"spi-rx-bus-width %d not supported\n",
230189da4293STrent Piepho 				value);
230280874d8cSGeert Uytterhoeven 			break;
2303f477b7fbSwangyuhang 		}
2304a822e99cSMark Brown 	}
2305f477b7fbSwangyuhang 
23068caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr)) {
2307194276b0SRob Herring 		if (!of_node_name_eq(nc, "slave")) {
230825c56c88SRob Herring 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
230925c56c88SRob Herring 				nc);
23106c364062SGeert Uytterhoeven 			return -EINVAL;
23116c364062SGeert Uytterhoeven 		}
23126c364062SGeert Uytterhoeven 		return 0;
23136c364062SGeert Uytterhoeven 	}
23146c364062SGeert Uytterhoeven 
23156c364062SGeert Uytterhoeven 	/* Device address */
23166c364062SGeert Uytterhoeven 	rc = of_property_read_u32(nc, "reg", &value);
23176c364062SGeert Uytterhoeven 	if (rc) {
231825c56c88SRob Herring 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
231925c56c88SRob Herring 			nc, rc);
23206c364062SGeert Uytterhoeven 		return rc;
23216c364062SGeert Uytterhoeven 	}
23226c364062SGeert Uytterhoeven 	spi->chip_select = value;
23236c364062SGeert Uytterhoeven 
2324d57a4282SGrant Likely 	/* Device speed */
2325671c3bf5SChuanhong Guo 	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
232689da4293STrent Piepho 		spi->max_speed_hz = value;
2327d57a4282SGrant Likely 
2328f276aacfSJanne Grunau 	/* Device CS delays */
2329f276aacfSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_setup, "spi-cs-setup-delay-ns");
2330*5827b31dSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_hold, "spi-cs-hold-delay-ns");
2331*5827b31dSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_inactive, "spi-cs-inactive-delay-ns");
233233a2fde5STudor Ambarus 
2333c2e51ac3SGeert Uytterhoeven 	return 0;
2334c2e51ac3SGeert Uytterhoeven }
2335c2e51ac3SGeert Uytterhoeven 
2336c2e51ac3SGeert Uytterhoeven static struct spi_device *
23378caab75fSGeert Uytterhoeven of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2338c2e51ac3SGeert Uytterhoeven {
2339c2e51ac3SGeert Uytterhoeven 	struct spi_device *spi;
2340c2e51ac3SGeert Uytterhoeven 	int rc;
2341c2e51ac3SGeert Uytterhoeven 
2342c2e51ac3SGeert Uytterhoeven 	/* Alloc an spi_device */
23438caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
2344c2e51ac3SGeert Uytterhoeven 	if (!spi) {
234525c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2346c2e51ac3SGeert Uytterhoeven 		rc = -ENOMEM;
2347c2e51ac3SGeert Uytterhoeven 		goto err_out;
2348c2e51ac3SGeert Uytterhoeven 	}
2349c2e51ac3SGeert Uytterhoeven 
2350c2e51ac3SGeert Uytterhoeven 	/* Select device driver */
2351c2e51ac3SGeert Uytterhoeven 	rc = of_modalias_node(nc, spi->modalias,
2352c2e51ac3SGeert Uytterhoeven 				sizeof(spi->modalias));
2353c2e51ac3SGeert Uytterhoeven 	if (rc < 0) {
235425c56c88SRob Herring 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2355c2e51ac3SGeert Uytterhoeven 		goto err_out;
2356c2e51ac3SGeert Uytterhoeven 	}
2357c2e51ac3SGeert Uytterhoeven 
23588caab75fSGeert Uytterhoeven 	rc = of_spi_parse_dt(ctlr, spi, nc);
2359c2e51ac3SGeert Uytterhoeven 	if (rc)
2360c2e51ac3SGeert Uytterhoeven 		goto err_out;
2361c2e51ac3SGeert Uytterhoeven 
2362d57a4282SGrant Likely 	/* Store a pointer to the node in the device structure */
2363d57a4282SGrant Likely 	of_node_get(nc);
2364d57a4282SGrant Likely 	spi->dev.of_node = nc;
23650e793ba7SCharles Keepax 	spi->dev.fwnode = of_fwnode_handle(nc);
2366d57a4282SGrant Likely 
2367d57a4282SGrant Likely 	/* Register the new device */
2368d57a4282SGrant Likely 	rc = spi_add_device(spi);
2369d57a4282SGrant Likely 	if (rc) {
237025c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
23718324147fSJohan Hovold 		goto err_of_node_put;
2372d57a4282SGrant Likely 	}
2373d57a4282SGrant Likely 
2374aff5e3f8SPantelis Antoniou 	return spi;
2375aff5e3f8SPantelis Antoniou 
23768324147fSJohan Hovold err_of_node_put:
23778324147fSJohan Hovold 	of_node_put(nc);
2378aff5e3f8SPantelis Antoniou err_out:
2379aff5e3f8SPantelis Antoniou 	spi_dev_put(spi);
2380aff5e3f8SPantelis Antoniou 	return ERR_PTR(rc);
2381aff5e3f8SPantelis Antoniou }
2382aff5e3f8SPantelis Antoniou 
2383aff5e3f8SPantelis Antoniou /**
2384aff5e3f8SPantelis Antoniou  * of_register_spi_devices() - Register child devices onto the SPI bus
23858caab75fSGeert Uytterhoeven  * @ctlr:	Pointer to spi_controller device
2386aff5e3f8SPantelis Antoniou  *
23876c364062SGeert Uytterhoeven  * Registers an spi_device for each child node of controller node which
23886c364062SGeert Uytterhoeven  * represents a valid SPI slave.
2389aff5e3f8SPantelis Antoniou  */
23908caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr)
2391aff5e3f8SPantelis Antoniou {
2392aff5e3f8SPantelis Antoniou 	struct spi_device *spi;
2393aff5e3f8SPantelis Antoniou 	struct device_node *nc;
2394aff5e3f8SPantelis Antoniou 
23958caab75fSGeert Uytterhoeven 	if (!ctlr->dev.of_node)
2396aff5e3f8SPantelis Antoniou 		return;
2397aff5e3f8SPantelis Antoniou 
23988caab75fSGeert Uytterhoeven 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2399bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2400bd6c1644SGeert Uytterhoeven 			continue;
24018caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, nc);
2402e0af98a7SRalf Ramsauer 		if (IS_ERR(spi)) {
24038caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
240425c56c88SRob Herring 				 "Failed to create SPI device for %pOF\n", nc);
2405e0af98a7SRalf Ramsauer 			of_node_clear_flag(nc, OF_POPULATED);
2406e0af98a7SRalf Ramsauer 		}
2407d57a4282SGrant Likely 	}
2408d57a4282SGrant Likely }
2409d57a4282SGrant Likely #else
24108caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr) { }
2411d57a4282SGrant Likely #endif
2412d57a4282SGrant Likely 
24130c79378cSSebastian Reichel /**
24140c79378cSSebastian Reichel  * spi_new_ancillary_device() - Register ancillary SPI device
24150c79378cSSebastian Reichel  * @spi:         Pointer to the main SPI device registering the ancillary device
24160c79378cSSebastian Reichel  * @chip_select: Chip Select of the ancillary device
24170c79378cSSebastian Reichel  *
24180c79378cSSebastian Reichel  * Register an ancillary SPI device; for example some chips have a chip-select
24190c79378cSSebastian Reichel  * for normal device usage and another one for setup/firmware upload.
24200c79378cSSebastian Reichel  *
24210c79378cSSebastian Reichel  * This may only be called from main SPI device's probe routine.
24220c79378cSSebastian Reichel  *
24230c79378cSSebastian Reichel  * Return: 0 on success; negative errno on failure
24240c79378cSSebastian Reichel  */
24250c79378cSSebastian Reichel struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
24260c79378cSSebastian Reichel 					     u8 chip_select)
24270c79378cSSebastian Reichel {
24280c79378cSSebastian Reichel 	struct spi_device *ancillary;
24290c79378cSSebastian Reichel 	int rc = 0;
24300c79378cSSebastian Reichel 
24310c79378cSSebastian Reichel 	/* Alloc an spi_device */
24320c79378cSSebastian Reichel 	ancillary = spi_alloc_device(spi->controller);
24330c79378cSSebastian Reichel 	if (!ancillary) {
24340c79378cSSebastian Reichel 		rc = -ENOMEM;
24350c79378cSSebastian Reichel 		goto err_out;
24360c79378cSSebastian Reichel 	}
24370c79378cSSebastian Reichel 
243851e99de5SWolfram Sang 	strscpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
24390c79378cSSebastian Reichel 
24400c79378cSSebastian Reichel 	/* Use provided chip-select for ancillary device */
24410c79378cSSebastian Reichel 	ancillary->chip_select = chip_select;
24420c79378cSSebastian Reichel 
24430c79378cSSebastian Reichel 	/* Take over SPI mode/speed from SPI main device */
24440c79378cSSebastian Reichel 	ancillary->max_speed_hz = spi->max_speed_hz;
2445b01d5506SColin Ian King 	ancillary->mode = spi->mode;
24460c79378cSSebastian Reichel 
24470c79378cSSebastian Reichel 	/* Register the new device */
24480c79378cSSebastian Reichel 	rc = spi_add_device_locked(ancillary);
24490c79378cSSebastian Reichel 	if (rc) {
24500c79378cSSebastian Reichel 		dev_err(&spi->dev, "failed to register ancillary device\n");
24510c79378cSSebastian Reichel 		goto err_out;
24520c79378cSSebastian Reichel 	}
24530c79378cSSebastian Reichel 
24540c79378cSSebastian Reichel 	return ancillary;
24550c79378cSSebastian Reichel 
24560c79378cSSebastian Reichel err_out:
24570c79378cSSebastian Reichel 	spi_dev_put(ancillary);
24580c79378cSSebastian Reichel 	return ERR_PTR(rc);
24590c79378cSSebastian Reichel }
24600c79378cSSebastian Reichel EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
24610c79378cSSebastian Reichel 
246264bee4d2SMika Westerberg #ifdef CONFIG_ACPI
24634c3c5954SArd Biesheuvel struct acpi_spi_lookup {
24644c3c5954SArd Biesheuvel 	struct spi_controller 	*ctlr;
24654c3c5954SArd Biesheuvel 	u32			max_speed_hz;
24664c3c5954SArd Biesheuvel 	u32			mode;
24674c3c5954SArd Biesheuvel 	int			irq;
24684c3c5954SArd Biesheuvel 	u8			bits_per_word;
24694c3c5954SArd Biesheuvel 	u8			chip_select;
247087e59b36SStefan Binding 	int			n;
247187e59b36SStefan Binding 	int			index;
24724c3c5954SArd Biesheuvel };
24734c3c5954SArd Biesheuvel 
2474e612af7aSStefan Binding static int acpi_spi_count(struct acpi_resource *ares, void *data)
2475e612af7aSStefan Binding {
2476e612af7aSStefan Binding 	struct acpi_resource_spi_serialbus *sb;
2477e612af7aSStefan Binding 	int *count = data;
2478e612af7aSStefan Binding 
2479e612af7aSStefan Binding 	if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2480e612af7aSStefan Binding 		return 1;
2481e612af7aSStefan Binding 
2482e612af7aSStefan Binding 	sb = &ares->data.spi_serial_bus;
2483e612af7aSStefan Binding 	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2484e612af7aSStefan Binding 		return 1;
2485e612af7aSStefan Binding 
2486e612af7aSStefan Binding 	*count = *count + 1;
2487e612af7aSStefan Binding 
2488e612af7aSStefan Binding 	return 1;
2489e612af7aSStefan Binding }
2490e612af7aSStefan Binding 
2491e612af7aSStefan Binding /**
2492e612af7aSStefan Binding  * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2493e612af7aSStefan Binding  * @adev:	ACPI device
2494e612af7aSStefan Binding  *
2495e612af7aSStefan Binding  * Returns the number of SpiSerialBus resources in the ACPI-device's
2496e612af7aSStefan Binding  * resource-list; or a negative error code.
2497e612af7aSStefan Binding  */
2498e612af7aSStefan Binding int acpi_spi_count_resources(struct acpi_device *adev)
2499e612af7aSStefan Binding {
2500e612af7aSStefan Binding 	LIST_HEAD(r);
2501e612af7aSStefan Binding 	int count = 0;
2502e612af7aSStefan Binding 	int ret;
2503e612af7aSStefan Binding 
2504e612af7aSStefan Binding 	ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2505e612af7aSStefan Binding 	if (ret < 0)
2506e612af7aSStefan Binding 		return ret;
2507e612af7aSStefan Binding 
2508e612af7aSStefan Binding 	acpi_dev_free_resource_list(&r);
2509e612af7aSStefan Binding 
2510e612af7aSStefan Binding 	return count;
2511e612af7aSStefan Binding }
2512e612af7aSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2513e612af7aSStefan Binding 
25144c3c5954SArd Biesheuvel static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
25154c3c5954SArd Biesheuvel 					    struct acpi_spi_lookup *lookup)
25168a2e487eSLukas Wunner {
25178a2e487eSLukas Wunner 	const union acpi_object *obj;
25188a2e487eSLukas Wunner 
25198a2e487eSLukas Wunner 	if (!x86_apple_machine)
25208a2e487eSLukas Wunner 		return;
25218a2e487eSLukas Wunner 
25228a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
25238a2e487eSLukas Wunner 	    && obj->buffer.length >= 4)
25244c3c5954SArd Biesheuvel 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
25258a2e487eSLukas Wunner 
25268a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
25278a2e487eSLukas Wunner 	    && obj->buffer.length == 8)
25284c3c5954SArd Biesheuvel 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
25298a2e487eSLukas Wunner 
25308a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
25318a2e487eSLukas Wunner 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
25324c3c5954SArd Biesheuvel 		lookup->mode |= SPI_LSB_FIRST;
25338a2e487eSLukas Wunner 
25348a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
25358a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
25364c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPOL;
25378a2e487eSLukas Wunner 
25388a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
25398a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
25404c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPHA;
25418a2e487eSLukas Wunner }
25428a2e487eSLukas Wunner 
254387e59b36SStefan Binding static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
254487e59b36SStefan Binding 
254564bee4d2SMika Westerberg static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
254664bee4d2SMika Westerberg {
25474c3c5954SArd Biesheuvel 	struct acpi_spi_lookup *lookup = data;
25484c3c5954SArd Biesheuvel 	struct spi_controller *ctlr = lookup->ctlr;
254964bee4d2SMika Westerberg 
255064bee4d2SMika Westerberg 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
255164bee4d2SMika Westerberg 		struct acpi_resource_spi_serialbus *sb;
25524c3c5954SArd Biesheuvel 		acpi_handle parent_handle;
25534c3c5954SArd Biesheuvel 		acpi_status status;
255464bee4d2SMika Westerberg 
255564bee4d2SMika Westerberg 		sb = &ares->data.spi_serial_bus;
255664bee4d2SMika Westerberg 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
25574c3c5954SArd Biesheuvel 
255887e59b36SStefan Binding 			if (lookup->index != -1 && lookup->n++ != lookup->index)
255987e59b36SStefan Binding 				return 1;
256087e59b36SStefan Binding 
25614c3c5954SArd Biesheuvel 			status = acpi_get_handle(NULL,
25624c3c5954SArd Biesheuvel 						 sb->resource_source.string_ptr,
25634c3c5954SArd Biesheuvel 						 &parent_handle);
25644c3c5954SArd Biesheuvel 
256587e59b36SStefan Binding 			if (ACPI_FAILURE(status))
25664c3c5954SArd Biesheuvel 				return -ENODEV;
25674c3c5954SArd Biesheuvel 
256887e59b36SStefan Binding 			if (ctlr) {
256987e59b36SStefan Binding 				if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
257087e59b36SStefan Binding 					return -ENODEV;
257187e59b36SStefan Binding 			} else {
257287e59b36SStefan Binding 				struct acpi_device *adev;
257387e59b36SStefan Binding 
2574ac2a3feeSRafael J. Wysocki 				adev = acpi_fetch_acpi_dev(parent_handle);
2575ac2a3feeSRafael J. Wysocki 				if (!adev)
257687e59b36SStefan Binding 					return -ENODEV;
257787e59b36SStefan Binding 
257887e59b36SStefan Binding 				ctlr = acpi_spi_find_controller_by_adev(adev);
257987e59b36SStefan Binding 				if (!ctlr)
25809c22ec4aSAndy Shevchenko 					return -EPROBE_DEFER;
258187e59b36SStefan Binding 
258287e59b36SStefan Binding 				lookup->ctlr = ctlr;
258387e59b36SStefan Binding 			}
258487e59b36SStefan Binding 
2585a0a90718SMika Westerberg 			/*
2586a0a90718SMika Westerberg 			 * ACPI DeviceSelection numbering is handled by the
2587a0a90718SMika Westerberg 			 * host controller driver in Windows and can vary
2588a0a90718SMika Westerberg 			 * from driver to driver. In Linux we always expect
2589a0a90718SMika Westerberg 			 * 0 .. max - 1 so we need to ask the driver to
2590a0a90718SMika Westerberg 			 * translate between the two schemes.
2591a0a90718SMika Westerberg 			 */
25928caab75fSGeert Uytterhoeven 			if (ctlr->fw_translate_cs) {
25938caab75fSGeert Uytterhoeven 				int cs = ctlr->fw_translate_cs(ctlr,
2594a0a90718SMika Westerberg 						sb->device_selection);
2595a0a90718SMika Westerberg 				if (cs < 0)
2596a0a90718SMika Westerberg 					return cs;
25974c3c5954SArd Biesheuvel 				lookup->chip_select = cs;
2598a0a90718SMika Westerberg 			} else {
25994c3c5954SArd Biesheuvel 				lookup->chip_select = sb->device_selection;
2600a0a90718SMika Westerberg 			}
2601a0a90718SMika Westerberg 
26024c3c5954SArd Biesheuvel 			lookup->max_speed_hz = sb->connection_speed;
26030dadde34SAndy Shevchenko 			lookup->bits_per_word = sb->data_bit_length;
260464bee4d2SMika Westerberg 
260564bee4d2SMika Westerberg 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
26064c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPHA;
260764bee4d2SMika Westerberg 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
26084c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPOL;
260964bee4d2SMika Westerberg 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
26104c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CS_HIGH;
261164bee4d2SMika Westerberg 		}
26124c3c5954SArd Biesheuvel 	} else if (lookup->irq < 0) {
261364bee4d2SMika Westerberg 		struct resource r;
261464bee4d2SMika Westerberg 
261564bee4d2SMika Westerberg 		if (acpi_dev_resource_interrupt(ares, 0, &r))
26164c3c5954SArd Biesheuvel 			lookup->irq = r.start;
261764bee4d2SMika Westerberg 	}
261864bee4d2SMika Westerberg 
261964bee4d2SMika Westerberg 	/* Always tell the ACPI core to skip this resource */
262064bee4d2SMika Westerberg 	return 1;
262164bee4d2SMika Westerberg }
262264bee4d2SMika Westerberg 
2623000bee0eSStefan Binding /**
2624000bee0eSStefan Binding  * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2625000bee0eSStefan Binding  * @ctlr: controller to which the spi device belongs
2626000bee0eSStefan Binding  * @adev: ACPI Device for the spi device
262787e59b36SStefan Binding  * @index: Index of the spi resource inside the ACPI Node
2628000bee0eSStefan Binding  *
2629000bee0eSStefan Binding  * This should be used to allocate a new spi device from and ACPI Node.
2630000bee0eSStefan Binding  * The caller is responsible for calling spi_add_device to register the spi device.
2631000bee0eSStefan Binding  *
263287e59b36SStefan Binding  * If ctlr is set to NULL, the Controller for the spi device will be looked up
263387e59b36SStefan Binding  * using the resource.
263487e59b36SStefan Binding  * If index is set to -1, index is not used.
263587e59b36SStefan Binding  * Note: If index is -1, ctlr must be set.
263687e59b36SStefan Binding  *
2637000bee0eSStefan Binding  * Return: a pointer to the new device, or ERR_PTR on error.
2638000bee0eSStefan Binding  */
2639000bee0eSStefan Binding struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
264087e59b36SStefan Binding 					 struct acpi_device *adev,
264187e59b36SStefan Binding 					 int index)
264264bee4d2SMika Westerberg {
26434c3c5954SArd Biesheuvel 	acpi_handle parent_handle = NULL;
264464bee4d2SMika Westerberg 	struct list_head resource_list;
2645b28944c6SArd Biesheuvel 	struct acpi_spi_lookup lookup = {};
264664bee4d2SMika Westerberg 	struct spi_device *spi;
264764bee4d2SMika Westerberg 	int ret;
264864bee4d2SMika Westerberg 
264987e59b36SStefan Binding 	if (!ctlr && index == -1)
265087e59b36SStefan Binding 		return ERR_PTR(-EINVAL);
265187e59b36SStefan Binding 
26524c3c5954SArd Biesheuvel 	lookup.ctlr		= ctlr;
26534c3c5954SArd Biesheuvel 	lookup.irq		= -1;
265487e59b36SStefan Binding 	lookup.index		= index;
265587e59b36SStefan Binding 	lookup.n		= 0;
26564c3c5954SArd Biesheuvel 
26574c3c5954SArd Biesheuvel 	INIT_LIST_HEAD(&resource_list);
26584c3c5954SArd Biesheuvel 	ret = acpi_dev_get_resources(adev, &resource_list,
26594c3c5954SArd Biesheuvel 				     acpi_spi_add_resource, &lookup);
26604c3c5954SArd Biesheuvel 	acpi_dev_free_resource_list(&resource_list);
26614c3c5954SArd Biesheuvel 
26624c3c5954SArd Biesheuvel 	if (ret < 0)
266395c8222fSDavid Jander 		/* Found SPI in _CRS but it points to another controller */
2664b6747f4fSAndy Shevchenko 		return ERR_PTR(ret);
26654c3c5954SArd Biesheuvel 
26664c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz &&
266710e92724SBjorn Helgaas 	    ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
266887e59b36SStefan Binding 	    ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
26694c3c5954SArd Biesheuvel 		/* Apple does not use _CRS but nested devices for SPI slaves */
26704c3c5954SArd Biesheuvel 		acpi_spi_parse_apple_properties(adev, &lookup);
26714c3c5954SArd Biesheuvel 	}
26724c3c5954SArd Biesheuvel 
26734c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz)
2674000bee0eSStefan Binding 		return ERR_PTR(-ENODEV);
26754c3c5954SArd Biesheuvel 
267687e59b36SStefan Binding 	spi = spi_alloc_device(lookup.ctlr);
267764bee4d2SMika Westerberg 	if (!spi) {
267887e59b36SStefan Binding 		dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
267964bee4d2SMika Westerberg 			dev_name(&adev->dev));
2680000bee0eSStefan Binding 		return ERR_PTR(-ENOMEM);
268164bee4d2SMika Westerberg 	}
268264bee4d2SMika Westerberg 
26837b199811SRafael J. Wysocki 	ACPI_COMPANION_SET(&spi->dev, adev);
26844c3c5954SArd Biesheuvel 	spi->max_speed_hz	= lookup.max_speed_hz;
2685ea235786SJohn Garry 	spi->mode		|= lookup.mode;
26864c3c5954SArd Biesheuvel 	spi->irq		= lookup.irq;
26874c3c5954SArd Biesheuvel 	spi->bits_per_word	= lookup.bits_per_word;
26884c3c5954SArd Biesheuvel 	spi->chip_select	= lookup.chip_select;
268964bee4d2SMika Westerberg 
2690000bee0eSStefan Binding 	return spi;
2691000bee0eSStefan Binding }
2692000bee0eSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2693000bee0eSStefan Binding 
2694000bee0eSStefan Binding static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2695000bee0eSStefan Binding 					    struct acpi_device *adev)
2696000bee0eSStefan Binding {
2697000bee0eSStefan Binding 	struct spi_device *spi;
2698000bee0eSStefan Binding 
2699000bee0eSStefan Binding 	if (acpi_bus_get_status(adev) || !adev->status.present ||
2700000bee0eSStefan Binding 	    acpi_device_enumerated(adev))
2701000bee0eSStefan Binding 		return AE_OK;
2702000bee0eSStefan Binding 
270387e59b36SStefan Binding 	spi = acpi_spi_device_alloc(ctlr, adev, -1);
2704000bee0eSStefan Binding 	if (IS_ERR(spi)) {
2705000bee0eSStefan Binding 		if (PTR_ERR(spi) == -ENOMEM)
2706000bee0eSStefan Binding 			return AE_NO_MEMORY;
2707000bee0eSStefan Binding 		else
2708000bee0eSStefan Binding 			return AE_OK;
2709000bee0eSStefan Binding 	}
2710000bee0eSStefan Binding 
27110c6543f6SDan O'Donovan 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
27120c6543f6SDan O'Donovan 			  sizeof(spi->modalias));
27130c6543f6SDan O'Donovan 
271433ada67dSChristophe RICARD 	if (spi->irq < 0)
271533ada67dSChristophe RICARD 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
271633ada67dSChristophe RICARD 
27177f24467fSOctavian Purdila 	acpi_device_set_enumerated(adev);
27187f24467fSOctavian Purdila 
271933cf00e5SMika Westerberg 	adev->power.flags.ignore_parent = true;
272064bee4d2SMika Westerberg 	if (spi_add_device(spi)) {
272133cf00e5SMika Westerberg 		adev->power.flags.ignore_parent = false;
27228caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
272364bee4d2SMika Westerberg 			dev_name(&adev->dev));
272464bee4d2SMika Westerberg 		spi_dev_put(spi);
272564bee4d2SMika Westerberg 	}
272664bee4d2SMika Westerberg 
272764bee4d2SMika Westerberg 	return AE_OK;
272864bee4d2SMika Westerberg }
272964bee4d2SMika Westerberg 
27307f24467fSOctavian Purdila static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
27317f24467fSOctavian Purdila 				       void *data, void **return_value)
27327f24467fSOctavian Purdila {
27337030c428SRafael J. Wysocki 	struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
27348caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = data;
27357f24467fSOctavian Purdila 
27367030c428SRafael J. Wysocki 	if (!adev)
27377f24467fSOctavian Purdila 		return AE_OK;
27387f24467fSOctavian Purdila 
27398caab75fSGeert Uytterhoeven 	return acpi_register_spi_device(ctlr, adev);
27407f24467fSOctavian Purdila }
27417f24467fSOctavian Purdila 
27424c3c5954SArd Biesheuvel #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
27434c3c5954SArd Biesheuvel 
27448caab75fSGeert Uytterhoeven static void acpi_register_spi_devices(struct spi_controller *ctlr)
274564bee4d2SMika Westerberg {
274664bee4d2SMika Westerberg 	acpi_status status;
274764bee4d2SMika Westerberg 	acpi_handle handle;
274864bee4d2SMika Westerberg 
27498caab75fSGeert Uytterhoeven 	handle = ACPI_HANDLE(ctlr->dev.parent);
275064bee4d2SMika Westerberg 	if (!handle)
275164bee4d2SMika Westerberg 		return;
275264bee4d2SMika Westerberg 
27534c3c5954SArd Biesheuvel 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
27544c3c5954SArd Biesheuvel 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
27558caab75fSGeert Uytterhoeven 				     acpi_spi_add_device, NULL, ctlr, NULL);
275664bee4d2SMika Westerberg 	if (ACPI_FAILURE(status))
27578caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
275864bee4d2SMika Westerberg }
275964bee4d2SMika Westerberg #else
27608caab75fSGeert Uytterhoeven static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
276164bee4d2SMika Westerberg #endif /* CONFIG_ACPI */
276264bee4d2SMika Westerberg 
27638caab75fSGeert Uytterhoeven static void spi_controller_release(struct device *dev)
27648ae12a0dSDavid Brownell {
27658caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
27668ae12a0dSDavid Brownell 
27678caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
27688caab75fSGeert Uytterhoeven 	kfree(ctlr);
27698ae12a0dSDavid Brownell }
27708ae12a0dSDavid Brownell 
27718ae12a0dSDavid Brownell static struct class spi_master_class = {
27728ae12a0dSDavid Brownell 	.name		= "spi_master",
27738ae12a0dSDavid Brownell 	.owner		= THIS_MODULE,
27748caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
2775eca2ebc7SMartin Sperl 	.dev_groups	= spi_master_groups,
27768ae12a0dSDavid Brownell };
27778ae12a0dSDavid Brownell 
27786c364062SGeert Uytterhoeven #ifdef CONFIG_SPI_SLAVE
27796c364062SGeert Uytterhoeven /**
27806c364062SGeert Uytterhoeven  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
27816c364062SGeert Uytterhoeven  *		     controller
27826c364062SGeert Uytterhoeven  * @spi: device used for the current transfer
27836c364062SGeert Uytterhoeven  */
27846c364062SGeert Uytterhoeven int spi_slave_abort(struct spi_device *spi)
27856c364062SGeert Uytterhoeven {
27868caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
27876c364062SGeert Uytterhoeven 
27888caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
27898caab75fSGeert Uytterhoeven 		return ctlr->slave_abort(ctlr);
27906c364062SGeert Uytterhoeven 
27916c364062SGeert Uytterhoeven 	return -ENOTSUPP;
27926c364062SGeert Uytterhoeven }
27936c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_slave_abort);
27946c364062SGeert Uytterhoeven 
2795b8d3b056SYang Yingliang int spi_target_abort(struct spi_device *spi)
2796b8d3b056SYang Yingliang {
2797b8d3b056SYang Yingliang 	struct spi_controller *ctlr = spi->controller;
2798b8d3b056SYang Yingliang 
2799b8d3b056SYang Yingliang 	if (spi_controller_is_target(ctlr) && ctlr->target_abort)
2800b8d3b056SYang Yingliang 		return ctlr->target_abort(ctlr);
2801b8d3b056SYang Yingliang 
2802b8d3b056SYang Yingliang 	return -ENOTSUPP;
2803b8d3b056SYang Yingliang }
2804b8d3b056SYang Yingliang EXPORT_SYMBOL_GPL(spi_target_abort);
2805b8d3b056SYang Yingliang 
2806cc8b4659SGeert Uytterhoeven static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2807cc8b4659SGeert Uytterhoeven 			  char *buf)
28086c364062SGeert Uytterhoeven {
28098caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
28108caab75fSGeert Uytterhoeven 						   dev);
28116c364062SGeert Uytterhoeven 	struct device *child;
28126c364062SGeert Uytterhoeven 
2813c21b0837SAndy Shevchenko 	child = device_find_any_child(&ctlr->dev);
28146c364062SGeert Uytterhoeven 	return sprintf(buf, "%s\n",
28156c364062SGeert Uytterhoeven 		       child ? to_spi_device(child)->modalias : NULL);
28166c364062SGeert Uytterhoeven }
28176c364062SGeert Uytterhoeven 
2818cc8b4659SGeert Uytterhoeven static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2819cc8b4659SGeert Uytterhoeven 			   const char *buf, size_t count)
28206c364062SGeert Uytterhoeven {
28218caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
28228caab75fSGeert Uytterhoeven 						   dev);
28236c364062SGeert Uytterhoeven 	struct spi_device *spi;
28246c364062SGeert Uytterhoeven 	struct device *child;
28256c364062SGeert Uytterhoeven 	char name[32];
28266c364062SGeert Uytterhoeven 	int rc;
28276c364062SGeert Uytterhoeven 
28286c364062SGeert Uytterhoeven 	rc = sscanf(buf, "%31s", name);
28296c364062SGeert Uytterhoeven 	if (rc != 1 || !name[0])
28306c364062SGeert Uytterhoeven 		return -EINVAL;
28316c364062SGeert Uytterhoeven 
2832c21b0837SAndy Shevchenko 	child = device_find_any_child(&ctlr->dev);
28336c364062SGeert Uytterhoeven 	if (child) {
28346c364062SGeert Uytterhoeven 		/* Remove registered slave */
28356c364062SGeert Uytterhoeven 		device_unregister(child);
28366c364062SGeert Uytterhoeven 		put_device(child);
28376c364062SGeert Uytterhoeven 	}
28386c364062SGeert Uytterhoeven 
28396c364062SGeert Uytterhoeven 	if (strcmp(name, "(null)")) {
28406c364062SGeert Uytterhoeven 		/* Register new slave */
28416c364062SGeert Uytterhoeven 		spi = spi_alloc_device(ctlr);
28426c364062SGeert Uytterhoeven 		if (!spi)
28436c364062SGeert Uytterhoeven 			return -ENOMEM;
28446c364062SGeert Uytterhoeven 
284551e99de5SWolfram Sang 		strscpy(spi->modalias, name, sizeof(spi->modalias));
28466c364062SGeert Uytterhoeven 
28476c364062SGeert Uytterhoeven 		rc = spi_add_device(spi);
28486c364062SGeert Uytterhoeven 		if (rc) {
28496c364062SGeert Uytterhoeven 			spi_dev_put(spi);
28506c364062SGeert Uytterhoeven 			return rc;
28516c364062SGeert Uytterhoeven 		}
28526c364062SGeert Uytterhoeven 	}
28536c364062SGeert Uytterhoeven 
28546c364062SGeert Uytterhoeven 	return count;
28556c364062SGeert Uytterhoeven }
28566c364062SGeert Uytterhoeven 
2857cc8b4659SGeert Uytterhoeven static DEVICE_ATTR_RW(slave);
28586c364062SGeert Uytterhoeven 
28596c364062SGeert Uytterhoeven static struct attribute *spi_slave_attrs[] = {
28606c364062SGeert Uytterhoeven 	&dev_attr_slave.attr,
28616c364062SGeert Uytterhoeven 	NULL,
28626c364062SGeert Uytterhoeven };
28636c364062SGeert Uytterhoeven 
28646c364062SGeert Uytterhoeven static const struct attribute_group spi_slave_group = {
28656c364062SGeert Uytterhoeven 	.attrs = spi_slave_attrs,
28666c364062SGeert Uytterhoeven };
28676c364062SGeert Uytterhoeven 
28686c364062SGeert Uytterhoeven static const struct attribute_group *spi_slave_groups[] = {
28698caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
28706c364062SGeert Uytterhoeven 	&spi_slave_group,
28716c364062SGeert Uytterhoeven 	NULL,
28726c364062SGeert Uytterhoeven };
28736c364062SGeert Uytterhoeven 
28746c364062SGeert Uytterhoeven static struct class spi_slave_class = {
28756c364062SGeert Uytterhoeven 	.name		= "spi_slave",
28766c364062SGeert Uytterhoeven 	.owner		= THIS_MODULE,
28778caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
28786c364062SGeert Uytterhoeven 	.dev_groups	= spi_slave_groups,
28796c364062SGeert Uytterhoeven };
28806c364062SGeert Uytterhoeven #else
28816c364062SGeert Uytterhoeven extern struct class spi_slave_class;	/* dummy */
28826c364062SGeert Uytterhoeven #endif
28838ae12a0dSDavid Brownell 
28848ae12a0dSDavid Brownell /**
28856c364062SGeert Uytterhoeven  * __spi_alloc_controller - allocate an SPI master or slave controller
28868ae12a0dSDavid Brownell  * @dev: the controller, possibly using the platform_bus
288733e34dc6SDavid Brownell  * @size: how much zeroed driver-private data to allocate; the pointer to this
2888229e6af1SLukas Wunner  *	memory is in the driver_data field of the returned device, accessible
2889229e6af1SLukas Wunner  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2890229e6af1SLukas Wunner  *	drivers granting DMA access to portions of their private data need to
2891229e6af1SLukas Wunner  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
28926c364062SGeert Uytterhoeven  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
28936c364062SGeert Uytterhoeven  *	slave (true) controller
289433e34dc6SDavid Brownell  * Context: can sleep
28958ae12a0dSDavid Brownell  *
28966c364062SGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
28978ae12a0dSDavid Brownell  * only ones directly touching chip registers.  It's how they allocate
28988caab75fSGeert Uytterhoeven  * an spi_controller structure, prior to calling spi_register_controller().
28998ae12a0dSDavid Brownell  *
290097d56dc6SJavier Martinez Canillas  * This must be called from context that can sleep.
29018ae12a0dSDavid Brownell  *
29026c364062SGeert Uytterhoeven  * The caller is responsible for assigning the bus number and initializing the
29038caab75fSGeert Uytterhoeven  * controller's methods before calling spi_register_controller(); and (after
29048caab75fSGeert Uytterhoeven  * errors adding the device) calling spi_controller_put() to prevent a memory
29058caab75fSGeert Uytterhoeven  * leak.
290697d56dc6SJavier Martinez Canillas  *
29076c364062SGeert Uytterhoeven  * Return: the SPI controller structure on success, else NULL.
29088ae12a0dSDavid Brownell  */
29098caab75fSGeert Uytterhoeven struct spi_controller *__spi_alloc_controller(struct device *dev,
29106c364062SGeert Uytterhoeven 					      unsigned int size, bool slave)
29118ae12a0dSDavid Brownell {
29128caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr;
2913229e6af1SLukas Wunner 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
29148ae12a0dSDavid Brownell 
29150c868461SDavid Brownell 	if (!dev)
29160c868461SDavid Brownell 		return NULL;
29170c868461SDavid Brownell 
2918229e6af1SLukas Wunner 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
29198caab75fSGeert Uytterhoeven 	if (!ctlr)
29208ae12a0dSDavid Brownell 		return NULL;
29218ae12a0dSDavid Brownell 
29228caab75fSGeert Uytterhoeven 	device_initialize(&ctlr->dev);
292316a8e2fbSUwe Kleine-König 	INIT_LIST_HEAD(&ctlr->queue);
292416a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->queue_lock);
292516a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->bus_lock_spinlock);
292616a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->bus_lock_mutex);
292716a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->io_mutex);
292816a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->add_lock);
29298caab75fSGeert Uytterhoeven 	ctlr->bus_num = -1;
29308caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = 1;
29318caab75fSGeert Uytterhoeven 	ctlr->slave = slave;
29326c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
29338caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_slave_class;
29346c364062SGeert Uytterhoeven 	else
29358caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_master_class;
29368caab75fSGeert Uytterhoeven 	ctlr->dev.parent = dev;
29378caab75fSGeert Uytterhoeven 	pm_suspend_ignore_children(&ctlr->dev, true);
2938229e6af1SLukas Wunner 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
29398ae12a0dSDavid Brownell 
29408caab75fSGeert Uytterhoeven 	return ctlr;
29418ae12a0dSDavid Brownell }
29426c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(__spi_alloc_controller);
29438ae12a0dSDavid Brownell 
29445e844cc3SLukas Wunner static void devm_spi_release_controller(struct device *dev, void *ctlr)
29455e844cc3SLukas Wunner {
29465e844cc3SLukas Wunner 	spi_controller_put(*(struct spi_controller **)ctlr);
29475e844cc3SLukas Wunner }
29485e844cc3SLukas Wunner 
29495e844cc3SLukas Wunner /**
29505e844cc3SLukas Wunner  * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
29515e844cc3SLukas Wunner  * @dev: physical device of SPI controller
29525e844cc3SLukas Wunner  * @size: how much zeroed driver-private data to allocate
29535e844cc3SLukas Wunner  * @slave: whether to allocate an SPI master (false) or SPI slave (true)
29545e844cc3SLukas Wunner  * Context: can sleep
29555e844cc3SLukas Wunner  *
29565e844cc3SLukas Wunner  * Allocate an SPI controller and automatically release a reference on it
29575e844cc3SLukas Wunner  * when @dev is unbound from its driver.  Drivers are thus relieved from
29585e844cc3SLukas Wunner  * having to call spi_controller_put().
29595e844cc3SLukas Wunner  *
29605e844cc3SLukas Wunner  * The arguments to this function are identical to __spi_alloc_controller().
29615e844cc3SLukas Wunner  *
29625e844cc3SLukas Wunner  * Return: the SPI controller structure on success, else NULL.
29635e844cc3SLukas Wunner  */
29645e844cc3SLukas Wunner struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
29655e844cc3SLukas Wunner 						   unsigned int size,
29665e844cc3SLukas Wunner 						   bool slave)
29675e844cc3SLukas Wunner {
29685e844cc3SLukas Wunner 	struct spi_controller **ptr, *ctlr;
29695e844cc3SLukas Wunner 
29705e844cc3SLukas Wunner 	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
29715e844cc3SLukas Wunner 			   GFP_KERNEL);
29725e844cc3SLukas Wunner 	if (!ptr)
29735e844cc3SLukas Wunner 		return NULL;
29745e844cc3SLukas Wunner 
29755e844cc3SLukas Wunner 	ctlr = __spi_alloc_controller(dev, size, slave);
29765e844cc3SLukas Wunner 	if (ctlr) {
2977794aaf01SWilliam A. Kennington III 		ctlr->devm_allocated = true;
29785e844cc3SLukas Wunner 		*ptr = ctlr;
29795e844cc3SLukas Wunner 		devres_add(dev, ptr);
29805e844cc3SLukas Wunner 	} else {
29815e844cc3SLukas Wunner 		devres_free(ptr);
29825e844cc3SLukas Wunner 	}
29835e844cc3SLukas Wunner 
29845e844cc3SLukas Wunner 	return ctlr;
29855e844cc3SLukas Wunner }
29865e844cc3SLukas Wunner EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
29875e844cc3SLukas Wunner 
2988f3186dd8SLinus Walleij /**
2989f3186dd8SLinus Walleij  * spi_get_gpio_descs() - grab chip select GPIOs for the master
2990f3186dd8SLinus Walleij  * @ctlr: The SPI master to grab GPIO descriptors for
2991f3186dd8SLinus Walleij  */
2992f3186dd8SLinus Walleij static int spi_get_gpio_descs(struct spi_controller *ctlr)
2993f3186dd8SLinus Walleij {
2994f3186dd8SLinus Walleij 	int nb, i;
2995f3186dd8SLinus Walleij 	struct gpio_desc **cs;
2996f3186dd8SLinus Walleij 	struct device *dev = &ctlr->dev;
29977d93aecdSGeert Uytterhoeven 	unsigned long native_cs_mask = 0;
29987d93aecdSGeert Uytterhoeven 	unsigned int num_cs_gpios = 0;
2999f3186dd8SLinus Walleij 
3000f3186dd8SLinus Walleij 	nb = gpiod_count(dev, "cs");
300131ed8ebcSAndy Shevchenko 	if (nb < 0) {
3002f3186dd8SLinus Walleij 		/* No GPIOs at all is fine, else return the error */
300331ed8ebcSAndy Shevchenko 		if (nb == -ENOENT)
3004f3186dd8SLinus Walleij 			return 0;
3005f3186dd8SLinus Walleij 		return nb;
300631ed8ebcSAndy Shevchenko 	}
300731ed8ebcSAndy Shevchenko 
300831ed8ebcSAndy Shevchenko 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
3009f3186dd8SLinus Walleij 
3010f3186dd8SLinus Walleij 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
3011f3186dd8SLinus Walleij 			  GFP_KERNEL);
3012f3186dd8SLinus Walleij 	if (!cs)
3013f3186dd8SLinus Walleij 		return -ENOMEM;
3014f3186dd8SLinus Walleij 	ctlr->cs_gpiods = cs;
3015f3186dd8SLinus Walleij 
3016f3186dd8SLinus Walleij 	for (i = 0; i < nb; i++) {
3017f3186dd8SLinus Walleij 		/*
3018f3186dd8SLinus Walleij 		 * Most chipselects are active low, the inverted
3019f3186dd8SLinus Walleij 		 * semantics are handled by special quirks in gpiolib,
3020f3186dd8SLinus Walleij 		 * so initializing them GPIOD_OUT_LOW here means
3021f3186dd8SLinus Walleij 		 * "unasserted", in most cases this will drive the physical
3022f3186dd8SLinus Walleij 		 * line high.
3023f3186dd8SLinus Walleij 		 */
3024f3186dd8SLinus Walleij 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
3025f3186dd8SLinus Walleij 						      GPIOD_OUT_LOW);
30261723fdecSGeert Uytterhoeven 		if (IS_ERR(cs[i]))
30271723fdecSGeert Uytterhoeven 			return PTR_ERR(cs[i]);
3028f3186dd8SLinus Walleij 
3029f3186dd8SLinus Walleij 		if (cs[i]) {
3030f3186dd8SLinus Walleij 			/*
3031f3186dd8SLinus Walleij 			 * If we find a CS GPIO, name it after the device and
3032f3186dd8SLinus Walleij 			 * chip select line.
3033f3186dd8SLinus Walleij 			 */
3034f3186dd8SLinus Walleij 			char *gpioname;
3035f3186dd8SLinus Walleij 
3036f3186dd8SLinus Walleij 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
3037f3186dd8SLinus Walleij 						  dev_name(dev), i);
3038f3186dd8SLinus Walleij 			if (!gpioname)
3039f3186dd8SLinus Walleij 				return -ENOMEM;
3040f3186dd8SLinus Walleij 			gpiod_set_consumer_name(cs[i], gpioname);
30417d93aecdSGeert Uytterhoeven 			num_cs_gpios++;
30427d93aecdSGeert Uytterhoeven 			continue;
3043f3186dd8SLinus Walleij 		}
30447d93aecdSGeert Uytterhoeven 
30457d93aecdSGeert Uytterhoeven 		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
30467d93aecdSGeert Uytterhoeven 			dev_err(dev, "Invalid native chip select %d\n", i);
30477d93aecdSGeert Uytterhoeven 			return -EINVAL;
30487d93aecdSGeert Uytterhoeven 		}
30497d93aecdSGeert Uytterhoeven 		native_cs_mask |= BIT(i);
30507d93aecdSGeert Uytterhoeven 	}
30517d93aecdSGeert Uytterhoeven 
3052f60d7270SAndy Shevchenko 	ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
3053dbaca8e5SAndy Shevchenko 
3054dbaca8e5SAndy Shevchenko 	if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
3055dbaca8e5SAndy Shevchenko 	    ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
30567d93aecdSGeert Uytterhoeven 		dev_err(dev, "No unused native chip select available\n");
30577d93aecdSGeert Uytterhoeven 		return -EINVAL;
3058f3186dd8SLinus Walleij 	}
3059f3186dd8SLinus Walleij 
3060f3186dd8SLinus Walleij 	return 0;
3061f3186dd8SLinus Walleij }
3062f3186dd8SLinus Walleij 
3063bdf3a3b5SBoris Brezillon static int spi_controller_check_ops(struct spi_controller *ctlr)
3064bdf3a3b5SBoris Brezillon {
3065bdf3a3b5SBoris Brezillon 	/*
3066b5932f5cSBoris Brezillon 	 * The controller may implement only the high-level SPI-memory like
3067b5932f5cSBoris Brezillon 	 * operations if it does not support regular SPI transfers, and this is
3068b5932f5cSBoris Brezillon 	 * valid use case.
3069b5932f5cSBoris Brezillon 	 * If ->mem_ops is NULL, we request that at least one of the
3070b5932f5cSBoris Brezillon 	 * ->transfer_xxx() method be implemented.
3071bdf3a3b5SBoris Brezillon 	 */
3072b5932f5cSBoris Brezillon 	if (ctlr->mem_ops) {
3073b5932f5cSBoris Brezillon 		if (!ctlr->mem_ops->exec_op)
3074bdf3a3b5SBoris Brezillon 			return -EINVAL;
3075b5932f5cSBoris Brezillon 	} else if (!ctlr->transfer && !ctlr->transfer_one &&
3076b5932f5cSBoris Brezillon 		   !ctlr->transfer_one_message) {
3077b5932f5cSBoris Brezillon 		return -EINVAL;
3078b5932f5cSBoris Brezillon 	}
3079bdf3a3b5SBoris Brezillon 
3080bdf3a3b5SBoris Brezillon 	return 0;
3081bdf3a3b5SBoris Brezillon }
3082bdf3a3b5SBoris Brezillon 
30838ae12a0dSDavid Brownell /**
30848caab75fSGeert Uytterhoeven  * spi_register_controller - register SPI master or slave controller
30858caab75fSGeert Uytterhoeven  * @ctlr: initialized master, originally from spi_alloc_master() or
30868caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
308733e34dc6SDavid Brownell  * Context: can sleep
30888ae12a0dSDavid Brownell  *
30898caab75fSGeert Uytterhoeven  * SPI controllers connect to their drivers using some non-SPI bus,
30908ae12a0dSDavid Brownell  * such as the platform bus.  The final stage of probe() in that code
30918caab75fSGeert Uytterhoeven  * includes calling spi_register_controller() to hook up to this SPI bus glue.
30928ae12a0dSDavid Brownell  *
30938ae12a0dSDavid Brownell  * SPI controllers use board specific (often SOC specific) bus numbers,
30948ae12a0dSDavid Brownell  * and board-specific addressing for SPI devices combines those numbers
30958ae12a0dSDavid Brownell  * with chip select numbers.  Since SPI does not directly support dynamic
30968ae12a0dSDavid Brownell  * device identification, boards need configuration tables telling which
30978ae12a0dSDavid Brownell  * chip is at which address.
30988ae12a0dSDavid Brownell  *
30998ae12a0dSDavid Brownell  * This must be called from context that can sleep.  It returns zero on
31008caab75fSGeert Uytterhoeven  * success, else a negative error code (dropping the controller's refcount).
31010c868461SDavid Brownell  * After a successful return, the caller is responsible for calling
31028caab75fSGeert Uytterhoeven  * spi_unregister_controller().
310397d56dc6SJavier Martinez Canillas  *
310497d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
31058ae12a0dSDavid Brownell  */
31068caab75fSGeert Uytterhoeven int spi_register_controller(struct spi_controller *ctlr)
31078ae12a0dSDavid Brownell {
31088caab75fSGeert Uytterhoeven 	struct device		*dev = ctlr->dev.parent;
31092b9603a0SFeng Tang 	struct boardinfo	*bi;
3110b93318a2SSergei Shtylyov 	int			status;
311142bdd706SLucas Stach 	int			id, first_dynamic;
31128ae12a0dSDavid Brownell 
31130c868461SDavid Brownell 	if (!dev)
31140c868461SDavid Brownell 		return -ENODEV;
31150c868461SDavid Brownell 
3116bdf3a3b5SBoris Brezillon 	/*
3117bdf3a3b5SBoris Brezillon 	 * Make sure all necessary hooks are implemented before registering
3118bdf3a3b5SBoris Brezillon 	 * the SPI controller.
3119bdf3a3b5SBoris Brezillon 	 */
3120bdf3a3b5SBoris Brezillon 	status = spi_controller_check_ops(ctlr);
3121bdf3a3b5SBoris Brezillon 	if (status)
3122bdf3a3b5SBoris Brezillon 		return status;
3123bdf3a3b5SBoris Brezillon 
312404b2d03aSGeert Uytterhoeven 	if (ctlr->bus_num >= 0) {
312595c8222fSDavid Jander 		/* Devices with a fixed bus num must check-in with the num */
312604b2d03aSGeert Uytterhoeven 		mutex_lock(&board_lock);
312704b2d03aSGeert Uytterhoeven 		id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
312804b2d03aSGeert Uytterhoeven 			ctlr->bus_num + 1, GFP_KERNEL);
312904b2d03aSGeert Uytterhoeven 		mutex_unlock(&board_lock);
313004b2d03aSGeert Uytterhoeven 		if (WARN(id < 0, "couldn't get idr"))
313104b2d03aSGeert Uytterhoeven 			return id == -ENOSPC ? -EBUSY : id;
313204b2d03aSGeert Uytterhoeven 		ctlr->bus_num = id;
313304b2d03aSGeert Uytterhoeven 	} else if (ctlr->dev.of_node) {
313495c8222fSDavid Jander 		/* Allocate dynamic bus number using Linux idr */
31359b61e302SSuniel Mahesh 		id = of_alias_get_id(ctlr->dev.of_node, "spi");
31369b61e302SSuniel Mahesh 		if (id >= 0) {
31379b61e302SSuniel Mahesh 			ctlr->bus_num = id;
31389b61e302SSuniel Mahesh 			mutex_lock(&board_lock);
31399b61e302SSuniel Mahesh 			id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
31409b61e302SSuniel Mahesh 				       ctlr->bus_num + 1, GFP_KERNEL);
31419b61e302SSuniel Mahesh 			mutex_unlock(&board_lock);
31429b61e302SSuniel Mahesh 			if (WARN(id < 0, "couldn't get idr"))
31439b61e302SSuniel Mahesh 				return id == -ENOSPC ? -EBUSY : id;
31449b61e302SSuniel Mahesh 		}
31459b61e302SSuniel Mahesh 	}
31468caab75fSGeert Uytterhoeven 	if (ctlr->bus_num < 0) {
314742bdd706SLucas Stach 		first_dynamic = of_alias_get_highest_id("spi");
314842bdd706SLucas Stach 		if (first_dynamic < 0)
314942bdd706SLucas Stach 			first_dynamic = 0;
315042bdd706SLucas Stach 		else
315142bdd706SLucas Stach 			first_dynamic++;
315242bdd706SLucas Stach 
31539b61e302SSuniel Mahesh 		mutex_lock(&board_lock);
315442bdd706SLucas Stach 		id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
315542bdd706SLucas Stach 			       0, GFP_KERNEL);
31569b61e302SSuniel Mahesh 		mutex_unlock(&board_lock);
31579b61e302SSuniel Mahesh 		if (WARN(id < 0, "couldn't get idr"))
31589b61e302SSuniel Mahesh 			return id;
31599b61e302SSuniel Mahesh 		ctlr->bus_num = id;
31608ae12a0dSDavid Brownell 	}
31618caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
31628caab75fSGeert Uytterhoeven 	init_completion(&ctlr->xfer_completion);
316369fa9590SDavid Jander 	init_completion(&ctlr->cur_msg_completion);
31648caab75fSGeert Uytterhoeven 	if (!ctlr->max_dma_len)
31658caab75fSGeert Uytterhoeven 		ctlr->max_dma_len = INT_MAX;
3166cf32b71eSErnst Schwab 
3167350de7ceSAndy Shevchenko 	/*
3168350de7ceSAndy Shevchenko 	 * Register the device, then userspace will see it.
3169350de7ceSAndy Shevchenko 	 * Registration fails if the bus ID is in use.
31708ae12a0dSDavid Brownell 	 */
31718caab75fSGeert Uytterhoeven 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
31720a919ae4SAndrey Smirnov 
3173f48dc6b9SLinus Walleij 	if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
31740a919ae4SAndrey Smirnov 		status = spi_get_gpio_descs(ctlr);
31750a919ae4SAndrey Smirnov 		if (status)
3176f9981d4fSAaro Koskinen 			goto free_bus_id;
31770a919ae4SAndrey Smirnov 		/*
31780a919ae4SAndrey Smirnov 		 * A controller using GPIO descriptors always
31790a919ae4SAndrey Smirnov 		 * supports SPI_CS_HIGH if need be.
31800a919ae4SAndrey Smirnov 		 */
31810a919ae4SAndrey Smirnov 		ctlr->mode_bits |= SPI_CS_HIGH;
31820a919ae4SAndrey Smirnov 	}
31830a919ae4SAndrey Smirnov 
3184f9481b08STudor Ambarus 	/*
3185f9481b08STudor Ambarus 	 * Even if it's just one always-selected device, there must
3186f9481b08STudor Ambarus 	 * be at least one chipselect.
3187f9481b08STudor Ambarus 	 */
3188f9981d4fSAaro Koskinen 	if (!ctlr->num_chipselect) {
3189f9981d4fSAaro Koskinen 		status = -EINVAL;
3190f9981d4fSAaro Koskinen 		goto free_bus_id;
3191f9981d4fSAaro Koskinen 	}
3192f9481b08STudor Ambarus 
319395c8222fSDavid Jander 	/* Setting last_cs to -1 means no chip selected */
31946bb477dfSYun Zhou 	ctlr->last_cs = -1;
31956bb477dfSYun Zhou 
31968caab75fSGeert Uytterhoeven 	status = device_add(&ctlr->dev);
3197f9981d4fSAaro Koskinen 	if (status < 0)
3198f9981d4fSAaro Koskinen 		goto free_bus_id;
31999b61e302SSuniel Mahesh 	dev_dbg(dev, "registered %s %s\n",
32008caab75fSGeert Uytterhoeven 			spi_controller_is_slave(ctlr) ? "slave" : "master",
32019b61e302SSuniel Mahesh 			dev_name(&ctlr->dev));
32028ae12a0dSDavid Brownell 
3203b5932f5cSBoris Brezillon 	/*
3204b5932f5cSBoris Brezillon 	 * If we're using a queued driver, start the queue. Note that we don't
3205b5932f5cSBoris Brezillon 	 * need the queueing logic if the driver is only supporting high-level
3206b5932f5cSBoris Brezillon 	 * memory operations.
3207b5932f5cSBoris Brezillon 	 */
3208b5932f5cSBoris Brezillon 	if (ctlr->transfer) {
32098caab75fSGeert Uytterhoeven 		dev_info(dev, "controller is unqueued, this is deprecated\n");
3210b5932f5cSBoris Brezillon 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
32118caab75fSGeert Uytterhoeven 		status = spi_controller_initialize_queue(ctlr);
3212ffbbdd21SLinus Walleij 		if (status) {
32138caab75fSGeert Uytterhoeven 			device_del(&ctlr->dev);
3214f9981d4fSAaro Koskinen 			goto free_bus_id;
3215ffbbdd21SLinus Walleij 		}
3216ffbbdd21SLinus Walleij 	}
321795c8222fSDavid Jander 	/* Add statistics */
32186598b91bSDavid Jander 	ctlr->pcpu_statistics = spi_alloc_pcpu_stats(dev);
32196598b91bSDavid Jander 	if (!ctlr->pcpu_statistics) {
32206598b91bSDavid Jander 		dev_err(dev, "Error allocating per-cpu statistics\n");
3221d52b095bSDan Carpenter 		status = -ENOMEM;
32226598b91bSDavid Jander 		goto destroy_queue;
32236598b91bSDavid Jander 	}
3224ffbbdd21SLinus Walleij 
32252b9603a0SFeng Tang 	mutex_lock(&board_lock);
32268caab75fSGeert Uytterhoeven 	list_add_tail(&ctlr->list, &spi_controller_list);
32272b9603a0SFeng Tang 	list_for_each_entry(bi, &board_list, list)
32288caab75fSGeert Uytterhoeven 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
32292b9603a0SFeng Tang 	mutex_unlock(&board_lock);
32302b9603a0SFeng Tang 
323164bee4d2SMika Westerberg 	/* Register devices from the device tree and ACPI */
32328caab75fSGeert Uytterhoeven 	of_register_spi_devices(ctlr);
32338caab75fSGeert Uytterhoeven 	acpi_register_spi_devices(ctlr);
3234f9981d4fSAaro Koskinen 	return status;
3235f9981d4fSAaro Koskinen 
32366598b91bSDavid Jander destroy_queue:
32376598b91bSDavid Jander 	spi_destroy_queue(ctlr);
3238f9981d4fSAaro Koskinen free_bus_id:
3239f9981d4fSAaro Koskinen 	mutex_lock(&board_lock);
3240f9981d4fSAaro Koskinen 	idr_remove(&spi_master_idr, ctlr->bus_num);
3241f9981d4fSAaro Koskinen 	mutex_unlock(&board_lock);
32428ae12a0dSDavid Brownell 	return status;
32438ae12a0dSDavid Brownell }
32448caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_register_controller);
32458ae12a0dSDavid Brownell 
324643cc5a0aSYang Yingliang static void devm_spi_unregister(struct device *dev, void *res)
3247666d5b4cSMark Brown {
324843cc5a0aSYang Yingliang 	spi_unregister_controller(*(struct spi_controller **)res);
3249666d5b4cSMark Brown }
3250666d5b4cSMark Brown 
3251666d5b4cSMark Brown /**
32528caab75fSGeert Uytterhoeven  * devm_spi_register_controller - register managed SPI master or slave
32538caab75fSGeert Uytterhoeven  *	controller
32548caab75fSGeert Uytterhoeven  * @dev:    device managing SPI controller
32558caab75fSGeert Uytterhoeven  * @ctlr: initialized controller, originally from spi_alloc_master() or
32568caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
3257666d5b4cSMark Brown  * Context: can sleep
3258666d5b4cSMark Brown  *
32598caab75fSGeert Uytterhoeven  * Register a SPI device as with spi_register_controller() which will
326068b892f1SJohan Hovold  * automatically be unregistered and freed.
326197d56dc6SJavier Martinez Canillas  *
326297d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3263666d5b4cSMark Brown  */
32648caab75fSGeert Uytterhoeven int devm_spi_register_controller(struct device *dev,
32658caab75fSGeert Uytterhoeven 				 struct spi_controller *ctlr)
3266666d5b4cSMark Brown {
326743cc5a0aSYang Yingliang 	struct spi_controller **ptr;
3268666d5b4cSMark Brown 	int ret;
3269666d5b4cSMark Brown 
327043cc5a0aSYang Yingliang 	ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
327143cc5a0aSYang Yingliang 	if (!ptr)
327243cc5a0aSYang Yingliang 		return -ENOMEM;
327359ebbe40STian Tao 
327443cc5a0aSYang Yingliang 	ret = spi_register_controller(ctlr);
327543cc5a0aSYang Yingliang 	if (!ret) {
327643cc5a0aSYang Yingliang 		*ptr = ctlr;
327743cc5a0aSYang Yingliang 		devres_add(dev, ptr);
327843cc5a0aSYang Yingliang 	} else {
327943cc5a0aSYang Yingliang 		devres_free(ptr);
328043cc5a0aSYang Yingliang 	}
328143cc5a0aSYang Yingliang 
328243cc5a0aSYang Yingliang 	return ret;
3283666d5b4cSMark Brown }
32848caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3285666d5b4cSMark Brown 
328634860089SDavid Lamparter static int __unregister(struct device *dev, void *null)
32878ae12a0dSDavid Brownell {
32880c868461SDavid Brownell 	spi_unregister_device(to_spi_device(dev));
32898ae12a0dSDavid Brownell 	return 0;
32908ae12a0dSDavid Brownell }
32918ae12a0dSDavid Brownell 
32928ae12a0dSDavid Brownell /**
32938caab75fSGeert Uytterhoeven  * spi_unregister_controller - unregister SPI master or slave controller
32948caab75fSGeert Uytterhoeven  * @ctlr: the controller being unregistered
329533e34dc6SDavid Brownell  * Context: can sleep
32968ae12a0dSDavid Brownell  *
32978caab75fSGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
32988ae12a0dSDavid Brownell  * only ones directly touching chip registers.
32998ae12a0dSDavid Brownell  *
33008ae12a0dSDavid Brownell  * This must be called from context that can sleep.
330168b892f1SJohan Hovold  *
330268b892f1SJohan Hovold  * Note that this function also drops a reference to the controller.
33038ae12a0dSDavid Brownell  */
33048caab75fSGeert Uytterhoeven void spi_unregister_controller(struct spi_controller *ctlr)
33058ae12a0dSDavid Brownell {
33069b61e302SSuniel Mahesh 	struct spi_controller *found;
330767f7b278SJohan Hovold 	int id = ctlr->bus_num;
330889fc9a1aSJeff Garzik 
3309ddf75be4SLukas Wunner 	/* Prevent addition of new devices, unregister existing ones */
3310ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
33116098475dSMark Brown 		mutex_lock(&ctlr->add_lock);
3312ddf75be4SLukas Wunner 
331384855678SLukas Wunner 	device_for_each_child(&ctlr->dev, NULL, __unregister);
331484855678SLukas Wunner 
33159b61e302SSuniel Mahesh 	/* First make sure that this controller was ever added */
33169b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
331767f7b278SJohan Hovold 	found = idr_find(&spi_master_idr, id);
33189b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
33198caab75fSGeert Uytterhoeven 	if (ctlr->queued) {
33208caab75fSGeert Uytterhoeven 		if (spi_destroy_queue(ctlr))
33218caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue remove failed\n");
3322ffbbdd21SLinus Walleij 	}
33232b9603a0SFeng Tang 	mutex_lock(&board_lock);
33248caab75fSGeert Uytterhoeven 	list_del(&ctlr->list);
33252b9603a0SFeng Tang 	mutex_unlock(&board_lock);
33262b9603a0SFeng Tang 
33275e844cc3SLukas Wunner 	device_del(&ctlr->dev);
33285e844cc3SLukas Wunner 
332995c8222fSDavid Jander 	/* Free bus id */
33309b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
3331613bd1eaSJarkko Nikula 	if (found == ctlr)
333267f7b278SJohan Hovold 		idr_remove(&spi_master_idr, id);
33339b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
3334ddf75be4SLukas Wunner 
3335ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
33366098475dSMark Brown 		mutex_unlock(&ctlr->add_lock);
33376c53b45cSMichael Walle 
33386c53b45cSMichael Walle 	/* Release the last reference on the controller if its driver
33396c53b45cSMichael Walle 	 * has not yet been converted to devm_spi_alloc_master/slave().
33406c53b45cSMichael Walle 	 */
33416c53b45cSMichael Walle 	if (!ctlr->devm_allocated)
33426c53b45cSMichael Walle 		put_device(&ctlr->dev);
33438ae12a0dSDavid Brownell }
33448caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_controller);
33458ae12a0dSDavid Brownell 
33468caab75fSGeert Uytterhoeven int spi_controller_suspend(struct spi_controller *ctlr)
3347ffbbdd21SLinus Walleij {
3348ffbbdd21SLinus Walleij 	int ret;
3349ffbbdd21SLinus Walleij 
33508caab75fSGeert Uytterhoeven 	/* Basically no-ops for non-queued controllers */
33518caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
3352ffbbdd21SLinus Walleij 		return 0;
3353ffbbdd21SLinus Walleij 
33548caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
3355ffbbdd21SLinus Walleij 	if (ret)
33568caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue stop failed\n");
3357ffbbdd21SLinus Walleij 
3358ffbbdd21SLinus Walleij 	return ret;
3359ffbbdd21SLinus Walleij }
33608caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_suspend);
3361ffbbdd21SLinus Walleij 
33628caab75fSGeert Uytterhoeven int spi_controller_resume(struct spi_controller *ctlr)
3363ffbbdd21SLinus Walleij {
3364ffbbdd21SLinus Walleij 	int ret;
3365ffbbdd21SLinus Walleij 
33668caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
3367ffbbdd21SLinus Walleij 		return 0;
3368ffbbdd21SLinus Walleij 
33698caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
3370ffbbdd21SLinus Walleij 	if (ret)
33718caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue restart failed\n");
3372ffbbdd21SLinus Walleij 
3373ffbbdd21SLinus Walleij 	return ret;
3374ffbbdd21SLinus Walleij }
33758caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_resume);
3376ffbbdd21SLinus Walleij 
33778ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
33788ae12a0dSDavid Brownell 
3379523baf5aSMartin Sperl /* Core methods for spi_message alterations */
3380523baf5aSMartin Sperl 
33818caab75fSGeert Uytterhoeven static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3382523baf5aSMartin Sperl 					    struct spi_message *msg,
3383523baf5aSMartin Sperl 					    void *res)
3384523baf5aSMartin Sperl {
3385523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer = res;
3386523baf5aSMartin Sperl 	size_t i;
3387523baf5aSMartin Sperl 
338895c8222fSDavid Jander 	/* Call extra callback if requested */
3389523baf5aSMartin Sperl 	if (rxfer->release)
33908caab75fSGeert Uytterhoeven 		rxfer->release(ctlr, msg, res);
3391523baf5aSMartin Sperl 
339295c8222fSDavid Jander 	/* Insert replaced transfers back into the message */
3393523baf5aSMartin Sperl 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3394523baf5aSMartin Sperl 
339595c8222fSDavid Jander 	/* Remove the formerly inserted entries */
3396523baf5aSMartin Sperl 	for (i = 0; i < rxfer->inserted; i++)
3397523baf5aSMartin Sperl 		list_del(&rxfer->inserted_transfers[i].transfer_list);
3398523baf5aSMartin Sperl }
3399523baf5aSMartin Sperl 
3400523baf5aSMartin Sperl /**
3401523baf5aSMartin Sperl  * spi_replace_transfers - replace transfers with several transfers
3402523baf5aSMartin Sperl  *                         and register change with spi_message.resources
3403523baf5aSMartin Sperl  * @msg:           the spi_message we work upon
3404523baf5aSMartin Sperl  * @xfer_first:    the first spi_transfer we want to replace
3405523baf5aSMartin Sperl  * @remove:        number of transfers to remove
3406523baf5aSMartin Sperl  * @insert:        the number of transfers we want to insert instead
3407523baf5aSMartin Sperl  * @release:       extra release code necessary in some circumstances
3408523baf5aSMartin Sperl  * @extradatasize: extra data to allocate (with alignment guarantees
3409523baf5aSMartin Sperl  *                 of struct @spi_transfer)
341005885397SMartin Sperl  * @gfp:           gfp flags
3411523baf5aSMartin Sperl  *
3412523baf5aSMartin Sperl  * Returns: pointer to @spi_replaced_transfers,
3413523baf5aSMartin Sperl  *          PTR_ERR(...) in case of errors.
3414523baf5aSMartin Sperl  */
3415da21fde0SUwe Kleine-König static struct spi_replaced_transfers *spi_replace_transfers(
3416523baf5aSMartin Sperl 	struct spi_message *msg,
3417523baf5aSMartin Sperl 	struct spi_transfer *xfer_first,
3418523baf5aSMartin Sperl 	size_t remove,
3419523baf5aSMartin Sperl 	size_t insert,
3420523baf5aSMartin Sperl 	spi_replaced_release_t release,
3421523baf5aSMartin Sperl 	size_t extradatasize,
3422523baf5aSMartin Sperl 	gfp_t gfp)
3423523baf5aSMartin Sperl {
3424523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer;
3425523baf5aSMartin Sperl 	struct spi_transfer *xfer;
3426523baf5aSMartin Sperl 	size_t i;
3427523baf5aSMartin Sperl 
342895c8222fSDavid Jander 	/* Allocate the structure using spi_res */
3429523baf5aSMartin Sperl 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3430aef97522SGustavo A. R. Silva 			      struct_size(rxfer, inserted_transfers, insert)
3431523baf5aSMartin Sperl 			      + extradatasize,
3432523baf5aSMartin Sperl 			      gfp);
3433523baf5aSMartin Sperl 	if (!rxfer)
3434523baf5aSMartin Sperl 		return ERR_PTR(-ENOMEM);
3435523baf5aSMartin Sperl 
343695c8222fSDavid Jander 	/* The release code to invoke before running the generic release */
3437523baf5aSMartin Sperl 	rxfer->release = release;
3438523baf5aSMartin Sperl 
343995c8222fSDavid Jander 	/* Assign extradata */
3440523baf5aSMartin Sperl 	if (extradatasize)
3441523baf5aSMartin Sperl 		rxfer->extradata =
3442523baf5aSMartin Sperl 			&rxfer->inserted_transfers[insert];
3443523baf5aSMartin Sperl 
344495c8222fSDavid Jander 	/* Init the replaced_transfers list */
3445523baf5aSMartin Sperl 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3446523baf5aSMartin Sperl 
3447350de7ceSAndy Shevchenko 	/*
3448350de7ceSAndy Shevchenko 	 * Assign the list_entry after which we should reinsert
3449523baf5aSMartin Sperl 	 * the @replaced_transfers - it may be spi_message.messages!
3450523baf5aSMartin Sperl 	 */
3451523baf5aSMartin Sperl 	rxfer->replaced_after = xfer_first->transfer_list.prev;
3452523baf5aSMartin Sperl 
345395c8222fSDavid Jander 	/* Remove the requested number of transfers */
3454523baf5aSMartin Sperl 	for (i = 0; i < remove; i++) {
3455350de7ceSAndy Shevchenko 		/*
3456350de7ceSAndy Shevchenko 		 * If the entry after replaced_after it is msg->transfers
3457523baf5aSMartin Sperl 		 * then we have been requested to remove more transfers
3458350de7ceSAndy Shevchenko 		 * than are in the list.
3459523baf5aSMartin Sperl 		 */
3460523baf5aSMartin Sperl 		if (rxfer->replaced_after->next == &msg->transfers) {
3461523baf5aSMartin Sperl 			dev_err(&msg->spi->dev,
3462523baf5aSMartin Sperl 				"requested to remove more spi_transfers than are available\n");
346395c8222fSDavid Jander 			/* Insert replaced transfers back into the message */
3464523baf5aSMartin Sperl 			list_splice(&rxfer->replaced_transfers,
3465523baf5aSMartin Sperl 				    rxfer->replaced_after);
3466523baf5aSMartin Sperl 
346795c8222fSDavid Jander 			/* Free the spi_replace_transfer structure... */
3468523baf5aSMartin Sperl 			spi_res_free(rxfer);
3469523baf5aSMartin Sperl 
347095c8222fSDavid Jander 			/* ...and return with an error */
3471523baf5aSMartin Sperl 			return ERR_PTR(-EINVAL);
3472523baf5aSMartin Sperl 		}
3473523baf5aSMartin Sperl 
3474350de7ceSAndy Shevchenko 		/*
3475350de7ceSAndy Shevchenko 		 * Remove the entry after replaced_after from list of
3476350de7ceSAndy Shevchenko 		 * transfers and add it to list of replaced_transfers.
3477523baf5aSMartin Sperl 		 */
3478523baf5aSMartin Sperl 		list_move_tail(rxfer->replaced_after->next,
3479523baf5aSMartin Sperl 			       &rxfer->replaced_transfers);
3480523baf5aSMartin Sperl 	}
3481523baf5aSMartin Sperl 
3482350de7ceSAndy Shevchenko 	/*
3483350de7ceSAndy Shevchenko 	 * Create copy of the given xfer with identical settings
3484350de7ceSAndy Shevchenko 	 * based on the first transfer to get removed.
3485523baf5aSMartin Sperl 	 */
3486523baf5aSMartin Sperl 	for (i = 0; i < insert; i++) {
348795c8222fSDavid Jander 		/* We need to run in reverse order */
3488523baf5aSMartin Sperl 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3489523baf5aSMartin Sperl 
349095c8222fSDavid Jander 		/* Copy all spi_transfer data */
3491523baf5aSMartin Sperl 		memcpy(xfer, xfer_first, sizeof(*xfer));
3492523baf5aSMartin Sperl 
349395c8222fSDavid Jander 		/* Add to list */
3494523baf5aSMartin Sperl 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3495523baf5aSMartin Sperl 
349695c8222fSDavid Jander 		/* Clear cs_change and delay for all but the last */
3497523baf5aSMartin Sperl 		if (i) {
3498523baf5aSMartin Sperl 			xfer->cs_change = false;
3499bebcfd27SAlexandru Ardelean 			xfer->delay.value = 0;
3500523baf5aSMartin Sperl 		}
3501523baf5aSMartin Sperl 	}
3502523baf5aSMartin Sperl 
350395c8222fSDavid Jander 	/* Set up inserted... */
3504523baf5aSMartin Sperl 	rxfer->inserted = insert;
3505523baf5aSMartin Sperl 
350695c8222fSDavid Jander 	/* ...and register it with spi_res/spi_message */
3507523baf5aSMartin Sperl 	spi_res_add(msg, rxfer);
3508523baf5aSMartin Sperl 
3509523baf5aSMartin Sperl 	return rxfer;
3510523baf5aSMartin Sperl }
3511523baf5aSMartin Sperl 
35128caab75fSGeert Uytterhoeven static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3513d9f12122SMartin Sperl 					struct spi_message *msg,
3514d9f12122SMartin Sperl 					struct spi_transfer **xferp,
3515d9f12122SMartin Sperl 					size_t maxsize,
3516d9f12122SMartin Sperl 					gfp_t gfp)
3517d9f12122SMartin Sperl {
3518d9f12122SMartin Sperl 	struct spi_transfer *xfer = *xferp, *xfers;
3519d9f12122SMartin Sperl 	struct spi_replaced_transfers *srt;
3520d9f12122SMartin Sperl 	size_t offset;
3521d9f12122SMartin Sperl 	size_t count, i;
3522d9f12122SMartin Sperl 
352395c8222fSDavid Jander 	/* Calculate how many we have to replace */
3524d9f12122SMartin Sperl 	count = DIV_ROUND_UP(xfer->len, maxsize);
3525d9f12122SMartin Sperl 
352695c8222fSDavid Jander 	/* Create replacement */
3527d9f12122SMartin Sperl 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3528657d32efSDan Carpenter 	if (IS_ERR(srt))
3529657d32efSDan Carpenter 		return PTR_ERR(srt);
3530d9f12122SMartin Sperl 	xfers = srt->inserted_transfers;
3531d9f12122SMartin Sperl 
3532350de7ceSAndy Shevchenko 	/*
3533350de7ceSAndy Shevchenko 	 * Now handle each of those newly inserted spi_transfers.
3534350de7ceSAndy Shevchenko 	 * Note that the replacements spi_transfers all are preset
3535d9f12122SMartin Sperl 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3536d9f12122SMartin Sperl 	 * are all identical (as well as most others)
3537d9f12122SMartin Sperl 	 * so we just have to fix up len and the pointers.
3538d9f12122SMartin Sperl 	 *
3539350de7ceSAndy Shevchenko 	 * This also includes support for the depreciated
3540350de7ceSAndy Shevchenko 	 * spi_message.is_dma_mapped interface.
3541d9f12122SMartin Sperl 	 */
3542d9f12122SMartin Sperl 
3543350de7ceSAndy Shevchenko 	/*
3544350de7ceSAndy Shevchenko 	 * The first transfer just needs the length modified, so we
3545350de7ceSAndy Shevchenko 	 * run it outside the loop.
3546d9f12122SMartin Sperl 	 */
3547c8dab77aSFabio Estevam 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3548d9f12122SMartin Sperl 
354995c8222fSDavid Jander 	/* All the others need rx_buf/tx_buf also set */
3550d9f12122SMartin Sperl 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
355195c8222fSDavid Jander 		/* Update rx_buf, tx_buf and dma */
3552d9f12122SMartin Sperl 		if (xfers[i].rx_buf)
3553d9f12122SMartin Sperl 			xfers[i].rx_buf += offset;
3554d9f12122SMartin Sperl 		if (xfers[i].rx_dma)
3555d9f12122SMartin Sperl 			xfers[i].rx_dma += offset;
3556d9f12122SMartin Sperl 		if (xfers[i].tx_buf)
3557d9f12122SMartin Sperl 			xfers[i].tx_buf += offset;
3558d9f12122SMartin Sperl 		if (xfers[i].tx_dma)
3559d9f12122SMartin Sperl 			xfers[i].tx_dma += offset;
3560d9f12122SMartin Sperl 
356195c8222fSDavid Jander 		/* Update length */
3562d9f12122SMartin Sperl 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3563d9f12122SMartin Sperl 	}
3564d9f12122SMartin Sperl 
3565350de7ceSAndy Shevchenko 	/*
3566350de7ceSAndy Shevchenko 	 * We set up xferp to the last entry we have inserted,
3567350de7ceSAndy Shevchenko 	 * so that we skip those already split transfers.
3568d9f12122SMartin Sperl 	 */
3569d9f12122SMartin Sperl 	*xferp = &xfers[count - 1];
3570d9f12122SMartin Sperl 
357195c8222fSDavid Jander 	/* Increment statistics counters */
35726598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics,
3573d9f12122SMartin Sperl 				       transfers_split_maxsize);
35746598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics,
3575d9f12122SMartin Sperl 				       transfers_split_maxsize);
3576d9f12122SMartin Sperl 
3577d9f12122SMartin Sperl 	return 0;
3578d9f12122SMartin Sperl }
3579d9f12122SMartin Sperl 
3580d9f12122SMartin Sperl /**
3581ce2424d7SMauro Carvalho Chehab  * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3582d9f12122SMartin Sperl  *                               when an individual transfer exceeds a
3583d9f12122SMartin Sperl  *                               certain size
35848caab75fSGeert Uytterhoeven  * @ctlr:    the @spi_controller for this transfer
35853700ce95SMasanari Iida  * @msg:   the @spi_message to transform
35863700ce95SMasanari Iida  * @maxsize:  the maximum when to apply this
358710f11a22SJavier Martinez Canillas  * @gfp: GFP allocation flags
3588d9f12122SMartin Sperl  *
3589d9f12122SMartin Sperl  * Return: status of transformation
3590d9f12122SMartin Sperl  */
35918caab75fSGeert Uytterhoeven int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3592d9f12122SMartin Sperl 				struct spi_message *msg,
3593d9f12122SMartin Sperl 				size_t maxsize,
3594d9f12122SMartin Sperl 				gfp_t gfp)
3595d9f12122SMartin Sperl {
3596d9f12122SMartin Sperl 	struct spi_transfer *xfer;
3597d9f12122SMartin Sperl 	int ret;
3598d9f12122SMartin Sperl 
3599350de7ceSAndy Shevchenko 	/*
3600350de7ceSAndy Shevchenko 	 * Iterate over the transfer_list,
3601d9f12122SMartin Sperl 	 * but note that xfer is advanced to the last transfer inserted
3602d9f12122SMartin Sperl 	 * to avoid checking sizes again unnecessarily (also xfer does
3603350de7ceSAndy Shevchenko 	 * potentially belong to a different list by the time the
3604350de7ceSAndy Shevchenko 	 * replacement has happened).
3605d9f12122SMartin Sperl 	 */
3606d9f12122SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3607d9f12122SMartin Sperl 		if (xfer->len > maxsize) {
36088caab75fSGeert Uytterhoeven 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
36098caab75fSGeert Uytterhoeven 							   maxsize, gfp);
3610d9f12122SMartin Sperl 			if (ret)
3611d9f12122SMartin Sperl 				return ret;
3612d9f12122SMartin Sperl 		}
3613d9f12122SMartin Sperl 	}
3614d9f12122SMartin Sperl 
3615d9f12122SMartin Sperl 	return 0;
3616d9f12122SMartin Sperl }
3617d9f12122SMartin Sperl EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
36188ae12a0dSDavid Brownell 
36198ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
36208ae12a0dSDavid Brownell 
36218caab75fSGeert Uytterhoeven /* Core methods for SPI controller protocol drivers.  Some of the
36227d077197SDavid Brownell  * other core methods are currently defined as inline functions.
36237d077197SDavid Brownell  */
36247d077197SDavid Brownell 
36258caab75fSGeert Uytterhoeven static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
36268caab75fSGeert Uytterhoeven 					u8 bits_per_word)
362763ab645fSStefan Brüns {
36288caab75fSGeert Uytterhoeven 	if (ctlr->bits_per_word_mask) {
362963ab645fSStefan Brüns 		/* Only 32 bits fit in the mask */
363063ab645fSStefan Brüns 		if (bits_per_word > 32)
363163ab645fSStefan Brüns 			return -EINVAL;
36328caab75fSGeert Uytterhoeven 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
363363ab645fSStefan Brüns 			return -EINVAL;
363463ab645fSStefan Brüns 	}
363563ab645fSStefan Brüns 
363663ab645fSStefan Brüns 	return 0;
363763ab645fSStefan Brüns }
363863ab645fSStefan Brüns 
36397d077197SDavid Brownell /**
3640684a4784STudor Ambarus  * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3641684a4784STudor Ambarus  * @spi: the device that requires specific CS timing configuration
3642684a4784STudor Ambarus  *
3643684a4784STudor Ambarus  * Return: zero on success, else a negative error code.
3644684a4784STudor Ambarus  */
3645684a4784STudor Ambarus static int spi_set_cs_timing(struct spi_device *spi)
3646684a4784STudor Ambarus {
3647684a4784STudor Ambarus 	struct device *parent = spi->controller->dev.parent;
3648684a4784STudor Ambarus 	int status = 0;
3649684a4784STudor Ambarus 
3650684a4784STudor Ambarus 	if (spi->controller->set_cs_timing && !spi->cs_gpiod) {
3651684a4784STudor Ambarus 		if (spi->controller->auto_runtime_pm) {
3652684a4784STudor Ambarus 			status = pm_runtime_get_sync(parent);
3653684a4784STudor Ambarus 			if (status < 0) {
3654684a4784STudor Ambarus 				pm_runtime_put_noidle(parent);
3655684a4784STudor Ambarus 				dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3656684a4784STudor Ambarus 					status);
3657684a4784STudor Ambarus 				return status;
3658684a4784STudor Ambarus 			}
3659684a4784STudor Ambarus 
3660684a4784STudor Ambarus 			status = spi->controller->set_cs_timing(spi);
3661684a4784STudor Ambarus 			pm_runtime_mark_last_busy(parent);
3662684a4784STudor Ambarus 			pm_runtime_put_autosuspend(parent);
3663684a4784STudor Ambarus 		} else {
3664684a4784STudor Ambarus 			status = spi->controller->set_cs_timing(spi);
3665684a4784STudor Ambarus 		}
3666684a4784STudor Ambarus 	}
3667684a4784STudor Ambarus 	return status;
3668684a4784STudor Ambarus }
3669684a4784STudor Ambarus 
3670684a4784STudor Ambarus /**
36717d077197SDavid Brownell  * spi_setup - setup SPI mode and clock rate
36727d077197SDavid Brownell  * @spi: the device whose settings are being modified
36737d077197SDavid Brownell  * Context: can sleep, and no requests are queued to the device
36747d077197SDavid Brownell  *
36757d077197SDavid Brownell  * SPI protocol drivers may need to update the transfer mode if the
36767d077197SDavid Brownell  * device doesn't work with its default.  They may likewise need
36777d077197SDavid Brownell  * to update clock rates or word sizes from initial values.  This function
36787d077197SDavid Brownell  * changes those settings, and must be called from a context that can sleep.
36797d077197SDavid Brownell  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
36807d077197SDavid Brownell  * effect the next time the device is selected and data is transferred to
36817d077197SDavid Brownell  * or from it.  When this function returns, the spi device is deselected.
36827d077197SDavid Brownell  *
36837d077197SDavid Brownell  * Note that this call will fail if the protocol driver specifies an option
36847d077197SDavid Brownell  * that the underlying controller or its driver does not support.  For
36857d077197SDavid Brownell  * example, not all hardware supports wire transfers using nine bit words,
36867d077197SDavid Brownell  * LSB-first wire encoding, or active-high chipselects.
368797d56dc6SJavier Martinez Canillas  *
368897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
36897d077197SDavid Brownell  */
36907d077197SDavid Brownell int spi_setup(struct spi_device *spi)
36917d077197SDavid Brownell {
369283596fbeSGeert Uytterhoeven 	unsigned	bad_bits, ugly_bits;
369373f93db5SPaul Kocialkowski 	int		status = 0;
36947d077197SDavid Brownell 
3695d962608cSDragos Bogdan 	/*
3696350de7ceSAndy Shevchenko 	 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3697350de7ceSAndy Shevchenko 	 * are set at the same time.
3698f477b7fbSwangyuhang 	 */
3699d962608cSDragos Bogdan 	if ((hweight_long(spi->mode &
3700d962608cSDragos Bogdan 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3701d962608cSDragos Bogdan 	    (hweight_long(spi->mode &
3702d962608cSDragos Bogdan 		(SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3703f477b7fbSwangyuhang 		dev_err(&spi->dev,
3704d962608cSDragos Bogdan 		"setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3705f477b7fbSwangyuhang 		return -EINVAL;
3706f477b7fbSwangyuhang 	}
3707350de7ceSAndy Shevchenko 	/* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3708f477b7fbSwangyuhang 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
37096b03061fSYogesh Narayan Gaur 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
37106b03061fSYogesh Narayan Gaur 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3711f477b7fbSwangyuhang 		return -EINVAL;
3712350de7ceSAndy Shevchenko 	/*
3713350de7ceSAndy Shevchenko 	 * Help drivers fail *cleanly* when they need options
3714350de7ceSAndy Shevchenko 	 * that aren't supported with their current controller.
3715cbaa62e0SDavid Lechner 	 * SPI_CS_WORD has a fallback software implementation,
3716cbaa62e0SDavid Lechner 	 * so it is ignored here.
3717e7db06b5SDavid Brownell 	 */
3718d962608cSDragos Bogdan 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3719d962608cSDragos Bogdan 				 SPI_NO_TX | SPI_NO_RX);
372083596fbeSGeert Uytterhoeven 	ugly_bits = bad_bits &
37216b03061fSYogesh Narayan Gaur 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
37226b03061fSYogesh Narayan Gaur 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
372383596fbeSGeert Uytterhoeven 	if (ugly_bits) {
372483596fbeSGeert Uytterhoeven 		dev_warn(&spi->dev,
372583596fbeSGeert Uytterhoeven 			 "setup: ignoring unsupported mode bits %x\n",
372683596fbeSGeert Uytterhoeven 			 ugly_bits);
372783596fbeSGeert Uytterhoeven 		spi->mode &= ~ugly_bits;
372883596fbeSGeert Uytterhoeven 		bad_bits &= ~ugly_bits;
372983596fbeSGeert Uytterhoeven 	}
3730e7db06b5SDavid Brownell 	if (bad_bits) {
3731eb288a1fSLinus Walleij 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3732e7db06b5SDavid Brownell 			bad_bits);
3733e7db06b5SDavid Brownell 		return -EINVAL;
3734e7db06b5SDavid Brownell 	}
3735e7db06b5SDavid Brownell 
3736b3fe2e51SPaul Kocialkowski 	if (!spi->bits_per_word) {
37377d077197SDavid Brownell 		spi->bits_per_word = 8;
3738b3fe2e51SPaul Kocialkowski 	} else {
3739b3fe2e51SPaul Kocialkowski 		/*
3740b3fe2e51SPaul Kocialkowski 		 * Some controllers may not support the default 8 bits-per-word
3741b3fe2e51SPaul Kocialkowski 		 * so only perform the check when this is explicitly provided.
3742b3fe2e51SPaul Kocialkowski 		 */
37438caab75fSGeert Uytterhoeven 		status = __spi_validate_bits_per_word(spi->controller,
37448caab75fSGeert Uytterhoeven 						      spi->bits_per_word);
37455ab8d262SAndy Shevchenko 		if (status)
37465ab8d262SAndy Shevchenko 			return status;
3747b3fe2e51SPaul Kocialkowski 	}
374863ab645fSStefan Brüns 
37496820e812STudor Ambarus 	if (spi->controller->max_speed_hz &&
37506820e812STudor Ambarus 	    (!spi->max_speed_hz ||
37516820e812STudor Ambarus 	     spi->max_speed_hz > spi->controller->max_speed_hz))
37528caab75fSGeert Uytterhoeven 		spi->max_speed_hz = spi->controller->max_speed_hz;
3753052eb2d4SAxel Lin 
37544fae3a58SSerge Semin 	mutex_lock(&spi->controller->io_mutex);
37554fae3a58SSerge Semin 
3756c914dbf8SJoe Burmeister 	if (spi->controller->setup) {
37578caab75fSGeert Uytterhoeven 		status = spi->controller->setup(spi);
3758c914dbf8SJoe Burmeister 		if (status) {
3759c914dbf8SJoe Burmeister 			mutex_unlock(&spi->controller->io_mutex);
3760c914dbf8SJoe Burmeister 			dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3761c914dbf8SJoe Burmeister 				status);
3762c914dbf8SJoe Burmeister 			return status;
3763c914dbf8SJoe Burmeister 		}
3764c914dbf8SJoe Burmeister 	}
37657d077197SDavid Brownell 
3766684a4784STudor Ambarus 	status = spi_set_cs_timing(spi);
3767684a4784STudor Ambarus 	if (status) {
3768684a4784STudor Ambarus 		mutex_unlock(&spi->controller->io_mutex);
3769684a4784STudor Ambarus 		return status;
3770684a4784STudor Ambarus 	}
3771684a4784STudor Ambarus 
3772d948e6caSLuhua Xu 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3773dd769f15SMinghao Chi 		status = pm_runtime_resume_and_get(spi->controller->dev.parent);
3774d948e6caSLuhua Xu 		if (status < 0) {
37754fae3a58SSerge Semin 			mutex_unlock(&spi->controller->io_mutex);
3776d948e6caSLuhua Xu 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3777d948e6caSLuhua Xu 				status);
3778d948e6caSLuhua Xu 			return status;
3779d948e6caSLuhua Xu 		}
378057a94607STony Lindgren 
378157a94607STony Lindgren 		/*
378257a94607STony Lindgren 		 * We do not want to return positive value from pm_runtime_get,
378357a94607STony Lindgren 		 * there are many instances of devices calling spi_setup() and
378457a94607STony Lindgren 		 * checking for a non-zero return value instead of a negative
378557a94607STony Lindgren 		 * return value.
378657a94607STony Lindgren 		 */
378757a94607STony Lindgren 		status = 0;
378857a94607STony Lindgren 
3789d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
3790d948e6caSLuhua Xu 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3791d948e6caSLuhua Xu 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3792d948e6caSLuhua Xu 	} else {
3793d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
3794d948e6caSLuhua Xu 	}
3795abeedb01SFranklin S Cooper Jr 
37964fae3a58SSerge Semin 	mutex_unlock(&spi->controller->io_mutex);
37974fae3a58SSerge Semin 
3798924b5867SDouglas Anderson 	if (spi->rt && !spi->controller->rt) {
3799924b5867SDouglas Anderson 		spi->controller->rt = true;
3800924b5867SDouglas Anderson 		spi_set_thread_rt(spi->controller);
3801924b5867SDouglas Anderson 	}
3802924b5867SDouglas Anderson 
38035cb4e1f3SAndy Shevchenko 	trace_spi_setup(spi, status);
38045cb4e1f3SAndy Shevchenko 
380540b82c2dSAndy Shevchenko 	dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
380640b82c2dSAndy Shevchenko 			spi->mode & SPI_MODE_X_MASK,
38077d077197SDavid Brownell 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
38087d077197SDavid Brownell 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
38097d077197SDavid Brownell 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
38107d077197SDavid Brownell 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
38117d077197SDavid Brownell 			spi->bits_per_word, spi->max_speed_hz,
38127d077197SDavid Brownell 			status);
38137d077197SDavid Brownell 
38147d077197SDavid Brownell 	return status;
38157d077197SDavid Brownell }
38167d077197SDavid Brownell EXPORT_SYMBOL_GPL(spi_setup);
38177d077197SDavid Brownell 
38186c613f68SAlexandru Ardelean static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
38196c613f68SAlexandru Ardelean 				       struct spi_device *spi)
38206c613f68SAlexandru Ardelean {
38216c613f68SAlexandru Ardelean 	int delay1, delay2;
38226c613f68SAlexandru Ardelean 
38233984d39bSAlexandru Ardelean 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
38246c613f68SAlexandru Ardelean 	if (delay1 < 0)
38256c613f68SAlexandru Ardelean 		return delay1;
38266c613f68SAlexandru Ardelean 
38273984d39bSAlexandru Ardelean 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
38286c613f68SAlexandru Ardelean 	if (delay2 < 0)
38296c613f68SAlexandru Ardelean 		return delay2;
38306c613f68SAlexandru Ardelean 
38316c613f68SAlexandru Ardelean 	if (delay1 < delay2)
38326c613f68SAlexandru Ardelean 		memcpy(&xfer->word_delay, &spi->word_delay,
38336c613f68SAlexandru Ardelean 		       sizeof(xfer->word_delay));
38346c613f68SAlexandru Ardelean 
38356c613f68SAlexandru Ardelean 	return 0;
38366c613f68SAlexandru Ardelean }
38376c613f68SAlexandru Ardelean 
383890808738SMark Brown static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3839cf32b71eSErnst Schwab {
38408caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3841e6811d1dSLaxman Dewangan 	struct spi_transfer *xfer;
38426ea31293SAtsushi Nemoto 	int w_size;
3843cf32b71eSErnst Schwab 
384424a0013aSMark Brown 	if (list_empty(&message->transfers))
384524a0013aSMark Brown 		return -EINVAL;
384624a0013aSMark Brown 
3847350de7ceSAndy Shevchenko 	/*
3848350de7ceSAndy Shevchenko 	 * If an SPI controller does not support toggling the CS line on each
384971388b21SDavid Lechner 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
385071388b21SDavid Lechner 	 * for the CS line, we can emulate the CS-per-word hardware function by
3851cbaa62e0SDavid Lechner 	 * splitting transfers into one-word transfers and ensuring that
3852cbaa62e0SDavid Lechner 	 * cs_change is set for each transfer.
3853cbaa62e0SDavid Lechner 	 */
385471388b21SDavid Lechner 	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3855f48dc6b9SLinus Walleij 					  spi->cs_gpiod)) {
3856cbaa62e0SDavid Lechner 		size_t maxsize;
3857cbaa62e0SDavid Lechner 		int ret;
3858cbaa62e0SDavid Lechner 
3859cbaa62e0SDavid Lechner 		maxsize = (spi->bits_per_word + 7) / 8;
3860cbaa62e0SDavid Lechner 
3861cbaa62e0SDavid Lechner 		/* spi_split_transfers_maxsize() requires message->spi */
3862cbaa62e0SDavid Lechner 		message->spi = spi;
3863cbaa62e0SDavid Lechner 
3864cbaa62e0SDavid Lechner 		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3865cbaa62e0SDavid Lechner 						  GFP_KERNEL);
3866cbaa62e0SDavid Lechner 		if (ret)
3867cbaa62e0SDavid Lechner 			return ret;
3868cbaa62e0SDavid Lechner 
3869cbaa62e0SDavid Lechner 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
387095c8222fSDavid Jander 			/* Don't change cs_change on the last entry in the list */
3871cbaa62e0SDavid Lechner 			if (list_is_last(&xfer->transfer_list, &message->transfers))
3872cbaa62e0SDavid Lechner 				break;
3873cbaa62e0SDavid Lechner 			xfer->cs_change = 1;
3874cbaa62e0SDavid Lechner 		}
3875cbaa62e0SDavid Lechner 	}
3876cbaa62e0SDavid Lechner 
3877350de7ceSAndy Shevchenko 	/*
3878350de7ceSAndy Shevchenko 	 * Half-duplex links include original MicroWire, and ones with
3879cf32b71eSErnst Schwab 	 * only one data pin like SPI_3WIRE (switches direction) or where
3880cf32b71eSErnst Schwab 	 * either MOSI or MISO is missing.  They can also be caused by
3881cf32b71eSErnst Schwab 	 * software limitations.
3882cf32b71eSErnst Schwab 	 */
38838caab75fSGeert Uytterhoeven 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
38848caab75fSGeert Uytterhoeven 	    (spi->mode & SPI_3WIRE)) {
38858caab75fSGeert Uytterhoeven 		unsigned flags = ctlr->flags;
3886cf32b71eSErnst Schwab 
3887cf32b71eSErnst Schwab 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3888cf32b71eSErnst Schwab 			if (xfer->rx_buf && xfer->tx_buf)
3889cf32b71eSErnst Schwab 				return -EINVAL;
38908caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3891cf32b71eSErnst Schwab 				return -EINVAL;
38928caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3893cf32b71eSErnst Schwab 				return -EINVAL;
3894cf32b71eSErnst Schwab 		}
3895cf32b71eSErnst Schwab 	}
3896cf32b71eSErnst Schwab 
3897350de7ceSAndy Shevchenko 	/*
3898059b8ffeSLaxman Dewangan 	 * Set transfer bits_per_word and max speed as spi device default if
3899059b8ffeSLaxman Dewangan 	 * it is not set for this transfer.
3900f477b7fbSwangyuhang 	 * Set transfer tx_nbits and rx_nbits as single transfer default
3901f477b7fbSwangyuhang 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3902b7bb367aSJonas Bonn 	 * Ensure transfer word_delay is at least as long as that required by
3903b7bb367aSJonas Bonn 	 * device itself.
3904e6811d1dSLaxman Dewangan 	 */
390577e80588SMartin Sperl 	message->frame_length = 0;
3906e6811d1dSLaxman Dewangan 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
39075d7e2b5eSMartin Sperl 		xfer->effective_speed_hz = 0;
3908078726ceSSourav Poddar 		message->frame_length += xfer->len;
3909e6811d1dSLaxman Dewangan 		if (!xfer->bits_per_word)
3910e6811d1dSLaxman Dewangan 			xfer->bits_per_word = spi->bits_per_word;
3911a6f87fadSAxel Lin 
3912a6f87fadSAxel Lin 		if (!xfer->speed_hz)
3913059b8ffeSLaxman Dewangan 			xfer->speed_hz = spi->max_speed_hz;
3914a6f87fadSAxel Lin 
39158caab75fSGeert Uytterhoeven 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
39168caab75fSGeert Uytterhoeven 			xfer->speed_hz = ctlr->max_speed_hz;
391756ede94aSGabor Juhos 
39188caab75fSGeert Uytterhoeven 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3919543bb255SStephen Warren 			return -EINVAL;
3920a2fd4f9fSMark Brown 
39214d94bd21SIvan T. Ivanov 		/*
39224d94bd21SIvan T. Ivanov 		 * SPI transfer length should be multiple of SPI word size
3923350de7ceSAndy Shevchenko 		 * where SPI word size should be power-of-two multiple.
39244d94bd21SIvan T. Ivanov 		 */
39254d94bd21SIvan T. Ivanov 		if (xfer->bits_per_word <= 8)
39264d94bd21SIvan T. Ivanov 			w_size = 1;
39274d94bd21SIvan T. Ivanov 		else if (xfer->bits_per_word <= 16)
39284d94bd21SIvan T. Ivanov 			w_size = 2;
39294d94bd21SIvan T. Ivanov 		else
39304d94bd21SIvan T. Ivanov 			w_size = 4;
39314d94bd21SIvan T. Ivanov 
39324d94bd21SIvan T. Ivanov 		/* No partial transfers accepted */
39336ea31293SAtsushi Nemoto 		if (xfer->len % w_size)
39344d94bd21SIvan T. Ivanov 			return -EINVAL;
39354d94bd21SIvan T. Ivanov 
39368caab75fSGeert Uytterhoeven 		if (xfer->speed_hz && ctlr->min_speed_hz &&
39378caab75fSGeert Uytterhoeven 		    xfer->speed_hz < ctlr->min_speed_hz)
3938a2fd4f9fSMark Brown 			return -EINVAL;
3939f477b7fbSwangyuhang 
3940f477b7fbSwangyuhang 		if (xfer->tx_buf && !xfer->tx_nbits)
3941f477b7fbSwangyuhang 			xfer->tx_nbits = SPI_NBITS_SINGLE;
3942f477b7fbSwangyuhang 		if (xfer->rx_buf && !xfer->rx_nbits)
3943f477b7fbSwangyuhang 			xfer->rx_nbits = SPI_NBITS_SINGLE;
3944350de7ceSAndy Shevchenko 		/*
3945350de7ceSAndy Shevchenko 		 * Check transfer tx/rx_nbits:
39461afd9989SGeert Uytterhoeven 		 * 1. check the value matches one of single, dual and quad
39471afd9989SGeert Uytterhoeven 		 * 2. check tx/rx_nbits match the mode in spi_device
3948f477b7fbSwangyuhang 		 */
3949db90a441SSourav Poddar 		if (xfer->tx_buf) {
3950d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_TX)
3951d962608cSDragos Bogdan 				return -EINVAL;
3952f477b7fbSwangyuhang 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3953f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_DUAL &&
3954f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_QUAD)
3955a2fd4f9fSMark Brown 				return -EINVAL;
3956f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3957f477b7fbSwangyuhang 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3958f477b7fbSwangyuhang 				return -EINVAL;
3959f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3960f477b7fbSwangyuhang 				!(spi->mode & SPI_TX_QUAD))
3961f477b7fbSwangyuhang 				return -EINVAL;
3962db90a441SSourav Poddar 		}
396395c8222fSDavid Jander 		/* Check transfer rx_nbits */
3964db90a441SSourav Poddar 		if (xfer->rx_buf) {
3965d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_RX)
3966d962608cSDragos Bogdan 				return -EINVAL;
3967f477b7fbSwangyuhang 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3968f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_DUAL &&
3969f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_QUAD)
3970f477b7fbSwangyuhang 				return -EINVAL;
3971f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3972f477b7fbSwangyuhang 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3973f477b7fbSwangyuhang 				return -EINVAL;
3974f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3975f477b7fbSwangyuhang 				!(spi->mode & SPI_RX_QUAD))
3976f477b7fbSwangyuhang 				return -EINVAL;
3977e6811d1dSLaxman Dewangan 		}
3978b7bb367aSJonas Bonn 
39796c613f68SAlexandru Ardelean 		if (_spi_xfer_word_delay_update(xfer, spi))
39806c613f68SAlexandru Ardelean 			return -EINVAL;
3981e6811d1dSLaxman Dewangan 	}
3982e6811d1dSLaxman Dewangan 
3983cf32b71eSErnst Schwab 	message->status = -EINPROGRESS;
398490808738SMark Brown 
398590808738SMark Brown 	return 0;
398690808738SMark Brown }
398790808738SMark Brown 
398890808738SMark Brown static int __spi_async(struct spi_device *spi, struct spi_message *message)
398990808738SMark Brown {
39908caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3991b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
399290808738SMark Brown 
3993b5932f5cSBoris Brezillon 	/*
3994b5932f5cSBoris Brezillon 	 * Some controllers do not support doing regular SPI transfers. Return
3995b5932f5cSBoris Brezillon 	 * ENOTSUPP when this is the case.
3996b5932f5cSBoris Brezillon 	 */
3997b5932f5cSBoris Brezillon 	if (!ctlr->transfer)
3998b5932f5cSBoris Brezillon 		return -ENOTSUPP;
3999b5932f5cSBoris Brezillon 
400090808738SMark Brown 	message->spi = spi;
400190808738SMark Brown 
40026598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async);
40036598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async);
4004eca2ebc7SMartin Sperl 
400590808738SMark Brown 	trace_spi_message_submit(message);
400690808738SMark Brown 
4007b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported) {
4008b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
4009b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
4010b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
4011b42faeeeSVladimir Oltean 		}
4012b42faeeeSVladimir Oltean 	}
4013b42faeeeSVladimir Oltean 
40148caab75fSGeert Uytterhoeven 	return ctlr->transfer(spi, message);
4015cf32b71eSErnst Schwab }
4016cf32b71eSErnst Schwab 
4017568d0697SDavid Brownell /**
4018568d0697SDavid Brownell  * spi_async - asynchronous SPI transfer
4019568d0697SDavid Brownell  * @spi: device with which data will be exchanged
4020568d0697SDavid Brownell  * @message: describes the data transfers, including completion callback
4021568d0697SDavid Brownell  * Context: any (irqs may be blocked, etc)
4022568d0697SDavid Brownell  *
4023568d0697SDavid Brownell  * This call may be used in_irq and other contexts which can't sleep,
4024568d0697SDavid Brownell  * as well as from task contexts which can sleep.
4025568d0697SDavid Brownell  *
4026568d0697SDavid Brownell  * The completion callback is invoked in a context which can't sleep.
4027568d0697SDavid Brownell  * Before that invocation, the value of message->status is undefined.
4028568d0697SDavid Brownell  * When the callback is issued, message->status holds either zero (to
4029568d0697SDavid Brownell  * indicate complete success) or a negative error code.  After that
4030568d0697SDavid Brownell  * callback returns, the driver which issued the transfer request may
4031568d0697SDavid Brownell  * deallocate the associated memory; it's no longer in use by any SPI
4032568d0697SDavid Brownell  * core or controller driver code.
4033568d0697SDavid Brownell  *
4034568d0697SDavid Brownell  * Note that although all messages to a spi_device are handled in
4035568d0697SDavid Brownell  * FIFO order, messages may go to different devices in other orders.
4036568d0697SDavid Brownell  * Some device might be higher priority, or have various "hard" access
4037568d0697SDavid Brownell  * time requirements, for example.
4038568d0697SDavid Brownell  *
4039568d0697SDavid Brownell  * On detection of any fault during the transfer, processing of
4040568d0697SDavid Brownell  * the entire message is aborted, and the device is deselected.
4041568d0697SDavid Brownell  * Until returning from the associated message completion callback,
4042568d0697SDavid Brownell  * no other spi_message queued to that device will be processed.
4043568d0697SDavid Brownell  * (This rule applies equally to all the synchronous transfer calls,
4044568d0697SDavid Brownell  * which are wrappers around this core asynchronous primitive.)
404597d56dc6SJavier Martinez Canillas  *
404697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4047568d0697SDavid Brownell  */
4048568d0697SDavid Brownell int spi_async(struct spi_device *spi, struct spi_message *message)
4049568d0697SDavid Brownell {
40508caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4051cf32b71eSErnst Schwab 	int ret;
4052cf32b71eSErnst Schwab 	unsigned long flags;
4053568d0697SDavid Brownell 
405490808738SMark Brown 	ret = __spi_validate(spi, message);
405590808738SMark Brown 	if (ret != 0)
405690808738SMark Brown 		return ret;
405790808738SMark Brown 
40588caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4059568d0697SDavid Brownell 
40608caab75fSGeert Uytterhoeven 	if (ctlr->bus_lock_flag)
4061cf32b71eSErnst Schwab 		ret = -EBUSY;
4062cf32b71eSErnst Schwab 	else
4063cf32b71eSErnst Schwab 		ret = __spi_async(spi, message);
4064568d0697SDavid Brownell 
40658caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4066cf32b71eSErnst Schwab 
4067cf32b71eSErnst Schwab 	return ret;
4068568d0697SDavid Brownell }
4069568d0697SDavid Brownell EXPORT_SYMBOL_GPL(spi_async);
4070568d0697SDavid Brownell 
4071cf32b71eSErnst Schwab /**
4072cf32b71eSErnst Schwab  * spi_async_locked - version of spi_async with exclusive bus usage
4073cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
4074cf32b71eSErnst Schwab  * @message: describes the data transfers, including completion callback
4075cf32b71eSErnst Schwab  * Context: any (irqs may be blocked, etc)
4076cf32b71eSErnst Schwab  *
4077cf32b71eSErnst Schwab  * This call may be used in_irq and other contexts which can't sleep,
4078cf32b71eSErnst Schwab  * as well as from task contexts which can sleep.
4079cf32b71eSErnst Schwab  *
4080cf32b71eSErnst Schwab  * The completion callback is invoked in a context which can't sleep.
4081cf32b71eSErnst Schwab  * Before that invocation, the value of message->status is undefined.
4082cf32b71eSErnst Schwab  * When the callback is issued, message->status holds either zero (to
4083cf32b71eSErnst Schwab  * indicate complete success) or a negative error code.  After that
4084cf32b71eSErnst Schwab  * callback returns, the driver which issued the transfer request may
4085cf32b71eSErnst Schwab  * deallocate the associated memory; it's no longer in use by any SPI
4086cf32b71eSErnst Schwab  * core or controller driver code.
4087cf32b71eSErnst Schwab  *
4088cf32b71eSErnst Schwab  * Note that although all messages to a spi_device are handled in
4089cf32b71eSErnst Schwab  * FIFO order, messages may go to different devices in other orders.
4090cf32b71eSErnst Schwab  * Some device might be higher priority, or have various "hard" access
4091cf32b71eSErnst Schwab  * time requirements, for example.
4092cf32b71eSErnst Schwab  *
4093cf32b71eSErnst Schwab  * On detection of any fault during the transfer, processing of
4094cf32b71eSErnst Schwab  * the entire message is aborted, and the device is deselected.
4095cf32b71eSErnst Schwab  * Until returning from the associated message completion callback,
4096cf32b71eSErnst Schwab  * no other spi_message queued to that device will be processed.
4097cf32b71eSErnst Schwab  * (This rule applies equally to all the synchronous transfer calls,
4098cf32b71eSErnst Schwab  * which are wrappers around this core asynchronous primitive.)
409997d56dc6SJavier Martinez Canillas  *
410097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4101cf32b71eSErnst Schwab  */
4102da21fde0SUwe Kleine-König static int spi_async_locked(struct spi_device *spi, struct spi_message *message)
4103cf32b71eSErnst Schwab {
41048caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4105cf32b71eSErnst Schwab 	int ret;
4106cf32b71eSErnst Schwab 	unsigned long flags;
4107cf32b71eSErnst Schwab 
410890808738SMark Brown 	ret = __spi_validate(spi, message);
410990808738SMark Brown 	if (ret != 0)
411090808738SMark Brown 		return ret;
411190808738SMark Brown 
41128caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4113cf32b71eSErnst Schwab 
4114cf32b71eSErnst Schwab 	ret = __spi_async(spi, message);
4115cf32b71eSErnst Schwab 
41168caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4117cf32b71eSErnst Schwab 
4118cf32b71eSErnst Schwab 	return ret;
4119cf32b71eSErnst Schwab 
4120cf32b71eSErnst Schwab }
4121cf32b71eSErnst Schwab 
4122ae7d2346SDavid Jander static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg)
4123ae7d2346SDavid Jander {
4124ae7d2346SDavid Jander 	bool was_busy;
4125ae7d2346SDavid Jander 	int ret;
4126ae7d2346SDavid Jander 
4127ae7d2346SDavid Jander 	mutex_lock(&ctlr->io_mutex);
4128ae7d2346SDavid Jander 
41291a9cafcbSDavid Jander 	was_busy = ctlr->busy;
4130ae7d2346SDavid Jander 
413172c5c59bSDavid Jander 	ctlr->cur_msg = msg;
4132ae7d2346SDavid Jander 	ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
4133ae7d2346SDavid Jander 	if (ret)
4134ae7d2346SDavid Jander 		goto out;
4135ae7d2346SDavid Jander 
413669fa9590SDavid Jander 	ctlr->cur_msg = NULL;
413769fa9590SDavid Jander 	ctlr->fallback = false;
413869fa9590SDavid Jander 
4139ae7d2346SDavid Jander 	if (!was_busy) {
4140ae7d2346SDavid Jander 		kfree(ctlr->dummy_rx);
4141ae7d2346SDavid Jander 		ctlr->dummy_rx = NULL;
4142ae7d2346SDavid Jander 		kfree(ctlr->dummy_tx);
4143ae7d2346SDavid Jander 		ctlr->dummy_tx = NULL;
4144ae7d2346SDavid Jander 		if (ctlr->unprepare_transfer_hardware &&
4145ae7d2346SDavid Jander 		    ctlr->unprepare_transfer_hardware(ctlr))
4146ae7d2346SDavid Jander 			dev_err(&ctlr->dev,
4147ae7d2346SDavid Jander 				"failed to unprepare transfer hardware\n");
4148ae7d2346SDavid Jander 		spi_idle_runtime_pm(ctlr);
4149ae7d2346SDavid Jander 	}
4150ae7d2346SDavid Jander 
4151ae7d2346SDavid Jander out:
4152ae7d2346SDavid Jander 	mutex_unlock(&ctlr->io_mutex);
4153ae7d2346SDavid Jander }
4154ae7d2346SDavid Jander 
41557d077197SDavid Brownell /*-------------------------------------------------------------------------*/
41567d077197SDavid Brownell 
4157350de7ceSAndy Shevchenko /*
4158350de7ceSAndy Shevchenko  * Utility methods for SPI protocol drivers, layered on
41597d077197SDavid Brownell  * top of the core.  Some other utility methods are defined as
41607d077197SDavid Brownell  * inline functions.
41617d077197SDavid Brownell  */
41627d077197SDavid Brownell 
41635d870c8eSAndrew Morton static void spi_complete(void *arg)
41645d870c8eSAndrew Morton {
41655d870c8eSAndrew Morton 	complete(arg);
41665d870c8eSAndrew Morton }
41675d870c8eSAndrew Morton 
4168ef4d96ecSMark Brown static int __spi_sync(struct spi_device *spi, struct spi_message *message)
4169cf32b71eSErnst Schwab {
4170cf32b71eSErnst Schwab 	DECLARE_COMPLETION_ONSTACK(done);
4171cf32b71eSErnst Schwab 	int status;
41728caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
41730461a414SMark Brown 
41740461a414SMark Brown 	status = __spi_validate(spi, message);
41750461a414SMark Brown 	if (status != 0)
41760461a414SMark Brown 		return status;
4177cf32b71eSErnst Schwab 
41780461a414SMark Brown 	message->spi = spi;
4179cf32b71eSErnst Schwab 
41806598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync);
41816598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync);
4182eca2ebc7SMartin Sperl 
4183350de7ceSAndy Shevchenko 	/*
4184ae7d2346SDavid Jander 	 * Checking queue_empty here only guarantees async/sync message
4185ae7d2346SDavid Jander 	 * ordering when coming from the same context. It does not need to
4186ae7d2346SDavid Jander 	 * guard against reentrancy from a different context. The io_mutex
4187ae7d2346SDavid Jander 	 * will catch those cases.
41880461a414SMark Brown 	 */
4189b30f7c8eSMark Brown 	if (READ_ONCE(ctlr->queue_empty) && !ctlr->must_async) {
4190ae7d2346SDavid Jander 		message->actual_length = 0;
4191ae7d2346SDavid Jander 		message->status = -EINPROGRESS;
41920461a414SMark Brown 
41930461a414SMark Brown 		trace_spi_message_submit(message);
41940461a414SMark Brown 
4195ae7d2346SDavid Jander 		SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate);
4196ae7d2346SDavid Jander 		SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate);
41970461a414SMark Brown 
4198ae7d2346SDavid Jander 		__spi_transfer_message_noqueue(ctlr, message);
4199ae7d2346SDavid Jander 
4200ae7d2346SDavid Jander 		return message->status;
4201ae7d2346SDavid Jander 	}
4202ae7d2346SDavid Jander 
4203ae7d2346SDavid Jander 	/*
4204ae7d2346SDavid Jander 	 * There are messages in the async queue that could have originated
4205ae7d2346SDavid Jander 	 * from the same context, so we need to preserve ordering.
4206ae7d2346SDavid Jander 	 * Therefor we send the message to the async queue and wait until they
4207ae7d2346SDavid Jander 	 * are completed.
4208ae7d2346SDavid Jander 	 */
4209ae7d2346SDavid Jander 	message->complete = spi_complete;
4210ae7d2346SDavid Jander 	message->context = &done;
4211cf32b71eSErnst Schwab 	status = spi_async_locked(spi, message);
4212cf32b71eSErnst Schwab 	if (status == 0) {
4213cf32b71eSErnst Schwab 		wait_for_completion(&done);
4214cf32b71eSErnst Schwab 		status = message->status;
4215cf32b71eSErnst Schwab 	}
4216cf32b71eSErnst Schwab 	message->context = NULL;
4217ae7d2346SDavid Jander 
4218cf32b71eSErnst Schwab 	return status;
4219cf32b71eSErnst Schwab }
4220cf32b71eSErnst Schwab 
42218ae12a0dSDavid Brownell /**
42228ae12a0dSDavid Brownell  * spi_sync - blocking/synchronous SPI data transfers
42238ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
42248ae12a0dSDavid Brownell  * @message: describes the data transfers
422533e34dc6SDavid Brownell  * Context: can sleep
42268ae12a0dSDavid Brownell  *
42278ae12a0dSDavid Brownell  * This call may only be used from a context that may sleep.  The sleep
42288ae12a0dSDavid Brownell  * is non-interruptible, and has no timeout.  Low-overhead controller
42298ae12a0dSDavid Brownell  * drivers may DMA directly into and out of the message buffers.
42308ae12a0dSDavid Brownell  *
42318ae12a0dSDavid Brownell  * Note that the SPI device's chip select is active during the message,
42328ae12a0dSDavid Brownell  * and then is normally disabled between messages.  Drivers for some
42338ae12a0dSDavid Brownell  * frequently-used devices may want to minimize costs of selecting a chip,
42348ae12a0dSDavid Brownell  * by leaving it selected in anticipation that the next message will go
42358ae12a0dSDavid Brownell  * to the same chip.  (That may increase power usage.)
42368ae12a0dSDavid Brownell  *
42370c868461SDavid Brownell  * Also, the caller is guaranteeing that the memory associated with the
42380c868461SDavid Brownell  * message will not be freed before this call returns.
42390c868461SDavid Brownell  *
424097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
42418ae12a0dSDavid Brownell  */
42428ae12a0dSDavid Brownell int spi_sync(struct spi_device *spi, struct spi_message *message)
42438ae12a0dSDavid Brownell {
4244ef4d96ecSMark Brown 	int ret;
4245ef4d96ecSMark Brown 
42468caab75fSGeert Uytterhoeven 	mutex_lock(&spi->controller->bus_lock_mutex);
4247ef4d96ecSMark Brown 	ret = __spi_sync(spi, message);
42488caab75fSGeert Uytterhoeven 	mutex_unlock(&spi->controller->bus_lock_mutex);
4249ef4d96ecSMark Brown 
4250ef4d96ecSMark Brown 	return ret;
42518ae12a0dSDavid Brownell }
42528ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_sync);
42538ae12a0dSDavid Brownell 
4254cf32b71eSErnst Schwab /**
4255cf32b71eSErnst Schwab  * spi_sync_locked - version of spi_sync with exclusive bus usage
4256cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
4257cf32b71eSErnst Schwab  * @message: describes the data transfers
4258cf32b71eSErnst Schwab  * Context: can sleep
4259cf32b71eSErnst Schwab  *
4260cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4261cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.  Low-overhead controller
4262cf32b71eSErnst Schwab  * drivers may DMA directly into and out of the message buffers.
4263cf32b71eSErnst Schwab  *
4264cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
426525985edcSLucas De Marchi  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4266cf32b71eSErnst Schwab  * be released by a spi_bus_unlock call when the exclusive access is over.
4267cf32b71eSErnst Schwab  *
426897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4269cf32b71eSErnst Schwab  */
4270cf32b71eSErnst Schwab int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4271cf32b71eSErnst Schwab {
4272ef4d96ecSMark Brown 	return __spi_sync(spi, message);
4273cf32b71eSErnst Schwab }
4274cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_sync_locked);
4275cf32b71eSErnst Schwab 
4276cf32b71eSErnst Schwab /**
4277cf32b71eSErnst Schwab  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
42788caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that should be locked for exclusive bus access
4279cf32b71eSErnst Schwab  * Context: can sleep
4280cf32b71eSErnst Schwab  *
4281cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4282cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4283cf32b71eSErnst Schwab  *
4284cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
4285cf32b71eSErnst Schwab  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4286cf32b71eSErnst Schwab  * exclusive access is over. Data transfer must be done by spi_sync_locked
4287cf32b71eSErnst Schwab  * and spi_async_locked calls when the SPI bus lock is held.
4288cf32b71eSErnst Schwab  *
428997d56dc6SJavier Martinez Canillas  * Return: always zero.
4290cf32b71eSErnst Schwab  */
42918caab75fSGeert Uytterhoeven int spi_bus_lock(struct spi_controller *ctlr)
4292cf32b71eSErnst Schwab {
4293cf32b71eSErnst Schwab 	unsigned long flags;
4294cf32b71eSErnst Schwab 
42958caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->bus_lock_mutex);
4296cf32b71eSErnst Schwab 
42978caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
42988caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 1;
42998caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4300cf32b71eSErnst Schwab 
430195c8222fSDavid Jander 	/* Mutex remains locked until spi_bus_unlock() is called */
4302cf32b71eSErnst Schwab 
4303cf32b71eSErnst Schwab 	return 0;
4304cf32b71eSErnst Schwab }
4305cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_lock);
4306cf32b71eSErnst Schwab 
4307cf32b71eSErnst Schwab /**
4308cf32b71eSErnst Schwab  * spi_bus_unlock - release the lock for exclusive SPI bus usage
43098caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that was locked for exclusive bus access
4310cf32b71eSErnst Schwab  * Context: can sleep
4311cf32b71eSErnst Schwab  *
4312cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4313cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4314cf32b71eSErnst Schwab  *
4315cf32b71eSErnst Schwab  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4316cf32b71eSErnst Schwab  * call.
4317cf32b71eSErnst Schwab  *
431897d56dc6SJavier Martinez Canillas  * Return: always zero.
4319cf32b71eSErnst Schwab  */
43208caab75fSGeert Uytterhoeven int spi_bus_unlock(struct spi_controller *ctlr)
4321cf32b71eSErnst Schwab {
43228caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
4323cf32b71eSErnst Schwab 
43248caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->bus_lock_mutex);
4325cf32b71eSErnst Schwab 
4326cf32b71eSErnst Schwab 	return 0;
4327cf32b71eSErnst Schwab }
4328cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_unlock);
4329cf32b71eSErnst Schwab 
433095c8222fSDavid Jander /* Portable code must never pass more than 32 bytes */
4331a9948b61SDavid Brownell #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
43328ae12a0dSDavid Brownell 
43338ae12a0dSDavid Brownell static u8	*buf;
43348ae12a0dSDavid Brownell 
43358ae12a0dSDavid Brownell /**
43368ae12a0dSDavid Brownell  * spi_write_then_read - SPI synchronous write followed by read
43378ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
43388ae12a0dSDavid Brownell  * @txbuf: data to be written (need not be dma-safe)
43398ae12a0dSDavid Brownell  * @n_tx: size of txbuf, in bytes
434027570497SJiri Pirko  * @rxbuf: buffer into which data will be read (need not be dma-safe)
434127570497SJiri Pirko  * @n_rx: size of rxbuf, in bytes
434233e34dc6SDavid Brownell  * Context: can sleep
43438ae12a0dSDavid Brownell  *
43448ae12a0dSDavid Brownell  * This performs a half duplex MicroWire style transaction with the
43458ae12a0dSDavid Brownell  * device, sending txbuf and then reading rxbuf.  The return value
43468ae12a0dSDavid Brownell  * is zero for success, else a negative errno status code.
4347b885244eSDavid Brownell  * This call may only be used from a context that may sleep.
43488ae12a0dSDavid Brownell  *
4349c373643bSMark Brown  * Parameters to this routine are always copied using a small buffer.
435033e34dc6SDavid Brownell  * Performance-sensitive or bulk transfer code should instead use
43510c868461SDavid Brownell  * spi_{async,sync}() calls with dma-safe buffers.
435297d56dc6SJavier Martinez Canillas  *
435397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
43548ae12a0dSDavid Brownell  */
43558ae12a0dSDavid Brownell int spi_write_then_read(struct spi_device *spi,
43560c4a1590SMark Brown 		const void *txbuf, unsigned n_tx,
43570c4a1590SMark Brown 		void *rxbuf, unsigned n_rx)
43588ae12a0dSDavid Brownell {
4359068f4070SDavid Brownell 	static DEFINE_MUTEX(lock);
43608ae12a0dSDavid Brownell 
43618ae12a0dSDavid Brownell 	int			status;
43628ae12a0dSDavid Brownell 	struct spi_message	message;
4363bdff549eSDavid Brownell 	struct spi_transfer	x[2];
43648ae12a0dSDavid Brownell 	u8			*local_buf;
43658ae12a0dSDavid Brownell 
4366350de7ceSAndy Shevchenko 	/*
4367350de7ceSAndy Shevchenko 	 * Use preallocated DMA-safe buffer if we can. We can't avoid
4368b3a223eeSMark Brown 	 * copying here, (as a pure convenience thing), but we can
4369b3a223eeSMark Brown 	 * keep heap costs out of the hot path unless someone else is
4370b3a223eeSMark Brown 	 * using the pre-allocated buffer or the transfer is too large.
43718ae12a0dSDavid Brownell 	 */
4372b3a223eeSMark Brown 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
43732cd94c8aSMark Brown 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
43742cd94c8aSMark Brown 				    GFP_KERNEL | GFP_DMA);
4375b3a223eeSMark Brown 		if (!local_buf)
4376b3a223eeSMark Brown 			return -ENOMEM;
4377b3a223eeSMark Brown 	} else {
4378b3a223eeSMark Brown 		local_buf = buf;
4379b3a223eeSMark Brown 	}
43808ae12a0dSDavid Brownell 
43818275c642SVitaly Wool 	spi_message_init(&message);
43825fe5f05eSJingoo Han 	memset(x, 0, sizeof(x));
4383bdff549eSDavid Brownell 	if (n_tx) {
4384bdff549eSDavid Brownell 		x[0].len = n_tx;
4385bdff549eSDavid Brownell 		spi_message_add_tail(&x[0], &message);
4386bdff549eSDavid Brownell 	}
4387bdff549eSDavid Brownell 	if (n_rx) {
4388bdff549eSDavid Brownell 		x[1].len = n_rx;
4389bdff549eSDavid Brownell 		spi_message_add_tail(&x[1], &message);
4390bdff549eSDavid Brownell 	}
43918275c642SVitaly Wool 
43928ae12a0dSDavid Brownell 	memcpy(local_buf, txbuf, n_tx);
4393bdff549eSDavid Brownell 	x[0].tx_buf = local_buf;
4394bdff549eSDavid Brownell 	x[1].rx_buf = local_buf + n_tx;
43958ae12a0dSDavid Brownell 
439695c8222fSDavid Jander 	/* Do the i/o */
43978ae12a0dSDavid Brownell 	status = spi_sync(spi, &message);
43989b938b74SMarc Pignat 	if (status == 0)
4399bdff549eSDavid Brownell 		memcpy(rxbuf, x[1].rx_buf, n_rx);
44008ae12a0dSDavid Brownell 
4401bdff549eSDavid Brownell 	if (x[0].tx_buf == buf)
4402068f4070SDavid Brownell 		mutex_unlock(&lock);
44038ae12a0dSDavid Brownell 	else
44048ae12a0dSDavid Brownell 		kfree(local_buf);
44058ae12a0dSDavid Brownell 
44068ae12a0dSDavid Brownell 	return status;
44078ae12a0dSDavid Brownell }
44088ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_write_then_read);
44098ae12a0dSDavid Brownell 
44108ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
44118ae12a0dSDavid Brownell 
4412da21fde0SUwe Kleine-König #if IS_ENABLED(CONFIG_OF_DYNAMIC)
441395c8222fSDavid Jander /* Must call put_device() when done with returned spi_device device */
4414da21fde0SUwe Kleine-König static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4415ce79d54aSPantelis Antoniou {
4416cfba5de9SSuzuki K Poulose 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4417cfba5de9SSuzuki K Poulose 
4418ce79d54aSPantelis Antoniou 	return dev ? to_spi_device(dev) : NULL;
4419ce79d54aSPantelis Antoniou }
4420ce79d54aSPantelis Antoniou 
442195c8222fSDavid Jander /* The spi controllers are not using spi_bus, so we find it with another way */
44228caab75fSGeert Uytterhoeven static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4423ce79d54aSPantelis Antoniou {
4424ce79d54aSPantelis Antoniou 	struct device *dev;
4425ce79d54aSPantelis Antoniou 
4426cfba5de9SSuzuki K Poulose 	dev = class_find_device_by_of_node(&spi_master_class, node);
44276c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4428cfba5de9SSuzuki K Poulose 		dev = class_find_device_by_of_node(&spi_slave_class, node);
4429ce79d54aSPantelis Antoniou 	if (!dev)
4430ce79d54aSPantelis Antoniou 		return NULL;
4431ce79d54aSPantelis Antoniou 
443295c8222fSDavid Jander 	/* Reference got in class_find_device */
44338caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
4434ce79d54aSPantelis Antoniou }
4435ce79d54aSPantelis Antoniou 
4436ce79d54aSPantelis Antoniou static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4437ce79d54aSPantelis Antoniou 			 void *arg)
4438ce79d54aSPantelis Antoniou {
4439ce79d54aSPantelis Antoniou 	struct of_reconfig_data *rd = arg;
44408caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
4441ce79d54aSPantelis Antoniou 	struct spi_device *spi;
4442ce79d54aSPantelis Antoniou 
4443ce79d54aSPantelis Antoniou 	switch (of_reconfig_get_state_change(action, arg)) {
4444ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_ADD:
44458caab75fSGeert Uytterhoeven 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
44468caab75fSGeert Uytterhoeven 		if (ctlr == NULL)
444795c8222fSDavid Jander 			return NOTIFY_OK;	/* Not for us */
4448ce79d54aSPantelis Antoniou 
4449bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
44508caab75fSGeert Uytterhoeven 			put_device(&ctlr->dev);
4451bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4452bd6c1644SGeert Uytterhoeven 		}
4453bd6c1644SGeert Uytterhoeven 
44548caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, rd->dn);
44558caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
4456ce79d54aSPantelis Antoniou 
4457ce79d54aSPantelis Antoniou 		if (IS_ERR(spi)) {
445825c56c88SRob Herring 			pr_err("%s: failed to create for '%pOF'\n",
445925c56c88SRob Herring 					__func__, rd->dn);
4460e0af98a7SRalf Ramsauer 			of_node_clear_flag(rd->dn, OF_POPULATED);
4461ce79d54aSPantelis Antoniou 			return notifier_from_errno(PTR_ERR(spi));
4462ce79d54aSPantelis Antoniou 		}
4463ce79d54aSPantelis Antoniou 		break;
4464ce79d54aSPantelis Antoniou 
4465ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_REMOVE:
446695c8222fSDavid Jander 		/* Already depopulated? */
4467bd6c1644SGeert Uytterhoeven 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4468bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4469bd6c1644SGeert Uytterhoeven 
447095c8222fSDavid Jander 		/* Find our device by node */
4471ce79d54aSPantelis Antoniou 		spi = of_find_spi_device_by_node(rd->dn);
4472ce79d54aSPantelis Antoniou 		if (spi == NULL)
447395c8222fSDavid Jander 			return NOTIFY_OK;	/* No? not meant for us */
4474ce79d54aSPantelis Antoniou 
447595c8222fSDavid Jander 		/* Unregister takes one ref away */
4476ce79d54aSPantelis Antoniou 		spi_unregister_device(spi);
4477ce79d54aSPantelis Antoniou 
447895c8222fSDavid Jander 		/* And put the reference of the find */
4479ce79d54aSPantelis Antoniou 		put_device(&spi->dev);
4480ce79d54aSPantelis Antoniou 		break;
4481ce79d54aSPantelis Antoniou 	}
4482ce79d54aSPantelis Antoniou 
4483ce79d54aSPantelis Antoniou 	return NOTIFY_OK;
4484ce79d54aSPantelis Antoniou }
4485ce79d54aSPantelis Antoniou 
4486ce79d54aSPantelis Antoniou static struct notifier_block spi_of_notifier = {
4487ce79d54aSPantelis Antoniou 	.notifier_call = of_spi_notify,
4488ce79d54aSPantelis Antoniou };
4489ce79d54aSPantelis Antoniou #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4490ce79d54aSPantelis Antoniou extern struct notifier_block spi_of_notifier;
4491ce79d54aSPantelis Antoniou #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4492ce79d54aSPantelis Antoniou 
44937f24467fSOctavian Purdila #if IS_ENABLED(CONFIG_ACPI)
44948caab75fSGeert Uytterhoeven static int spi_acpi_controller_match(struct device *dev, const void *data)
44957f24467fSOctavian Purdila {
44967f24467fSOctavian Purdila 	return ACPI_COMPANION(dev->parent) == data;
44977f24467fSOctavian Purdila }
44987f24467fSOctavian Purdila 
44998caab75fSGeert Uytterhoeven static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
45007f24467fSOctavian Purdila {
45017f24467fSOctavian Purdila 	struct device *dev;
45027f24467fSOctavian Purdila 
45037f24467fSOctavian Purdila 	dev = class_find_device(&spi_master_class, NULL, adev,
45048caab75fSGeert Uytterhoeven 				spi_acpi_controller_match);
45056c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
45066c364062SGeert Uytterhoeven 		dev = class_find_device(&spi_slave_class, NULL, adev,
45078caab75fSGeert Uytterhoeven 					spi_acpi_controller_match);
45087f24467fSOctavian Purdila 	if (!dev)
45097f24467fSOctavian Purdila 		return NULL;
45107f24467fSOctavian Purdila 
45118caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
45127f24467fSOctavian Purdila }
45137f24467fSOctavian Purdila 
45147f24467fSOctavian Purdila static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
45157f24467fSOctavian Purdila {
45167f24467fSOctavian Purdila 	struct device *dev;
45177f24467fSOctavian Purdila 
451800500147SSuzuki K Poulose 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
45195b16668eSWolfram Sang 	return to_spi_device(dev);
45207f24467fSOctavian Purdila }
45217f24467fSOctavian Purdila 
45227f24467fSOctavian Purdila static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
45237f24467fSOctavian Purdila 			   void *arg)
45247f24467fSOctavian Purdila {
45257f24467fSOctavian Purdila 	struct acpi_device *adev = arg;
45268caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
45277f24467fSOctavian Purdila 	struct spi_device *spi;
45287f24467fSOctavian Purdila 
45297f24467fSOctavian Purdila 	switch (value) {
45307f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_ADD:
453162fcb99bSRafael J. Wysocki 		ctlr = acpi_spi_find_controller_by_adev(acpi_dev_parent(adev));
45328caab75fSGeert Uytterhoeven 		if (!ctlr)
45337f24467fSOctavian Purdila 			break;
45347f24467fSOctavian Purdila 
45358caab75fSGeert Uytterhoeven 		acpi_register_spi_device(ctlr, adev);
45368caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
45377f24467fSOctavian Purdila 		break;
45387f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_REMOVE:
45397f24467fSOctavian Purdila 		if (!acpi_device_enumerated(adev))
45407f24467fSOctavian Purdila 			break;
45417f24467fSOctavian Purdila 
45427f24467fSOctavian Purdila 		spi = acpi_spi_find_device_by_adev(adev);
45437f24467fSOctavian Purdila 		if (!spi)
45447f24467fSOctavian Purdila 			break;
45457f24467fSOctavian Purdila 
45467f24467fSOctavian Purdila 		spi_unregister_device(spi);
45477f24467fSOctavian Purdila 		put_device(&spi->dev);
45487f24467fSOctavian Purdila 		break;
45497f24467fSOctavian Purdila 	}
45507f24467fSOctavian Purdila 
45517f24467fSOctavian Purdila 	return NOTIFY_OK;
45527f24467fSOctavian Purdila }
45537f24467fSOctavian Purdila 
45547f24467fSOctavian Purdila static struct notifier_block spi_acpi_notifier = {
45557f24467fSOctavian Purdila 	.notifier_call = acpi_spi_notify,
45567f24467fSOctavian Purdila };
45577f24467fSOctavian Purdila #else
45587f24467fSOctavian Purdila extern struct notifier_block spi_acpi_notifier;
45597f24467fSOctavian Purdila #endif
45607f24467fSOctavian Purdila 
45618ae12a0dSDavid Brownell static int __init spi_init(void)
45628ae12a0dSDavid Brownell {
4563b885244eSDavid Brownell 	int	status;
45648ae12a0dSDavid Brownell 
4565e94b1766SChristoph Lameter 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4566b885244eSDavid Brownell 	if (!buf) {
4567b885244eSDavid Brownell 		status = -ENOMEM;
4568b885244eSDavid Brownell 		goto err0;
45698ae12a0dSDavid Brownell 	}
4570b885244eSDavid Brownell 
4571b885244eSDavid Brownell 	status = bus_register(&spi_bus_type);
4572b885244eSDavid Brownell 	if (status < 0)
4573b885244eSDavid Brownell 		goto err1;
4574b885244eSDavid Brownell 
4575b885244eSDavid Brownell 	status = class_register(&spi_master_class);
4576b885244eSDavid Brownell 	if (status < 0)
4577b885244eSDavid Brownell 		goto err2;
4578ce79d54aSPantelis Antoniou 
45796c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
45806c364062SGeert Uytterhoeven 		status = class_register(&spi_slave_class);
45816c364062SGeert Uytterhoeven 		if (status < 0)
45826c364062SGeert Uytterhoeven 			goto err3;
45836c364062SGeert Uytterhoeven 	}
45846c364062SGeert Uytterhoeven 
45855267720eSFabio Estevam 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4586ce79d54aSPantelis Antoniou 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
45877f24467fSOctavian Purdila 	if (IS_ENABLED(CONFIG_ACPI))
45887f24467fSOctavian Purdila 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4589ce79d54aSPantelis Antoniou 
4590b885244eSDavid Brownell 	return 0;
4591b885244eSDavid Brownell 
45926c364062SGeert Uytterhoeven err3:
45936c364062SGeert Uytterhoeven 	class_unregister(&spi_master_class);
4594b885244eSDavid Brownell err2:
4595b885244eSDavid Brownell 	bus_unregister(&spi_bus_type);
4596b885244eSDavid Brownell err1:
4597b885244eSDavid Brownell 	kfree(buf);
4598b885244eSDavid Brownell 	buf = NULL;
4599b885244eSDavid Brownell err0:
4600b885244eSDavid Brownell 	return status;
4601b885244eSDavid Brownell }
4602b885244eSDavid Brownell 
4603350de7ceSAndy Shevchenko /*
4604350de7ceSAndy Shevchenko  * A board_info is normally registered in arch_initcall(),
4605350de7ceSAndy Shevchenko  * but even essential drivers wait till later.
4606b885244eSDavid Brownell  *
4607350de7ceSAndy Shevchenko  * REVISIT only boardinfo really needs static linking. The rest (device and
4608350de7ceSAndy Shevchenko  * driver registration) _could_ be dynamically linked (modular) ... Costs
4609b885244eSDavid Brownell  * include needing to have boardinfo data structures be much more public.
46108ae12a0dSDavid Brownell  */
4611673c0c00SDavid Brownell postcore_initcall(spi_init);
4612