xref: /openbmc/linux/drivers/spi/spi.c (revision ecc23d0a422a3118fcf6e4f0a46e17a6c2047b02)
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 
7edf6a864SAndy Shevchenko #include <linux/acpi.h>
88ae12a0dSDavid Brownell #include <linux/cache.h>
9edf6a864SAndy Shevchenko #include <linux/clk/clk-conf.h>
10edf6a864SAndy Shevchenko #include <linux/delay.h>
11edf6a864SAndy Shevchenko #include <linux/device.h>
1299adef31SMark Brown #include <linux/dmaengine.h>
13edf6a864SAndy Shevchenko #include <linux/dma-mapping.h>
14edf6a864SAndy Shevchenko #include <linux/export.h>
15edf6a864SAndy Shevchenko #include <linux/gpio/consumer.h>
16edf6a864SAndy Shevchenko #include <linux/highmem.h>
17edf6a864SAndy Shevchenko #include <linux/idr.h>
18edf6a864SAndy Shevchenko #include <linux/init.h>
19edf6a864SAndy Shevchenko #include <linux/ioport.h>
20edf6a864SAndy Shevchenko #include <linux/kernel.h>
21edf6a864SAndy Shevchenko #include <linux/kthread.h>
22edf6a864SAndy Shevchenko #include <linux/mod_devicetable.h>
2394040828SMatthias Kaehlcke #include <linux/mutex.h>
242b7a32f7SSinan Akman #include <linux/of_device.h>
25d57a4282SGrant Likely #include <linux/of_irq.h>
26edf6a864SAndy Shevchenko #include <linux/percpu.h>
27edf6a864SAndy Shevchenko #include <linux/platform_data/x86/apple.h>
28edf6a864SAndy Shevchenko #include <linux/pm_domain.h>
29edf6a864SAndy Shevchenko #include <linux/pm_runtime.h>
30edf6a864SAndy Shevchenko #include <linux/property.h>
31edf6a864SAndy Shevchenko #include <linux/ptp_clock_kernel.h>
32edf6a864SAndy Shevchenko #include <linux/sched/rt.h>
335a0e3ad6STejun Heo #include <linux/slab.h>
348ae12a0dSDavid Brownell #include <linux/spi/spi.h>
35b5932f5cSBoris Brezillon #include <linux/spi/spi-mem.h>
36ae7e81c0SIngo Molnar #include <uapi/linux/sched/types.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 
spidev_release(struct device * dev)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
modalias_show(struct device * dev,struct device_attribute * a,char * buf)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 
67f2daa466SAndy Shevchenko 	return sysfs_emit(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
688ae12a0dSDavid Brownell }
69aa7da564SGreg Kroah-Hartman static DEVICE_ATTR_RO(modalias);
708ae12a0dSDavid Brownell 
driver_override_store(struct device * dev,struct device_attribute * a,const char * buf,size_t count)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 
driver_override_show(struct device * dev,struct device_attribute * a,char * buf)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);
92f2daa466SAndy Shevchenko 	len = sysfs_emit(buf, "%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 
spi_alloc_pcpu_stats(struct device * dev)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 
spi_emit_pcpu_stats(struct spi_statistics __percpu * stat,char * buf,size_t offset)120fc12d4bbSGeert Uytterhoeven static ssize_t spi_emit_pcpu_stats(struct spi_statistics __percpu *stat,
121fc12d4bbSGeert Uytterhoeven 				   char *buf, size_t offset)
122fc12d4bbSGeert Uytterhoeven {
123fc12d4bbSGeert Uytterhoeven 	u64 val = 0;
124fc12d4bbSGeert Uytterhoeven 	int i;
125fc12d4bbSGeert Uytterhoeven 
126fc12d4bbSGeert Uytterhoeven 	for_each_possible_cpu(i) {
127fc12d4bbSGeert Uytterhoeven 		const struct spi_statistics *pcpu_stats;
128fc12d4bbSGeert Uytterhoeven 		u64_stats_t *field;
129fc12d4bbSGeert Uytterhoeven 		unsigned int start;
130fc12d4bbSGeert Uytterhoeven 		u64 inc;
131fc12d4bbSGeert Uytterhoeven 
132fc12d4bbSGeert Uytterhoeven 		pcpu_stats = per_cpu_ptr(stat, i);
133fc12d4bbSGeert Uytterhoeven 		field = (void *)pcpu_stats + offset;
134fc12d4bbSGeert Uytterhoeven 		do {
135fc12d4bbSGeert Uytterhoeven 			start = u64_stats_fetch_begin(&pcpu_stats->syncp);
136fc12d4bbSGeert Uytterhoeven 			inc = u64_stats_read(field);
137fc12d4bbSGeert Uytterhoeven 		} while (u64_stats_fetch_retry(&pcpu_stats->syncp, start));
138fc12d4bbSGeert Uytterhoeven 		val += inc;
139fc12d4bbSGeert Uytterhoeven 	}
140fc12d4bbSGeert Uytterhoeven 	return sysfs_emit(buf, "%llu\n", val);
141fc12d4bbSGeert Uytterhoeven }
1426598b91bSDavid Jander 
143eca2ebc7SMartin Sperl #define SPI_STATISTICS_ATTRS(field, file)				\
1448caab75fSGeert Uytterhoeven static ssize_t spi_controller_##field##_show(struct device *dev,	\
145eca2ebc7SMartin Sperl 					     struct device_attribute *attr, \
146eca2ebc7SMartin Sperl 					     char *buf)			\
147eca2ebc7SMartin Sperl {									\
1488caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev,			\
1498caab75fSGeert Uytterhoeven 					 struct spi_controller, dev);	\
1506598b91bSDavid Jander 	return spi_statistics_##field##_show(ctlr->pcpu_statistics, buf); \
151eca2ebc7SMartin Sperl }									\
1528caab75fSGeert Uytterhoeven static struct device_attribute dev_attr_spi_controller_##field = {	\
153ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
1548caab75fSGeert Uytterhoeven 	.show = spi_controller_##field##_show,				\
155eca2ebc7SMartin Sperl };									\
156eca2ebc7SMartin Sperl static ssize_t spi_device_##field##_show(struct device *dev,		\
157eca2ebc7SMartin Sperl 					 struct device_attribute *attr,	\
158eca2ebc7SMartin Sperl 					char *buf)			\
159eca2ebc7SMartin Sperl {									\
160d1eba93bSGeliang Tang 	struct spi_device *spi = to_spi_device(dev);			\
1616598b91bSDavid Jander 	return spi_statistics_##field##_show(spi->pcpu_statistics, buf); \
162eca2ebc7SMartin Sperl }									\
163eca2ebc7SMartin Sperl static struct device_attribute dev_attr_spi_device_##field = {		\
164ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
165eca2ebc7SMartin Sperl 	.show = spi_device_##field##_show,				\
166eca2ebc7SMartin Sperl }
167eca2ebc7SMartin Sperl 
1686598b91bSDavid Jander #define SPI_STATISTICS_SHOW_NAME(name, file, field)			\
169d501cc4cSDavid Jander static ssize_t spi_statistics_##name##_show(struct spi_statistics __percpu *stat, \
170eca2ebc7SMartin Sperl 					    char *buf)			\
171eca2ebc7SMartin Sperl {									\
172fc12d4bbSGeert Uytterhoeven 	return spi_emit_pcpu_stats(stat, buf,				\
173fc12d4bbSGeert Uytterhoeven 			offsetof(struct spi_statistics, field));	\
174eca2ebc7SMartin Sperl }									\
175eca2ebc7SMartin Sperl SPI_STATISTICS_ATTRS(name, file)
176eca2ebc7SMartin Sperl 
1776598b91bSDavid Jander #define SPI_STATISTICS_SHOW(field)					\
178eca2ebc7SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(field, __stringify(field),		\
1796598b91bSDavid Jander 				 field)
180eca2ebc7SMartin Sperl 
1816598b91bSDavid Jander SPI_STATISTICS_SHOW(messages);
1826598b91bSDavid Jander SPI_STATISTICS_SHOW(transfers);
1836598b91bSDavid Jander SPI_STATISTICS_SHOW(errors);
1846598b91bSDavid Jander SPI_STATISTICS_SHOW(timedout);
185eca2ebc7SMartin Sperl 
1866598b91bSDavid Jander SPI_STATISTICS_SHOW(spi_sync);
1876598b91bSDavid Jander SPI_STATISTICS_SHOW(spi_sync_immediate);
1886598b91bSDavid Jander SPI_STATISTICS_SHOW(spi_async);
189eca2ebc7SMartin Sperl 
1906598b91bSDavid Jander SPI_STATISTICS_SHOW(bytes);
1916598b91bSDavid Jander SPI_STATISTICS_SHOW(bytes_rx);
1926598b91bSDavid Jander SPI_STATISTICS_SHOW(bytes_tx);
193eca2ebc7SMartin Sperl 
1946b7bc061SMartin Sperl #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number)		\
1956b7bc061SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index,		\
1966b7bc061SMartin Sperl 				 "transfer_bytes_histo_" number,	\
1976598b91bSDavid Jander 				 transfer_bytes_histo[index])
1986b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(0,  "0-1");
1996b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(1,  "2-3");
2006b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(2,  "4-7");
2016b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(3,  "8-15");
2026b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(4,  "16-31");
2036b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(5,  "32-63");
2046b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(6,  "64-127");
2056b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(7,  "128-255");
2066b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(8,  "256-511");
2076b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(9,  "512-1023");
2086b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
2096b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
2106b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
2116b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
2126b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
2136b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
2146b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
2156b7bc061SMartin Sperl 
2166598b91bSDavid Jander SPI_STATISTICS_SHOW(transfers_split_maxsize);
217d9f12122SMartin Sperl 
218aa7da564SGreg Kroah-Hartman static struct attribute *spi_dev_attrs[] = {
219aa7da564SGreg Kroah-Hartman 	&dev_attr_modalias.attr,
2205039563eSTrent Piepho 	&dev_attr_driver_override.attr,
221aa7da564SGreg Kroah-Hartman 	NULL,
2228ae12a0dSDavid Brownell };
223eca2ebc7SMartin Sperl 
224eca2ebc7SMartin Sperl static const struct attribute_group spi_dev_group = {
225eca2ebc7SMartin Sperl 	.attrs  = spi_dev_attrs,
226eca2ebc7SMartin Sperl };
227eca2ebc7SMartin Sperl 
228eca2ebc7SMartin Sperl static struct attribute *spi_device_statistics_attrs[] = {
229eca2ebc7SMartin Sperl 	&dev_attr_spi_device_messages.attr,
230eca2ebc7SMartin Sperl 	&dev_attr_spi_device_transfers.attr,
231eca2ebc7SMartin Sperl 	&dev_attr_spi_device_errors.attr,
232eca2ebc7SMartin Sperl 	&dev_attr_spi_device_timedout.attr,
233eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync.attr,
234eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync_immediate.attr,
235eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_async.attr,
236eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes.attr,
237eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_rx.attr,
238eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_tx.attr,
2396b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo0.attr,
2406b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo1.attr,
2416b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo2.attr,
2426b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo3.attr,
2436b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo4.attr,
2446b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo5.attr,
2456b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo6.attr,
2466b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo7.attr,
2476b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo8.attr,
2486b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo9.attr,
2496b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo10.attr,
2506b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo11.attr,
2516b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo12.attr,
2526b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo13.attr,
2536b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo14.attr,
2546b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo15.attr,
2556b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo16.attr,
256d9f12122SMartin Sperl 	&dev_attr_spi_device_transfers_split_maxsize.attr,
257eca2ebc7SMartin Sperl 	NULL,
258eca2ebc7SMartin Sperl };
259eca2ebc7SMartin Sperl 
260eca2ebc7SMartin Sperl static const struct attribute_group spi_device_statistics_group = {
261eca2ebc7SMartin Sperl 	.name  = "statistics",
262eca2ebc7SMartin Sperl 	.attrs  = spi_device_statistics_attrs,
263eca2ebc7SMartin Sperl };
264eca2ebc7SMartin Sperl 
265eca2ebc7SMartin Sperl static const struct attribute_group *spi_dev_groups[] = {
266eca2ebc7SMartin Sperl 	&spi_dev_group,
267eca2ebc7SMartin Sperl 	&spi_device_statistics_group,
268eca2ebc7SMartin Sperl 	NULL,
269eca2ebc7SMartin Sperl };
270eca2ebc7SMartin Sperl 
2718caab75fSGeert Uytterhoeven static struct attribute *spi_controller_statistics_attrs[] = {
2728caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_messages.attr,
2738caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers.attr,
2748caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_errors.attr,
2758caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_timedout.attr,
2768caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync.attr,
2778caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync_immediate.attr,
2788caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_async.attr,
2798caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes.attr,
2808caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_rx.attr,
2818caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_tx.attr,
2828caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo0.attr,
2838caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo1.attr,
2848caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo2.attr,
2858caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo3.attr,
2868caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo4.attr,
2878caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo5.attr,
2888caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo6.attr,
2898caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo7.attr,
2908caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo8.attr,
2918caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo9.attr,
2928caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo10.attr,
2938caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo11.attr,
2948caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo12.attr,
2958caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo13.attr,
2968caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo14.attr,
2978caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo15.attr,
2988caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo16.attr,
2998caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers_split_maxsize.attr,
300eca2ebc7SMartin Sperl 	NULL,
301eca2ebc7SMartin Sperl };
302eca2ebc7SMartin Sperl 
3038caab75fSGeert Uytterhoeven static const struct attribute_group spi_controller_statistics_group = {
304eca2ebc7SMartin Sperl 	.name  = "statistics",
3058caab75fSGeert Uytterhoeven 	.attrs  = spi_controller_statistics_attrs,
306eca2ebc7SMartin Sperl };
307eca2ebc7SMartin Sperl 
308eca2ebc7SMartin Sperl static const struct attribute_group *spi_master_groups[] = {
3098caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
310eca2ebc7SMartin Sperl 	NULL,
311eca2ebc7SMartin Sperl };
312eca2ebc7SMartin Sperl 
spi_statistics_add_transfer_stats(struct spi_statistics __percpu * pcpu_stats,struct spi_transfer * xfer,struct spi_controller * ctlr)313d501cc4cSDavid Jander static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
314eca2ebc7SMartin Sperl 					      struct spi_transfer *xfer,
3158caab75fSGeert Uytterhoeven 					      struct spi_controller *ctlr)
316eca2ebc7SMartin Sperl {
3176b7bc061SMartin Sperl 	int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
31867b9d641SDavid Jander 	struct spi_statistics *stats;
3196b7bc061SMartin Sperl 
3206b7bc061SMartin Sperl 	if (l2len < 0)
3216b7bc061SMartin Sperl 		l2len = 0;
322eca2ebc7SMartin Sperl 
32367b9d641SDavid Jander 	get_cpu();
32467b9d641SDavid Jander 	stats = this_cpu_ptr(pcpu_stats);
3256598b91bSDavid Jander 	u64_stats_update_begin(&stats->syncp);
326eca2ebc7SMartin Sperl 
3276598b91bSDavid Jander 	u64_stats_inc(&stats->transfers);
3286598b91bSDavid Jander 	u64_stats_inc(&stats->transfer_bytes_histo[l2len]);
329eca2ebc7SMartin Sperl 
3306598b91bSDavid Jander 	u64_stats_add(&stats->bytes, xfer->len);
331eca2ebc7SMartin Sperl 	if ((xfer->tx_buf) &&
3328caab75fSGeert Uytterhoeven 	    (xfer->tx_buf != ctlr->dummy_tx))
3336598b91bSDavid Jander 		u64_stats_add(&stats->bytes_tx, xfer->len);
334eca2ebc7SMartin Sperl 	if ((xfer->rx_buf) &&
3358caab75fSGeert Uytterhoeven 	    (xfer->rx_buf != ctlr->dummy_rx))
3366598b91bSDavid Jander 		u64_stats_add(&stats->bytes_rx, xfer->len);
337eca2ebc7SMartin Sperl 
3386598b91bSDavid Jander 	u64_stats_update_end(&stats->syncp);
33967b9d641SDavid Jander 	put_cpu();
340eca2ebc7SMartin Sperl }
3418ae12a0dSDavid Brownell 
342350de7ceSAndy Shevchenko /*
343350de7ceSAndy Shevchenko  * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
3448ae12a0dSDavid Brownell  * and the sysfs version makes coldplug work too.
3458ae12a0dSDavid Brownell  */
spi_match_id(const struct spi_device_id * id,const char * name)3463f076575SAndy Shevchenko static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
34775368bf6SAnton Vorontsov {
34875368bf6SAnton Vorontsov 	while (id->name[0]) {
3493f076575SAndy Shevchenko 		if (!strcmp(name, id->name))
35075368bf6SAnton Vorontsov 			return id;
35175368bf6SAnton Vorontsov 		id++;
35275368bf6SAnton Vorontsov 	}
35375368bf6SAnton Vorontsov 	return NULL;
35475368bf6SAnton Vorontsov }
35575368bf6SAnton Vorontsov 
spi_get_device_id(const struct spi_device * sdev)35675368bf6SAnton Vorontsov const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
35775368bf6SAnton Vorontsov {
35875368bf6SAnton Vorontsov 	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
35975368bf6SAnton Vorontsov 
3603f076575SAndy Shevchenko 	return spi_match_id(sdrv->id_table, sdev->modalias);
36175368bf6SAnton Vorontsov }
36275368bf6SAnton Vorontsov EXPORT_SYMBOL_GPL(spi_get_device_id);
36375368bf6SAnton Vorontsov 
spi_get_device_match_data(const struct spi_device * sdev)364aea672d0SAndy Shevchenko const void *spi_get_device_match_data(const struct spi_device *sdev)
365aea672d0SAndy Shevchenko {
366aea672d0SAndy Shevchenko 	const void *match;
367aea672d0SAndy Shevchenko 
368aea672d0SAndy Shevchenko 	match = device_get_match_data(&sdev->dev);
369aea672d0SAndy Shevchenko 	if (match)
370aea672d0SAndy Shevchenko 		return match;
371aea672d0SAndy Shevchenko 
372aea672d0SAndy Shevchenko 	return (const void *)spi_get_device_id(sdev)->driver_data;
373aea672d0SAndy Shevchenko }
374aea672d0SAndy Shevchenko EXPORT_SYMBOL_GPL(spi_get_device_match_data);
375aea672d0SAndy Shevchenko 
spi_match_device(struct device * dev,struct device_driver * drv)3768ae12a0dSDavid Brownell static int spi_match_device(struct device *dev, struct device_driver *drv)
3778ae12a0dSDavid Brownell {
3788ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
37975368bf6SAnton Vorontsov 	const struct spi_driver	*sdrv = to_spi_driver(drv);
38075368bf6SAnton Vorontsov 
3815039563eSTrent Piepho 	/* Check override first, and if set, only use the named driver */
3825039563eSTrent Piepho 	if (spi->driver_override)
3835039563eSTrent Piepho 		return strcmp(spi->driver_override, drv->name) == 0;
3845039563eSTrent Piepho 
3852b7a32f7SSinan Akman 	/* Attempt an OF style match */
3862b7a32f7SSinan Akman 	if (of_driver_match_device(dev, drv))
3872b7a32f7SSinan Akman 		return 1;
3882b7a32f7SSinan Akman 
38964bee4d2SMika Westerberg 	/* Then try ACPI */
39064bee4d2SMika Westerberg 	if (acpi_driver_match_device(dev, drv))
39164bee4d2SMika Westerberg 		return 1;
39264bee4d2SMika Westerberg 
39375368bf6SAnton Vorontsov 	if (sdrv->id_table)
3943f076575SAndy Shevchenko 		return !!spi_match_id(sdrv->id_table, spi->modalias);
3958ae12a0dSDavid Brownell 
39635f74fcaSKay Sievers 	return strcmp(spi->modalias, drv->name) == 0;
3978ae12a0dSDavid Brownell }
3988ae12a0dSDavid Brownell 
spi_uevent(const struct device * dev,struct kobj_uevent_env * env)3992a81ada3SGreg Kroah-Hartman static int spi_uevent(const struct device *dev, struct kobj_uevent_env *env)
4008ae12a0dSDavid Brownell {
4018ae12a0dSDavid Brownell 	const struct spi_device		*spi = to_spi_device(dev);
4028c4ff6d0SZhang Rui 	int rc;
4038c4ff6d0SZhang Rui 
4048c4ff6d0SZhang Rui 	rc = acpi_device_uevent_modalias(dev, env);
4058c4ff6d0SZhang Rui 	if (rc != -ENODEV)
4068c4ff6d0SZhang Rui 		return rc;
4078ae12a0dSDavid Brownell 
4082856670fSAndy Shevchenko 	return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
4098ae12a0dSDavid Brownell }
4108ae12a0dSDavid Brownell 
spi_probe(struct device * dev)4119db34ee6SUwe Kleine-König static int spi_probe(struct device *dev)
412b885244eSDavid Brownell {
413b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
41444af7927SJon Hunter 	struct spi_device		*spi = to_spi_device(dev);
41533cf00e5SMika Westerberg 	int ret;
416b885244eSDavid Brownell 
41786be408bSSylwester Nawrocki 	ret = of_clk_set_defaults(dev->of_node, false);
41886be408bSSylwester Nawrocki 	if (ret)
41986be408bSSylwester Nawrocki 		return ret;
42086be408bSSylwester Nawrocki 
42144af7927SJon Hunter 	if (dev->of_node) {
42244af7927SJon Hunter 		spi->irq = of_irq_get(dev->of_node, 0);
42344af7927SJon Hunter 		if (spi->irq == -EPROBE_DEFER)
42444af7927SJon Hunter 			return -EPROBE_DEFER;
42544af7927SJon Hunter 		if (spi->irq < 0)
42644af7927SJon Hunter 			spi->irq = 0;
42744af7927SJon Hunter 	}
42844af7927SJon Hunter 
429*66f0fbc8SStanislaw Gruszka 	if (has_acpi_companion(dev) && spi->irq < 0) {
430*66f0fbc8SStanislaw Gruszka 		struct acpi_device *adev = to_acpi_device_node(dev->fwnode);
431*66f0fbc8SStanislaw Gruszka 
432*66f0fbc8SStanislaw Gruszka 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
433*66f0fbc8SStanislaw Gruszka 		if (spi->irq == -EPROBE_DEFER)
434*66f0fbc8SStanislaw Gruszka 			return -EPROBE_DEFER;
435*66f0fbc8SStanislaw Gruszka 		if (spi->irq < 0)
436*66f0fbc8SStanislaw Gruszka 			spi->irq = 0;
437*66f0fbc8SStanislaw Gruszka 	}
438*66f0fbc8SStanislaw Gruszka 
439676e7c25SUlf Hansson 	ret = dev_pm_domain_attach(dev, true);
44071f277a7SUlf Hansson 	if (ret)
44171f277a7SUlf Hansson 		return ret;
44271f277a7SUlf Hansson 
443440408dbSUwe Kleine-König 	if (sdrv->probe) {
44444af7927SJon Hunter 		ret = sdrv->probe(spi);
44533cf00e5SMika Westerberg 		if (ret)
446676e7c25SUlf Hansson 			dev_pm_domain_detach(dev, true);
447440408dbSUwe Kleine-König 	}
44833cf00e5SMika Westerberg 
44933cf00e5SMika Westerberg 	return ret;
450b885244eSDavid Brownell }
451b885244eSDavid Brownell 
spi_remove(struct device * dev)452fc7a6209SUwe Kleine-König static void spi_remove(struct device *dev)
453b885244eSDavid Brownell {
454b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
455b885244eSDavid Brownell 
456a0386bbaSUwe Kleine-König 	if (sdrv->remove)
457a0386bbaSUwe Kleine-König 		sdrv->remove(to_spi_device(dev));
4587795d475SUwe Kleine-König 
459676e7c25SUlf Hansson 	dev_pm_domain_detach(dev, true);
460b885244eSDavid Brownell }
461b885244eSDavid Brownell 
spi_shutdown(struct device * dev)4629db34ee6SUwe Kleine-König static void spi_shutdown(struct device *dev)
463b885244eSDavid Brownell {
464a6f483b2SMarek Szyprowski 	if (dev->driver) {
465b885244eSDavid Brownell 		const struct spi_driver	*sdrv = to_spi_driver(dev->driver);
466b885244eSDavid Brownell 
4679db34ee6SUwe Kleine-König 		if (sdrv->shutdown)
468b885244eSDavid Brownell 			sdrv->shutdown(to_spi_device(dev));
469b885244eSDavid Brownell 	}
470a6f483b2SMarek Szyprowski }
471b885244eSDavid Brownell 
4729db34ee6SUwe Kleine-König struct bus_type spi_bus_type = {
4739db34ee6SUwe Kleine-König 	.name		= "spi",
4749db34ee6SUwe Kleine-König 	.dev_groups	= spi_dev_groups,
4759db34ee6SUwe Kleine-König 	.match		= spi_match_device,
4769db34ee6SUwe Kleine-König 	.uevent		= spi_uevent,
4779db34ee6SUwe Kleine-König 	.probe		= spi_probe,
4789db34ee6SUwe Kleine-König 	.remove		= spi_remove,
4799db34ee6SUwe Kleine-König 	.shutdown	= spi_shutdown,
4809db34ee6SUwe Kleine-König };
4819db34ee6SUwe Kleine-König EXPORT_SYMBOL_GPL(spi_bus_type);
4829db34ee6SUwe Kleine-König 
48333e34dc6SDavid Brownell /**
484ca5d2485SAndrew F. Davis  * __spi_register_driver - register a SPI driver
48588c9321dSThierry Reding  * @owner: owner module of the driver to register
48633e34dc6SDavid Brownell  * @sdrv: the driver to register
48733e34dc6SDavid Brownell  * Context: can sleep
48897d56dc6SJavier Martinez Canillas  *
48997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
49033e34dc6SDavid Brownell  */
__spi_register_driver(struct module * owner,struct spi_driver * sdrv)491ca5d2485SAndrew F. Davis int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
492b885244eSDavid Brownell {
493ca5d2485SAndrew F. Davis 	sdrv->driver.owner = owner;
494b885244eSDavid Brownell 	sdrv->driver.bus = &spi_bus_type;
4955fa6863bSMark Brown 
4965fa6863bSMark Brown 	/*
4975fa6863bSMark Brown 	 * For Really Good Reasons we use spi: modaliases not of:
4985fa6863bSMark Brown 	 * modaliases for DT so module autoloading won't work if we
4995fa6863bSMark Brown 	 * don't have a spi_device_id as well as a compatible string.
5005fa6863bSMark Brown 	 */
5015fa6863bSMark Brown 	if (sdrv->driver.of_match_table) {
5025fa6863bSMark Brown 		const struct of_device_id *of_id;
5035fa6863bSMark Brown 
5045fa6863bSMark Brown 		for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
5055fa6863bSMark Brown 		     of_id++) {
5065fa6863bSMark Brown 			const char *of_name;
5075fa6863bSMark Brown 
5085fa6863bSMark Brown 			/* Strip off any vendor prefix */
5095fa6863bSMark Brown 			of_name = strnchr(of_id->compatible,
5105fa6863bSMark Brown 					  sizeof(of_id->compatible), ',');
5115fa6863bSMark Brown 			if (of_name)
5125fa6863bSMark Brown 				of_name++;
5135fa6863bSMark Brown 			else
5145fa6863bSMark Brown 				of_name = of_id->compatible;
5155fa6863bSMark Brown 
5165fa6863bSMark Brown 			if (sdrv->id_table) {
5175fa6863bSMark Brown 				const struct spi_device_id *spi_id;
5185fa6863bSMark Brown 
5193f076575SAndy Shevchenko 				spi_id = spi_match_id(sdrv->id_table, of_name);
520b79332efSAndy Shevchenko 				if (spi_id)
5215fa6863bSMark Brown 					continue;
5225fa6863bSMark Brown 			} else {
5235fa6863bSMark Brown 				if (strcmp(sdrv->driver.name, of_name) == 0)
5245fa6863bSMark Brown 					continue;
5255fa6863bSMark Brown 			}
5265fa6863bSMark Brown 
5275fa6863bSMark Brown 			pr_warn("SPI driver %s has no spi_device_id for %s\n",
5285fa6863bSMark Brown 				sdrv->driver.name, of_id->compatible);
5295fa6863bSMark Brown 		}
5305fa6863bSMark Brown 	}
5315fa6863bSMark Brown 
532b885244eSDavid Brownell 	return driver_register(&sdrv->driver);
533b885244eSDavid Brownell }
534ca5d2485SAndrew F. Davis EXPORT_SYMBOL_GPL(__spi_register_driver);
535b885244eSDavid Brownell 
5368ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
5378ae12a0dSDavid Brownell 
538350de7ceSAndy Shevchenko /*
539350de7ceSAndy Shevchenko  * SPI devices should normally not be created by SPI device drivers; that
5408caab75fSGeert Uytterhoeven  * would make them board-specific.  Similarly with SPI controller drivers.
5418ae12a0dSDavid Brownell  * Device registration normally goes into like arch/.../mach.../board-YYY.c
5428ae12a0dSDavid Brownell  * with other readonly (flashable) information about mainboard devices.
5438ae12a0dSDavid Brownell  */
5448ae12a0dSDavid Brownell 
5458ae12a0dSDavid Brownell struct boardinfo {
5468ae12a0dSDavid Brownell 	struct list_head	list;
5472b9603a0SFeng Tang 	struct spi_board_info	board_info;
5488ae12a0dSDavid Brownell };
5498ae12a0dSDavid Brownell 
5508ae12a0dSDavid Brownell static LIST_HEAD(board_list);
5518caab75fSGeert Uytterhoeven static LIST_HEAD(spi_controller_list);
5522b9603a0SFeng Tang 
5532b9603a0SFeng Tang /*
554be73e323SAndy Shevchenko  * Used to protect add/del operation for board_info list and
555350de7ceSAndy Shevchenko  * spi_controller list, and their matching process also used
556350de7ceSAndy Shevchenko  * to protect object of type struct idr.
5572b9603a0SFeng Tang  */
55894040828SMatthias Kaehlcke static DEFINE_MUTEX(board_lock);
5598ae12a0dSDavid Brownell 
560dc87c98eSGrant Likely /**
561dc87c98eSGrant Likely  * spi_alloc_device - Allocate a new SPI device
5628caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
563dc87c98eSGrant Likely  * Context: can sleep
564dc87c98eSGrant Likely  *
565dc87c98eSGrant Likely  * Allows a driver to allocate and initialize a spi_device without
566dc87c98eSGrant Likely  * registering it immediately.  This allows a driver to directly
567dc87c98eSGrant Likely  * fill the spi_device with device parameters before calling
568dc87c98eSGrant Likely  * spi_add_device() on it.
569dc87c98eSGrant Likely  *
570dc87c98eSGrant Likely  * Caller is responsible to call spi_add_device() on the returned
5718caab75fSGeert Uytterhoeven  * spi_device structure to add it to the SPI controller.  If the caller
572dc87c98eSGrant Likely  * needs to discard the spi_device without adding it, then it should
573dc87c98eSGrant Likely  * call spi_dev_put() on it.
574dc87c98eSGrant Likely  *
57597d56dc6SJavier Martinez Canillas  * Return: a pointer to the new device, or NULL.
576dc87c98eSGrant Likely  */
spi_alloc_device(struct spi_controller * ctlr)577e3dc1399SStefan Binding struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
578dc87c98eSGrant Likely {
579dc87c98eSGrant Likely 	struct spi_device	*spi;
580dc87c98eSGrant Likely 
5818caab75fSGeert Uytterhoeven 	if (!spi_controller_get(ctlr))
582dc87c98eSGrant Likely 		return NULL;
583dc87c98eSGrant Likely 
5845fe5f05eSJingoo Han 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
585dc87c98eSGrant Likely 	if (!spi) {
5868caab75fSGeert Uytterhoeven 		spi_controller_put(ctlr);
587dc87c98eSGrant Likely 		return NULL;
588dc87c98eSGrant Likely 	}
589dc87c98eSGrant Likely 
5906598b91bSDavid Jander 	spi->pcpu_statistics = spi_alloc_pcpu_stats(NULL);
5916598b91bSDavid Jander 	if (!spi->pcpu_statistics) {
5926598b91bSDavid Jander 		kfree(spi);
5936598b91bSDavid Jander 		spi_controller_put(ctlr);
5946598b91bSDavid Jander 		return NULL;
5956598b91bSDavid Jander 	}
5966598b91bSDavid Jander 
5978caab75fSGeert Uytterhoeven 	spi->master = spi->controller = ctlr;
5988caab75fSGeert Uytterhoeven 	spi->dev.parent = &ctlr->dev;
599dc87c98eSGrant Likely 	spi->dev.bus = &spi_bus_type;
600dc87c98eSGrant Likely 	spi->dev.release = spidev_release;
601ea235786SJohn Garry 	spi->mode = ctlr->buswidth_override_bits;
602eca2ebc7SMartin Sperl 
603dc87c98eSGrant Likely 	device_initialize(&spi->dev);
604dc87c98eSGrant Likely 	return spi;
605dc87c98eSGrant Likely }
606e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_alloc_device);
607dc87c98eSGrant Likely 
spi_dev_set_name(struct spi_device * spi)608e13ac47bSJarkko Nikula static void spi_dev_set_name(struct spi_device *spi)
609e13ac47bSJarkko Nikula {
610e13ac47bSJarkko Nikula 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
611e13ac47bSJarkko Nikula 
612e13ac47bSJarkko Nikula 	if (adev) {
613e13ac47bSJarkko Nikula 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
614e13ac47bSJarkko Nikula 		return;
615e13ac47bSJarkko Nikula 	}
616e13ac47bSJarkko Nikula 
6178caab75fSGeert Uytterhoeven 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
618303feb3cSAmit Kumar Mahapatra 		     spi_get_chipselect(spi, 0));
619e13ac47bSJarkko Nikula }
620e13ac47bSJarkko Nikula 
spi_dev_check(struct device * dev,void * data)621b6fb8d3aSMika Westerberg static int spi_dev_check(struct device *dev, void *data)
622b6fb8d3aSMika Westerberg {
623b6fb8d3aSMika Westerberg 	struct spi_device *spi = to_spi_device(dev);
624b6fb8d3aSMika Westerberg 	struct spi_device *new_spi = data;
625b6fb8d3aSMika Westerberg 
6268caab75fSGeert Uytterhoeven 	if (spi->controller == new_spi->controller &&
627303feb3cSAmit Kumar Mahapatra 	    spi_get_chipselect(spi, 0) == spi_get_chipselect(new_spi, 0))
628b6fb8d3aSMika Westerberg 		return -EBUSY;
629b6fb8d3aSMika Westerberg 	return 0;
630b6fb8d3aSMika Westerberg }
631b6fb8d3aSMika Westerberg 
spi_cleanup(struct spi_device * spi)632c7299feaSSaravana Kannan static void spi_cleanup(struct spi_device *spi)
633c7299feaSSaravana Kannan {
634c7299feaSSaravana Kannan 	if (spi->controller->cleanup)
635c7299feaSSaravana Kannan 		spi->controller->cleanup(spi);
636c7299feaSSaravana Kannan }
637c7299feaSSaravana Kannan 
__spi_add_device(struct spi_device * spi)6380c79378cSSebastian Reichel static int __spi_add_device(struct spi_device *spi)
6390c79378cSSebastian Reichel {
6400c79378cSSebastian Reichel 	struct spi_controller *ctlr = spi->controller;
6410c79378cSSebastian Reichel 	struct device *dev = ctlr->dev.parent;
6420c79378cSSebastian Reichel 	int status;
6430c79378cSSebastian Reichel 
64436124deaSAndy Shevchenko 	/* Chipselects are numbered 0..max; validate. */
64536124deaSAndy Shevchenko 	if (spi_get_chipselect(spi, 0) >= ctlr->num_chipselect) {
64636124deaSAndy Shevchenko 		dev_err(dev, "cs%d >= max %d\n", spi_get_chipselect(spi, 0),
64736124deaSAndy Shevchenko 			ctlr->num_chipselect);
64836124deaSAndy Shevchenko 		return -EINVAL;
64936124deaSAndy Shevchenko 	}
65036124deaSAndy Shevchenko 
65136124deaSAndy Shevchenko 	/* Set the bus ID string */
65236124deaSAndy Shevchenko 	spi_dev_set_name(spi);
65336124deaSAndy Shevchenko 
6546bfb15f3SUwe Kleine-König 	/*
6556bfb15f3SUwe Kleine-König 	 * We need to make sure there's no other device with this
6566bfb15f3SUwe Kleine-König 	 * chipselect **BEFORE** we call setup(), else we'll trash
6576bfb15f3SUwe Kleine-König 	 * its configuration.
6586bfb15f3SUwe Kleine-König 	 */
6590c79378cSSebastian Reichel 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
6600c79378cSSebastian Reichel 	if (status) {
6610c79378cSSebastian Reichel 		dev_err(dev, "chipselect %d already in use\n",
662303feb3cSAmit Kumar Mahapatra 				spi_get_chipselect(spi, 0));
6630c79378cSSebastian Reichel 		return status;
6640c79378cSSebastian Reichel 	}
6650c79378cSSebastian Reichel 
6660c79378cSSebastian Reichel 	/* Controller may unregister concurrently */
6670c79378cSSebastian Reichel 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
6680c79378cSSebastian Reichel 	    !device_is_registered(&ctlr->dev)) {
6690c79378cSSebastian Reichel 		return -ENODEV;
6700c79378cSSebastian Reichel 	}
6710c79378cSSebastian Reichel 
6720c79378cSSebastian Reichel 	if (ctlr->cs_gpiods)
673303feb3cSAmit Kumar Mahapatra 		spi_set_csgpiod(spi, 0, ctlr->cs_gpiods[spi_get_chipselect(spi, 0)]);
6740c79378cSSebastian Reichel 
675350de7ceSAndy Shevchenko 	/*
676350de7ceSAndy Shevchenko 	 * Drivers may modify this initial i/o setup, but will
6770c79378cSSebastian Reichel 	 * normally rely on the device being setup.  Devices
6780c79378cSSebastian Reichel 	 * using SPI_CS_HIGH can't coexist well otherwise...
6790c79378cSSebastian Reichel 	 */
6800c79378cSSebastian Reichel 	status = spi_setup(spi);
6810c79378cSSebastian Reichel 	if (status < 0) {
6820c79378cSSebastian Reichel 		dev_err(dev, "can't setup %s, status %d\n",
6830c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
6840c79378cSSebastian Reichel 		return status;
6850c79378cSSebastian Reichel 	}
6860c79378cSSebastian Reichel 
6870c79378cSSebastian Reichel 	/* Device may be bound to an active driver when this returns */
6880c79378cSSebastian Reichel 	status = device_add(&spi->dev);
6890c79378cSSebastian Reichel 	if (status < 0) {
6900c79378cSSebastian Reichel 		dev_err(dev, "can't add %s, status %d\n",
6910c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
6920c79378cSSebastian Reichel 		spi_cleanup(spi);
6930c79378cSSebastian Reichel 	} else {
6940c79378cSSebastian Reichel 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
6950c79378cSSebastian Reichel 	}
6960c79378cSSebastian Reichel 
6970c79378cSSebastian Reichel 	return status;
6980c79378cSSebastian Reichel }
6990c79378cSSebastian Reichel 
700dc87c98eSGrant Likely /**
701dc87c98eSGrant Likely  * spi_add_device - Add spi_device allocated with spi_alloc_device
702dc87c98eSGrant Likely  * @spi: spi_device to register
703dc87c98eSGrant Likely  *
704dc87c98eSGrant Likely  * Companion function to spi_alloc_device.  Devices allocated with
705702ca026SAndy Shevchenko  * spi_alloc_device can be added onto the SPI bus with this function.
706dc87c98eSGrant Likely  *
70797d56dc6SJavier Martinez Canillas  * Return: 0 on success; negative errno on failure
708dc87c98eSGrant Likely  */
spi_add_device(struct spi_device * spi)709e3dc1399SStefan Binding int spi_add_device(struct spi_device *spi)
710dc87c98eSGrant Likely {
7118caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
712dc87c98eSGrant Likely 	int status;
713dc87c98eSGrant Likely 
7146098475dSMark Brown 	mutex_lock(&ctlr->add_lock);
7150c79378cSSebastian Reichel 	status = __spi_add_device(spi);
7166098475dSMark Brown 	mutex_unlock(&ctlr->add_lock);
717e48880e0SDavid Brownell 	return status;
718dc87c98eSGrant Likely }
719e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_add_device);
7208ae12a0dSDavid Brownell 
72133e34dc6SDavid Brownell /**
72233e34dc6SDavid Brownell  * spi_new_device - instantiate one new SPI device
7238caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
72433e34dc6SDavid Brownell  * @chip: Describes the SPI device
72533e34dc6SDavid Brownell  * Context: can sleep
72633e34dc6SDavid Brownell  *
72733e34dc6SDavid Brownell  * On typical mainboards, this is purely internal; and it's not needed
7288ae12a0dSDavid Brownell  * after board init creates the hard-wired devices.  Some development
7298ae12a0dSDavid Brownell  * platforms may not be able to use spi_register_board_info though, and
7308ae12a0dSDavid Brownell  * this is exported so that for example a USB or parport based adapter
7318ae12a0dSDavid Brownell  * driver could add devices (which it would learn about out-of-band).
732082c8cb4SDavid Brownell  *
73397d56dc6SJavier Martinez Canillas  * Return: the new device, or NULL.
7348ae12a0dSDavid Brownell  */
spi_new_device(struct spi_controller * ctlr,struct spi_board_info * chip)7358caab75fSGeert Uytterhoeven struct spi_device *spi_new_device(struct spi_controller *ctlr,
736e9d5a461SAdrian Bunk 				  struct spi_board_info *chip)
7378ae12a0dSDavid Brownell {
7388ae12a0dSDavid Brownell 	struct spi_device	*proxy;
7398ae12a0dSDavid Brownell 	int			status;
7408ae12a0dSDavid Brownell 
741350de7ceSAndy Shevchenko 	/*
742350de7ceSAndy Shevchenko 	 * NOTE:  caller did any chip->bus_num checks necessary.
743082c8cb4SDavid Brownell 	 *
744082c8cb4SDavid Brownell 	 * Also, unless we change the return value convention to use
745082c8cb4SDavid Brownell 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
746082c8cb4SDavid Brownell 	 * suggests syslogged diagnostics are best here (ugh).
747082c8cb4SDavid Brownell 	 */
748082c8cb4SDavid Brownell 
7498caab75fSGeert Uytterhoeven 	proxy = spi_alloc_device(ctlr);
750dc87c98eSGrant Likely 	if (!proxy)
7518ae12a0dSDavid Brownell 		return NULL;
7528ae12a0dSDavid Brownell 
753102eb975SGrant Likely 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
754102eb975SGrant Likely 
755303feb3cSAmit Kumar Mahapatra 	spi_set_chipselect(proxy, 0, chip->chip_select);
7568ae12a0dSDavid Brownell 	proxy->max_speed_hz = chip->max_speed_hz;
757980a01c9SDavid Brownell 	proxy->mode = chip->mode;
7588ae12a0dSDavid Brownell 	proxy->irq = chip->irq;
75951e99de5SWolfram Sang 	strscpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
7608ae12a0dSDavid Brownell 	proxy->dev.platform_data = (void *) chip->platform_data;
7618ae12a0dSDavid Brownell 	proxy->controller_data = chip->controller_data;
7628ae12a0dSDavid Brownell 	proxy->controller_state = NULL;
7638ae12a0dSDavid Brownell 
76447afc77bSHeikki Krogerus 	if (chip->swnode) {
76547afc77bSHeikki Krogerus 		status = device_add_software_node(&proxy->dev, chip->swnode);
766826cf175SDmitry Torokhov 		if (status) {
7679d902c2aSColin Ian King 			dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
768826cf175SDmitry Torokhov 				chip->modalias, status);
769826cf175SDmitry Torokhov 			goto err_dev_put;
770826cf175SDmitry Torokhov 		}
7718ae12a0dSDavid Brownell 	}
772dc87c98eSGrant Likely 
773826cf175SDmitry Torokhov 	status = spi_add_device(proxy);
774826cf175SDmitry Torokhov 	if (status < 0)
775df41a5daSHeikki Krogerus 		goto err_dev_put;
776826cf175SDmitry Torokhov 
777dc87c98eSGrant Likely 	return proxy;
778826cf175SDmitry Torokhov 
779826cf175SDmitry Torokhov err_dev_put:
780df41a5daSHeikki Krogerus 	device_remove_software_node(&proxy->dev);
781826cf175SDmitry Torokhov 	spi_dev_put(proxy);
782826cf175SDmitry Torokhov 	return NULL;
783dc87c98eSGrant Likely }
7848ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_new_device);
7858ae12a0dSDavid Brownell 
7863b1884c2SGeert Uytterhoeven /**
7873b1884c2SGeert Uytterhoeven  * spi_unregister_device - unregister a single SPI device
7883b1884c2SGeert Uytterhoeven  * @spi: spi_device to unregister
7893b1884c2SGeert Uytterhoeven  *
7903b1884c2SGeert Uytterhoeven  * Start making the passed SPI device vanish. Normally this would be handled
7918caab75fSGeert Uytterhoeven  * by spi_unregister_controller().
7923b1884c2SGeert Uytterhoeven  */
spi_unregister_device(struct spi_device * spi)7933b1884c2SGeert Uytterhoeven void spi_unregister_device(struct spi_device *spi)
7943b1884c2SGeert Uytterhoeven {
795bd6c1644SGeert Uytterhoeven 	if (!spi)
796bd6c1644SGeert Uytterhoeven 		return;
797bd6c1644SGeert Uytterhoeven 
7988324147fSJohan Hovold 	if (spi->dev.of_node) {
799bd6c1644SGeert Uytterhoeven 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
8008324147fSJohan Hovold 		of_node_put(spi->dev.of_node);
8018324147fSJohan Hovold 	}
8027f24467fSOctavian Purdila 	if (ACPI_COMPANION(&spi->dev))
8037f24467fSOctavian Purdila 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
80447afc77bSHeikki Krogerus 	device_remove_software_node(&spi->dev);
80527e7db56SSaravana Kannan 	device_del(&spi->dev);
80627e7db56SSaravana Kannan 	spi_cleanup(spi);
80727e7db56SSaravana Kannan 	put_device(&spi->dev);
8083b1884c2SGeert Uytterhoeven }
8093b1884c2SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_device);
8103b1884c2SGeert Uytterhoeven 
spi_match_controller_to_boardinfo(struct spi_controller * ctlr,struct spi_board_info * bi)8118caab75fSGeert Uytterhoeven static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
8122b9603a0SFeng Tang 					      struct spi_board_info *bi)
8132b9603a0SFeng Tang {
8142b9603a0SFeng Tang 	struct spi_device *dev;
8152b9603a0SFeng Tang 
8168caab75fSGeert Uytterhoeven 	if (ctlr->bus_num != bi->bus_num)
8172b9603a0SFeng Tang 		return;
8182b9603a0SFeng Tang 
8198caab75fSGeert Uytterhoeven 	dev = spi_new_device(ctlr, bi);
8202b9603a0SFeng Tang 	if (!dev)
8218caab75fSGeert Uytterhoeven 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
8222b9603a0SFeng Tang 			bi->modalias);
8232b9603a0SFeng Tang }
8242b9603a0SFeng Tang 
82533e34dc6SDavid Brownell /**
82633e34dc6SDavid Brownell  * spi_register_board_info - register SPI devices for a given board
82733e34dc6SDavid Brownell  * @info: array of chip descriptors
82833e34dc6SDavid Brownell  * @n: how many descriptors are provided
82933e34dc6SDavid Brownell  * Context: can sleep
83033e34dc6SDavid Brownell  *
8318ae12a0dSDavid Brownell  * Board-specific early init code calls this (probably during arch_initcall)
8328ae12a0dSDavid Brownell  * with segments of the SPI device table.  Any device nodes are created later,
8338ae12a0dSDavid Brownell  * after the relevant parent SPI controller (bus_num) is defined.  We keep
8348ae12a0dSDavid Brownell  * this table of devices forever, so that reloading a controller driver will
8358ae12a0dSDavid Brownell  * not make Linux forget about these hard-wired devices.
8368ae12a0dSDavid Brownell  *
8378ae12a0dSDavid Brownell  * Other code can also call this, e.g. a particular add-on board might provide
8388ae12a0dSDavid Brownell  * SPI devices through its expansion connector, so code initializing that board
8398ae12a0dSDavid Brownell  * would naturally declare its SPI devices.
8408ae12a0dSDavid Brownell  *
8418ae12a0dSDavid Brownell  * The board info passed can safely be __initdata ... but be careful of
8428ae12a0dSDavid Brownell  * any embedded pointers (platform_data, etc), they're copied as-is.
84397d56dc6SJavier Martinez Canillas  *
84497d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
8458ae12a0dSDavid Brownell  */
spi_register_board_info(struct spi_board_info const * info,unsigned n)846fd4a319bSGrant Likely int spi_register_board_info(struct spi_board_info const *info, unsigned n)
8478ae12a0dSDavid Brownell {
8488ae12a0dSDavid Brownell 	struct boardinfo *bi;
8492b9603a0SFeng Tang 	int i;
8508ae12a0dSDavid Brownell 
851c7908a37SXiubo Li 	if (!n)
852f974cf57SDmitry Torokhov 		return 0;
853c7908a37SXiubo Li 
854f9bdb7fdSMarkus Elfring 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
8558ae12a0dSDavid Brownell 	if (!bi)
8568ae12a0dSDavid Brownell 		return -ENOMEM;
8578ae12a0dSDavid Brownell 
8582b9603a0SFeng Tang 	for (i = 0; i < n; i++, bi++, info++) {
8598caab75fSGeert Uytterhoeven 		struct spi_controller *ctlr;
8602b9603a0SFeng Tang 
8612b9603a0SFeng Tang 		memcpy(&bi->board_info, info, sizeof(*info));
862826cf175SDmitry Torokhov 
86394040828SMatthias Kaehlcke 		mutex_lock(&board_lock);
8648ae12a0dSDavid Brownell 		list_add_tail(&bi->list, &board_list);
8658caab75fSGeert Uytterhoeven 		list_for_each_entry(ctlr, &spi_controller_list, list)
8668caab75fSGeert Uytterhoeven 			spi_match_controller_to_boardinfo(ctlr,
8678caab75fSGeert Uytterhoeven 							  &bi->board_info);
86894040828SMatthias Kaehlcke 		mutex_unlock(&board_lock);
8692b9603a0SFeng Tang 	}
8702b9603a0SFeng Tang 
8718ae12a0dSDavid Brownell 	return 0;
8728ae12a0dSDavid Brownell }
8738ae12a0dSDavid Brownell 
8748ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
8758ae12a0dSDavid Brownell 
876fb51601bSUwe Kleine-König /* Core methods for SPI resource management */
877fb51601bSUwe Kleine-König 
878fb51601bSUwe Kleine-König /**
879fb51601bSUwe Kleine-König  * spi_res_alloc - allocate a spi resource that is life-cycle managed
880fb51601bSUwe Kleine-König  *                 during the processing of a spi_message while using
881fb51601bSUwe Kleine-König  *                 spi_transfer_one
882702ca026SAndy Shevchenko  * @spi:     the SPI device for which we allocate memory
883fb51601bSUwe Kleine-König  * @release: the release code to execute for this resource
884fb51601bSUwe Kleine-König  * @size:    size to alloc and return
885fb51601bSUwe Kleine-König  * @gfp:     GFP allocation flags
886fb51601bSUwe Kleine-König  *
887fb51601bSUwe Kleine-König  * Return: the pointer to the allocated data
888fb51601bSUwe Kleine-König  *
889fb51601bSUwe Kleine-König  * This may get enhanced in the future to allocate from a memory pool
890fb51601bSUwe Kleine-König  * of the @spi_device or @spi_controller to avoid repeated allocations.
891fb51601bSUwe Kleine-König  */
spi_res_alloc(struct spi_device * spi,spi_res_release_t release,size_t size,gfp_t gfp)892da21fde0SUwe Kleine-König static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
893fb51601bSUwe Kleine-König 			   size_t size, gfp_t gfp)
894fb51601bSUwe Kleine-König {
895fb51601bSUwe Kleine-König 	struct spi_res *sres;
896fb51601bSUwe Kleine-König 
897fb51601bSUwe Kleine-König 	sres = kzalloc(sizeof(*sres) + size, gfp);
898fb51601bSUwe Kleine-König 	if (!sres)
899fb51601bSUwe Kleine-König 		return NULL;
900fb51601bSUwe Kleine-König 
901fb51601bSUwe Kleine-König 	INIT_LIST_HEAD(&sres->entry);
902fb51601bSUwe Kleine-König 	sres->release = release;
903fb51601bSUwe Kleine-König 
904fb51601bSUwe Kleine-König 	return sres->data;
905fb51601bSUwe Kleine-König }
906fb51601bSUwe Kleine-König 
907fb51601bSUwe Kleine-König /**
908702ca026SAndy Shevchenko  * spi_res_free - free an SPI resource
909fb51601bSUwe Kleine-König  * @res: pointer to the custom data of a resource
910fb51601bSUwe Kleine-König  */
spi_res_free(void * res)911da21fde0SUwe Kleine-König static void spi_res_free(void *res)
912fb51601bSUwe Kleine-König {
913fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
914fb51601bSUwe Kleine-König 
915fb51601bSUwe Kleine-König 	if (!res)
916fb51601bSUwe Kleine-König 		return;
917fb51601bSUwe Kleine-König 
918fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
919fb51601bSUwe Kleine-König 	kfree(sres);
920fb51601bSUwe Kleine-König }
921fb51601bSUwe Kleine-König 
922fb51601bSUwe Kleine-König /**
923fb51601bSUwe Kleine-König  * spi_res_add - add a spi_res to the spi_message
924702ca026SAndy Shevchenko  * @message: the SPI message
925fb51601bSUwe Kleine-König  * @res:     the spi_resource
926fb51601bSUwe Kleine-König  */
spi_res_add(struct spi_message * message,void * res)927da21fde0SUwe Kleine-König static void spi_res_add(struct spi_message *message, void *res)
928fb51601bSUwe Kleine-König {
929fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
930fb51601bSUwe Kleine-König 
931fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
932fb51601bSUwe Kleine-König 	list_add_tail(&sres->entry, &message->resources);
933fb51601bSUwe Kleine-König }
934fb51601bSUwe Kleine-König 
935fb51601bSUwe Kleine-König /**
936702ca026SAndy Shevchenko  * spi_res_release - release all SPI resources for this message
937fb51601bSUwe Kleine-König  * @ctlr:  the @spi_controller
938fb51601bSUwe Kleine-König  * @message: the @spi_message
939fb51601bSUwe Kleine-König  */
spi_res_release(struct spi_controller * ctlr,struct spi_message * message)940da21fde0SUwe Kleine-König static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
941fb51601bSUwe Kleine-König {
942fb51601bSUwe Kleine-König 	struct spi_res *res, *tmp;
943fb51601bSUwe Kleine-König 
944fb51601bSUwe Kleine-König 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
945fb51601bSUwe Kleine-König 		if (res->release)
946fb51601bSUwe Kleine-König 			res->release(ctlr, message, res->data);
947fb51601bSUwe Kleine-König 
948fb51601bSUwe Kleine-König 		list_del(&res->entry);
949fb51601bSUwe Kleine-König 
950fb51601bSUwe Kleine-König 		kfree(res);
951fb51601bSUwe Kleine-König 	}
952fb51601bSUwe Kleine-König }
953fb51601bSUwe Kleine-König 
954fb51601bSUwe Kleine-König /*-------------------------------------------------------------------------*/
955fb51601bSUwe Kleine-König 
spi_set_cs(struct spi_device * spi,bool enable,bool force)956d347b4aaSDavid Bauer static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
957b158935fSMark Brown {
95886527bcbSAndy Shevchenko 	bool activate = enable;
95925093bdeSAlexandru Ardelean 
960d40f0b6fSDouglas Anderson 	/*
961d40f0b6fSDouglas Anderson 	 * Avoid calling into the driver (or doing delays) if the chip select
962d40f0b6fSDouglas Anderson 	 * isn't actually changing from the last time this was called.
963d40f0b6fSDouglas Anderson 	 */
964303feb3cSAmit Kumar Mahapatra 	if (!force && ((enable && spi->controller->last_cs == spi_get_chipselect(spi, 0)) ||
965303feb3cSAmit Kumar Mahapatra 		       (!enable && spi->controller->last_cs != spi_get_chipselect(spi, 0))) &&
966d40f0b6fSDouglas Anderson 	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
967d40f0b6fSDouglas Anderson 		return;
968d40f0b6fSDouglas Anderson 
9695cb4e1f3SAndy Shevchenko 	trace_spi_set_cs(spi, activate);
9705cb4e1f3SAndy Shevchenko 
971303feb3cSAmit Kumar Mahapatra 	spi->controller->last_cs = enable ? spi_get_chipselect(spi, 0) : -1;
972d40f0b6fSDouglas Anderson 	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
973d40f0b6fSDouglas Anderson 
974303feb3cSAmit Kumar Mahapatra 	if ((spi_get_csgpiod(spi, 0) || !spi->controller->set_cs_timing) && !activate)
9758c33ebfeSMason Zhang 		spi_delay_exec(&spi->cs_hold, NULL);
97625093bdeSAlexandru Ardelean 
977b158935fSMark Brown 	if (spi->mode & SPI_CS_HIGH)
978b158935fSMark Brown 		enable = !enable;
979b158935fSMark Brown 
980303feb3cSAmit Kumar Mahapatra 	if (spi_get_csgpiod(spi, 0)) {
981f48dc6b9SLinus Walleij 		if (!(spi->mode & SPI_NO_CS)) {
9826b695469SAndy Shevchenko 			/*
9836b695469SAndy Shevchenko 			 * Historically ACPI has no means of the GPIO polarity and
9846b695469SAndy Shevchenko 			 * thus the SPISerialBus() resource defines it on the per-chip
9856b695469SAndy Shevchenko 			 * basis. In order to avoid a chain of negations, the GPIO
9866b695469SAndy Shevchenko 			 * polarity is considered being Active High. Even for the cases
9876b695469SAndy Shevchenko 			 * when _DSD() is involved (in the updated versions of ACPI)
9886b695469SAndy Shevchenko 			 * the GPIO CS polarity must be defined Active High to avoid
9896b695469SAndy Shevchenko 			 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
9906b695469SAndy Shevchenko 			 * into account.
9916b695469SAndy Shevchenko 			 */
9926b695469SAndy Shevchenko 			if (has_acpi_companion(&spi->dev))
993303feb3cSAmit Kumar Mahapatra 				gpiod_set_value_cansleep(spi_get_csgpiod(spi, 0), !enable);
994f3186dd8SLinus Walleij 			else
9956b695469SAndy Shevchenko 				/* Polarity handled by GPIO library */
996303feb3cSAmit Kumar Mahapatra 				gpiod_set_value_cansleep(spi_get_csgpiod(spi, 0), activate);
9976b695469SAndy Shevchenko 		}
9988eee6b9dSThor Thayer 		/* Some SPI masters need both GPIO CS & slave_select */
99982238d2cSAndy Shevchenko 		if ((spi->controller->flags & SPI_CONTROLLER_GPIO_SS) &&
10008caab75fSGeert Uytterhoeven 		    spi->controller->set_cs)
10018caab75fSGeert Uytterhoeven 			spi->controller->set_cs(spi, !enable);
10028caab75fSGeert Uytterhoeven 	} else if (spi->controller->set_cs) {
10038caab75fSGeert Uytterhoeven 		spi->controller->set_cs(spi, !enable);
10048eee6b9dSThor Thayer 	}
100525093bdeSAlexandru Ardelean 
1006303feb3cSAmit Kumar Mahapatra 	if (spi_get_csgpiod(spi, 0) || !spi->controller->set_cs_timing) {
100795c07247SHector Martin 		if (activate)
100895c07247SHector Martin 			spi_delay_exec(&spi->cs_setup, NULL);
100995c07247SHector Martin 		else
10108c33ebfeSMason Zhang 			spi_delay_exec(&spi->cs_inactive, NULL);
101125093bdeSAlexandru Ardelean 	}
1012b158935fSMark Brown }
1013b158935fSMark Brown 
10142de440f5SGeert Uytterhoeven #ifdef CONFIG_HAS_DMA
spi_map_buf_attrs(struct spi_controller * ctlr,struct device * dev,struct sg_table * sgt,void * buf,size_t len,enum dma_data_direction dir,unsigned long attrs)10150c17ba73SVincent Whitchurch static int spi_map_buf_attrs(struct spi_controller *ctlr, struct device *dev,
10166ad45a27SMark Brown 			     struct sg_table *sgt, void *buf, size_t len,
10170c17ba73SVincent Whitchurch 			     enum dma_data_direction dir, unsigned long attrs)
10186ad45a27SMark Brown {
10196ad45a27SMark Brown 	const bool vmalloced_buf = is_vmalloc_addr(buf);
1020df88e91bSAndy Shevchenko 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
1021b1b8153cSVignesh R #ifdef CONFIG_HIGHMEM
1022b1b8153cSVignesh R 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
1023b1b8153cSVignesh R 				(unsigned long)buf < (PKMAP_BASE +
1024b1b8153cSVignesh R 					(LAST_PKMAP * PAGE_SIZE)));
1025b1b8153cSVignesh R #else
1026b1b8153cSVignesh R 	const bool kmap_buf = false;
1027b1b8153cSVignesh R #endif
102865598c13SAndrew Gabbasov 	int desc_len;
102965598c13SAndrew Gabbasov 	int sgs;
10306ad45a27SMark Brown 	struct page *vm_page;
10318dd4a016SJuan Gutierrez 	struct scatterlist *sg;
10326ad45a27SMark Brown 	void *sg_buf;
10336ad45a27SMark Brown 	size_t min;
10346ad45a27SMark Brown 	int i, ret;
10356ad45a27SMark Brown 
1036b1b8153cSVignesh R 	if (vmalloced_buf || kmap_buf) {
1037ebc4cb43SBiju Das 		desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
103865598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
10390569a88fSVignesh R 	} else if (virt_addr_valid(buf)) {
1040ebc4cb43SBiju Das 		desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
104165598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len, desc_len);
10420569a88fSVignesh R 	} else {
10430569a88fSVignesh R 		return -EINVAL;
104465598c13SAndrew Gabbasov 	}
104565598c13SAndrew Gabbasov 
10466ad45a27SMark Brown 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
10476ad45a27SMark Brown 	if (ret != 0)
10486ad45a27SMark Brown 		return ret;
10496ad45a27SMark Brown 
10508dd4a016SJuan Gutierrez 	sg = &sgt->sgl[0];
10516ad45a27SMark Brown 	for (i = 0; i < sgs; i++) {
10526ad45a27SMark Brown 
1053b1b8153cSVignesh R 		if (vmalloced_buf || kmap_buf) {
1054ce99319aSMaxime Chevallier 			/*
1055ce99319aSMaxime Chevallier 			 * Next scatterlist entry size is the minimum between
1056ce99319aSMaxime Chevallier 			 * the desc_len and the remaining buffer length that
1057ce99319aSMaxime Chevallier 			 * fits in a page.
1058ce99319aSMaxime Chevallier 			 */
1059ce99319aSMaxime Chevallier 			min = min_t(size_t, desc_len,
1060ce99319aSMaxime Chevallier 				    min_t(size_t, len,
1061ce99319aSMaxime Chevallier 					  PAGE_SIZE - offset_in_page(buf)));
1062b1b8153cSVignesh R 			if (vmalloced_buf)
10636ad45a27SMark Brown 				vm_page = vmalloc_to_page(buf);
1064b1b8153cSVignesh R 			else
1065b1b8153cSVignesh R 				vm_page = kmap_to_page(buf);
10666ad45a27SMark Brown 			if (!vm_page) {
10676ad45a27SMark Brown 				sg_free_table(sgt);
10686ad45a27SMark Brown 				return -ENOMEM;
10696ad45a27SMark Brown 			}
10708dd4a016SJuan Gutierrez 			sg_set_page(sg, vm_page,
1071c1aefbddSCharles Keepax 				    min, offset_in_page(buf));
10726ad45a27SMark Brown 		} else {
107365598c13SAndrew Gabbasov 			min = min_t(size_t, len, desc_len);
10746ad45a27SMark Brown 			sg_buf = buf;
10758dd4a016SJuan Gutierrez 			sg_set_buf(sg, sg_buf, min);
10766ad45a27SMark Brown 		}
10776ad45a27SMark Brown 
10786ad45a27SMark Brown 		buf += min;
10796ad45a27SMark Brown 		len -= min;
10808dd4a016SJuan Gutierrez 		sg = sg_next(sg);
10816ad45a27SMark Brown 	}
10826ad45a27SMark Brown 
10830c17ba73SVincent Whitchurch 	ret = dma_map_sgtable(dev, sgt, dir, attrs);
10846ad45a27SMark Brown 	if (ret < 0) {
10856ad45a27SMark Brown 		sg_free_table(sgt);
10866ad45a27SMark Brown 		return ret;
10876ad45a27SMark Brown 	}
10886ad45a27SMark Brown 
10896ad45a27SMark Brown 	return 0;
10906ad45a27SMark Brown }
10916ad45a27SMark Brown 
spi_map_buf(struct spi_controller * ctlr,struct device * dev,struct sg_table * sgt,void * buf,size_t len,enum dma_data_direction dir)10920c17ba73SVincent Whitchurch int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
10930c17ba73SVincent Whitchurch 		struct sg_table *sgt, void *buf, size_t len,
10940c17ba73SVincent Whitchurch 		enum dma_data_direction dir)
10950c17ba73SVincent Whitchurch {
10960c17ba73SVincent Whitchurch 	return spi_map_buf_attrs(ctlr, dev, sgt, buf, len, dir, 0);
10970c17ba73SVincent Whitchurch }
10980c17ba73SVincent Whitchurch 
spi_unmap_buf_attrs(struct spi_controller * ctlr,struct device * dev,struct sg_table * sgt,enum dma_data_direction dir,unsigned long attrs)10990c17ba73SVincent Whitchurch static void spi_unmap_buf_attrs(struct spi_controller *ctlr,
11000c17ba73SVincent Whitchurch 				struct device *dev, struct sg_table *sgt,
11010c17ba73SVincent Whitchurch 				enum dma_data_direction dir,
11020c17ba73SVincent Whitchurch 				unsigned long attrs)
11030c17ba73SVincent Whitchurch {
11040c17ba73SVincent Whitchurch 	if (sgt->orig_nents) {
11050c17ba73SVincent Whitchurch 		dma_unmap_sgtable(dev, sgt, dir, attrs);
11060c17ba73SVincent Whitchurch 		sg_free_table(sgt);
11078e9204cdSMarek Szyprowski 		sgt->orig_nents = 0;
11088e9204cdSMarek Szyprowski 		sgt->nents = 0;
11090c17ba73SVincent Whitchurch 	}
11100c17ba73SVincent Whitchurch }
11110c17ba73SVincent Whitchurch 
spi_unmap_buf(struct spi_controller * ctlr,struct device * dev,struct sg_table * sgt,enum dma_data_direction dir)111246336966SBoris Brezillon void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
11136ad45a27SMark Brown 		   struct sg_table *sgt, enum dma_data_direction dir)
11146ad45a27SMark Brown {
11150c17ba73SVincent Whitchurch 	spi_unmap_buf_attrs(ctlr, dev, sgt, dir, 0);
11166ad45a27SMark Brown }
11176ad45a27SMark Brown 
__spi_map_msg(struct spi_controller * ctlr,struct spi_message * msg)11188caab75fSGeert Uytterhoeven static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
111999adef31SMark Brown {
112099adef31SMark Brown 	struct device *tx_dev, *rx_dev;
112199adef31SMark Brown 	struct spi_transfer *xfer;
11226ad45a27SMark Brown 	int ret;
11233a2eba9bSMark Brown 
11248caab75fSGeert Uytterhoeven 	if (!ctlr->can_dma)
112599adef31SMark Brown 		return 0;
112699adef31SMark Brown 
11278caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
11288caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
1129b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1130b470e10eSVinod Koul 		tx_dev = ctlr->dma_map_dev;
1131c37f45b5SLeilk Liu 	else
11328caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
1133c37f45b5SLeilk Liu 
11348caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
11358caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
1136b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1137b470e10eSVinod Koul 		rx_dev = ctlr->dma_map_dev;
1138c37f45b5SLeilk Liu 	else
11398caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
114099adef31SMark Brown 
11411b5234b2SAndy Shevchenko 	ret = -ENOMSG;
114299adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11430c17ba73SVincent Whitchurch 		/* The sync is done before each transfer. */
11440c17ba73SVincent Whitchurch 		unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
11450c17ba73SVincent Whitchurch 
11468caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
114799adef31SMark Brown 			continue;
114899adef31SMark Brown 
114999adef31SMark Brown 		if (xfer->tx_buf != NULL) {
11500c17ba73SVincent Whitchurch 			ret = spi_map_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
11510c17ba73SVincent Whitchurch 						(void *)xfer->tx_buf,
11520c17ba73SVincent Whitchurch 						xfer->len, DMA_TO_DEVICE,
11530c17ba73SVincent Whitchurch 						attrs);
11546ad45a27SMark Brown 			if (ret != 0)
11556ad45a27SMark Brown 				return ret;
115699adef31SMark Brown 		}
115799adef31SMark Brown 
115899adef31SMark Brown 		if (xfer->rx_buf != NULL) {
11590c17ba73SVincent Whitchurch 			ret = spi_map_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
116099adef31SMark Brown 						xfer->rx_buf, xfer->len,
11610c17ba73SVincent Whitchurch 						DMA_FROM_DEVICE, attrs);
11626ad45a27SMark Brown 			if (ret != 0) {
11630c17ba73SVincent Whitchurch 				spi_unmap_buf_attrs(ctlr, tx_dev,
11640c17ba73SVincent Whitchurch 						&xfer->tx_sg, DMA_TO_DEVICE,
11650c17ba73SVincent Whitchurch 						attrs);
11660c17ba73SVincent Whitchurch 
11676ad45a27SMark Brown 				return ret;
116899adef31SMark Brown 			}
116999adef31SMark Brown 		}
117099adef31SMark Brown 	}
11711b5234b2SAndy Shevchenko 	/* No transfer has been mapped, bail out with success */
11721b5234b2SAndy Shevchenko 	if (ret)
11731b5234b2SAndy Shevchenko 		return 0;
117499adef31SMark Brown 
1175f25723dcSVincent Whitchurch 	ctlr->cur_rx_dma_dev = rx_dev;
1176f25723dcSVincent Whitchurch 	ctlr->cur_tx_dma_dev = tx_dev;
11778caab75fSGeert Uytterhoeven 	ctlr->cur_msg_mapped = true;
117899adef31SMark Brown 
117999adef31SMark Brown 	return 0;
118099adef31SMark Brown }
118199adef31SMark Brown 
__spi_unmap_msg(struct spi_controller * ctlr,struct spi_message * msg)11828caab75fSGeert Uytterhoeven static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
118399adef31SMark Brown {
1184f25723dcSVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
1185f25723dcSVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
118699adef31SMark Brown 	struct spi_transfer *xfer;
118799adef31SMark Brown 
11888caab75fSGeert Uytterhoeven 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
118999adef31SMark Brown 		return 0;
119099adef31SMark Brown 
119199adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
11920c17ba73SVincent Whitchurch 		/* The sync has already been done after each transfer. */
11930c17ba73SVincent Whitchurch 		unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
11940c17ba73SVincent Whitchurch 
11958caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
119699adef31SMark Brown 			continue;
119799adef31SMark Brown 
11980c17ba73SVincent Whitchurch 		spi_unmap_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
11990c17ba73SVincent Whitchurch 				    DMA_FROM_DEVICE, attrs);
12000c17ba73SVincent Whitchurch 		spi_unmap_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
12010c17ba73SVincent Whitchurch 				    DMA_TO_DEVICE, attrs);
120299adef31SMark Brown 	}
120399adef31SMark Brown 
1204809b1b04SRobin Gong 	ctlr->cur_msg_mapped = false;
1205809b1b04SRobin Gong 
120699adef31SMark Brown 	return 0;
120799adef31SMark Brown }
12080c17ba73SVincent Whitchurch 
spi_dma_sync_for_device(struct spi_controller * ctlr,struct spi_transfer * xfer)12090c17ba73SVincent Whitchurch static void spi_dma_sync_for_device(struct spi_controller *ctlr,
12100c17ba73SVincent Whitchurch 				    struct spi_transfer *xfer)
12110c17ba73SVincent Whitchurch {
12120c17ba73SVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
12130c17ba73SVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
12140c17ba73SVincent Whitchurch 
12150c17ba73SVincent Whitchurch 	if (!ctlr->cur_msg_mapped)
12160c17ba73SVincent Whitchurch 		return;
12170c17ba73SVincent Whitchurch 
12180c17ba73SVincent Whitchurch 	if (xfer->tx_sg.orig_nents)
12190c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_device(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
12200c17ba73SVincent Whitchurch 	if (xfer->rx_sg.orig_nents)
12210c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
12220c17ba73SVincent Whitchurch }
12230c17ba73SVincent Whitchurch 
spi_dma_sync_for_cpu(struct spi_controller * ctlr,struct spi_transfer * xfer)12240c17ba73SVincent Whitchurch static void spi_dma_sync_for_cpu(struct spi_controller *ctlr,
12250c17ba73SVincent Whitchurch 				 struct spi_transfer *xfer)
12260c17ba73SVincent Whitchurch {
12270c17ba73SVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
12280c17ba73SVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
12290c17ba73SVincent Whitchurch 
12300c17ba73SVincent Whitchurch 	if (!ctlr->cur_msg_mapped)
12310c17ba73SVincent Whitchurch 		return;
12320c17ba73SVincent Whitchurch 
12330c17ba73SVincent Whitchurch 	if (xfer->rx_sg.orig_nents)
12340c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
12350c17ba73SVincent Whitchurch 	if (xfer->tx_sg.orig_nents)
12360c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_cpu(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
12370c17ba73SVincent Whitchurch }
12382de440f5SGeert Uytterhoeven #else /* !CONFIG_HAS_DMA */
__spi_map_msg(struct spi_controller * ctlr,struct spi_message * msg)12398caab75fSGeert Uytterhoeven static inline int __spi_map_msg(struct spi_controller *ctlr,
12402de440f5SGeert Uytterhoeven 				struct spi_message *msg)
12412de440f5SGeert Uytterhoeven {
12422de440f5SGeert Uytterhoeven 	return 0;
12432de440f5SGeert Uytterhoeven }
12442de440f5SGeert Uytterhoeven 
__spi_unmap_msg(struct spi_controller * ctlr,struct spi_message * msg)12458caab75fSGeert Uytterhoeven static inline int __spi_unmap_msg(struct spi_controller *ctlr,
12462de440f5SGeert Uytterhoeven 				  struct spi_message *msg)
12472de440f5SGeert Uytterhoeven {
12482de440f5SGeert Uytterhoeven 	return 0;
12492de440f5SGeert Uytterhoeven }
12500c17ba73SVincent Whitchurch 
spi_dma_sync_for_device(struct spi_controller * ctrl,struct spi_transfer * xfer)12510c17ba73SVincent Whitchurch static void spi_dma_sync_for_device(struct spi_controller *ctrl,
12520c17ba73SVincent Whitchurch 				    struct spi_transfer *xfer)
12530c17ba73SVincent Whitchurch {
12540c17ba73SVincent Whitchurch }
12550c17ba73SVincent Whitchurch 
spi_dma_sync_for_cpu(struct spi_controller * ctrl,struct spi_transfer * xfer)12560c17ba73SVincent Whitchurch static void spi_dma_sync_for_cpu(struct spi_controller *ctrl,
12570c17ba73SVincent Whitchurch 				 struct spi_transfer *xfer)
12580c17ba73SVincent Whitchurch {
12590c17ba73SVincent Whitchurch }
12602de440f5SGeert Uytterhoeven #endif /* !CONFIG_HAS_DMA */
12612de440f5SGeert Uytterhoeven 
spi_unmap_msg(struct spi_controller * ctlr,struct spi_message * msg)12628caab75fSGeert Uytterhoeven static inline int spi_unmap_msg(struct spi_controller *ctlr,
12634b786458SMartin Sperl 				struct spi_message *msg)
12644b786458SMartin Sperl {
12654b786458SMartin Sperl 	struct spi_transfer *xfer;
12664b786458SMartin Sperl 
12674b786458SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
12684b786458SMartin Sperl 		/*
12694b786458SMartin Sperl 		 * Restore the original value of tx_buf or rx_buf if they are
12704b786458SMartin Sperl 		 * NULL.
12714b786458SMartin Sperl 		 */
12728caab75fSGeert Uytterhoeven 		if (xfer->tx_buf == ctlr->dummy_tx)
12734b786458SMartin Sperl 			xfer->tx_buf = NULL;
12748caab75fSGeert Uytterhoeven 		if (xfer->rx_buf == ctlr->dummy_rx)
12754b786458SMartin Sperl 			xfer->rx_buf = NULL;
12764b786458SMartin Sperl 	}
12774b786458SMartin Sperl 
12788caab75fSGeert Uytterhoeven 	return __spi_unmap_msg(ctlr, msg);
12794b786458SMartin Sperl }
12804b786458SMartin Sperl 
spi_map_msg(struct spi_controller * ctlr,struct spi_message * msg)12818caab75fSGeert Uytterhoeven static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
12822de440f5SGeert Uytterhoeven {
12832de440f5SGeert Uytterhoeven 	struct spi_transfer *xfer;
12842de440f5SGeert Uytterhoeven 	void *tmp;
12852de440f5SGeert Uytterhoeven 	unsigned int max_tx, max_rx;
12862de440f5SGeert Uytterhoeven 
1287aee67fe8Sdillon min 	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1288aee67fe8Sdillon min 		&& !(msg->spi->mode & SPI_3WIRE)) {
12892de440f5SGeert Uytterhoeven 		max_tx = 0;
12902de440f5SGeert Uytterhoeven 		max_rx = 0;
12912de440f5SGeert Uytterhoeven 
12922de440f5SGeert Uytterhoeven 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
12938caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
12942de440f5SGeert Uytterhoeven 			    !xfer->tx_buf)
12952de440f5SGeert Uytterhoeven 				max_tx = max(xfer->len, max_tx);
12968caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
12972de440f5SGeert Uytterhoeven 			    !xfer->rx_buf)
12982de440f5SGeert Uytterhoeven 				max_rx = max(xfer->len, max_rx);
12992de440f5SGeert Uytterhoeven 		}
13002de440f5SGeert Uytterhoeven 
13012de440f5SGeert Uytterhoeven 		if (max_tx) {
13028caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_tx, max_tx,
1303b00bab9dSAndy Shevchenko 				       GFP_KERNEL | GFP_DMA | __GFP_ZERO);
13042de440f5SGeert Uytterhoeven 			if (!tmp)
13052de440f5SGeert Uytterhoeven 				return -ENOMEM;
13068caab75fSGeert Uytterhoeven 			ctlr->dummy_tx = tmp;
13072de440f5SGeert Uytterhoeven 		}
13082de440f5SGeert Uytterhoeven 
13092de440f5SGeert Uytterhoeven 		if (max_rx) {
13108caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_rx, max_rx,
13112de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
13122de440f5SGeert Uytterhoeven 			if (!tmp)
13132de440f5SGeert Uytterhoeven 				return -ENOMEM;
13148caab75fSGeert Uytterhoeven 			ctlr->dummy_rx = tmp;
13152de440f5SGeert Uytterhoeven 		}
13162de440f5SGeert Uytterhoeven 
13172de440f5SGeert Uytterhoeven 		if (max_tx || max_rx) {
13182de440f5SGeert Uytterhoeven 			list_for_each_entry(xfer, &msg->transfers,
13192de440f5SGeert Uytterhoeven 					    transfer_list) {
13205442dcaaSChris Lesiak 				if (!xfer->len)
13215442dcaaSChris Lesiak 					continue;
13222de440f5SGeert Uytterhoeven 				if (!xfer->tx_buf)
13238caab75fSGeert Uytterhoeven 					xfer->tx_buf = ctlr->dummy_tx;
13242de440f5SGeert Uytterhoeven 				if (!xfer->rx_buf)
13258caab75fSGeert Uytterhoeven 					xfer->rx_buf = ctlr->dummy_rx;
13262de440f5SGeert Uytterhoeven 			}
13272de440f5SGeert Uytterhoeven 		}
13282de440f5SGeert Uytterhoeven 	}
13292de440f5SGeert Uytterhoeven 
13308caab75fSGeert Uytterhoeven 	return __spi_map_msg(ctlr, msg);
13312de440f5SGeert Uytterhoeven }
133299adef31SMark Brown 
spi_transfer_wait(struct spi_controller * ctlr,struct spi_message * msg,struct spi_transfer * xfer)1333810923f3SLubomir Rintel static int spi_transfer_wait(struct spi_controller *ctlr,
1334810923f3SLubomir Rintel 			     struct spi_message *msg,
1335810923f3SLubomir Rintel 			     struct spi_transfer *xfer)
1336810923f3SLubomir Rintel {
1337d501cc4cSDavid Jander 	struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1338d501cc4cSDavid Jander 	struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
13396170d077SXu Yilun 	u32 speed_hz = xfer->speed_hz;
134049686df5SColin Ian King 	unsigned long long ms;
1341810923f3SLubomir Rintel 
1342810923f3SLubomir Rintel 	if (spi_controller_is_slave(ctlr)) {
1343810923f3SLubomir Rintel 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1344810923f3SLubomir Rintel 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1345810923f3SLubomir Rintel 			return -EINTR;
1346810923f3SLubomir Rintel 		}
1347810923f3SLubomir Rintel 	} else {
13486170d077SXu Yilun 		if (!speed_hz)
13496170d077SXu Yilun 			speed_hz = 100000;
13506170d077SXu Yilun 
135186b8bff7SAndy Shevchenko 		/*
135286b8bff7SAndy Shevchenko 		 * For each byte we wait for 8 cycles of the SPI clock.
135386b8bff7SAndy Shevchenko 		 * Since speed is defined in Hz and we want milliseconds,
135486b8bff7SAndy Shevchenko 		 * use respective multiplier, but before the division,
135586b8bff7SAndy Shevchenko 		 * otherwise we may get 0 for short transfers.
135686b8bff7SAndy Shevchenko 		 */
135786b8bff7SAndy Shevchenko 		ms = 8LL * MSEC_PER_SEC * xfer->len;
13586170d077SXu Yilun 		do_div(ms, speed_hz);
1359810923f3SLubomir Rintel 
136086b8bff7SAndy Shevchenko 		/*
136186b8bff7SAndy Shevchenko 		 * Increase it twice and add 200 ms tolerance, use
136286b8bff7SAndy Shevchenko 		 * predefined maximum in case of overflow.
136386b8bff7SAndy Shevchenko 		 */
136486b8bff7SAndy Shevchenko 		ms += ms + 200;
1365810923f3SLubomir Rintel 		if (ms > UINT_MAX)
1366810923f3SLubomir Rintel 			ms = UINT_MAX;
1367810923f3SLubomir Rintel 
1368810923f3SLubomir Rintel 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1369810923f3SLubomir Rintel 						 msecs_to_jiffies(ms));
1370810923f3SLubomir Rintel 
1371810923f3SLubomir Rintel 		if (ms == 0) {
1372810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1373810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1374810923f3SLubomir Rintel 			dev_err(&msg->spi->dev,
1375810923f3SLubomir Rintel 				"SPI transfer timed out\n");
1376810923f3SLubomir Rintel 			return -ETIMEDOUT;
1377810923f3SLubomir Rintel 		}
1378810923f3SLubomir Rintel 	}
1379810923f3SLubomir Rintel 
1380810923f3SLubomir Rintel 	return 0;
1381810923f3SLubomir Rintel }
1382810923f3SLubomir Rintel 
_spi_transfer_delay_ns(u32 ns)13830ff2de8bSMartin Sperl static void _spi_transfer_delay_ns(u32 ns)
13840ff2de8bSMartin Sperl {
13850ff2de8bSMartin Sperl 	if (!ns)
13860ff2de8bSMartin Sperl 		return;
138786b8bff7SAndy Shevchenko 	if (ns <= NSEC_PER_USEC) {
13880ff2de8bSMartin Sperl 		ndelay(ns);
13890ff2de8bSMartin Sperl 	} else {
139086b8bff7SAndy Shevchenko 		u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
13910ff2de8bSMartin Sperl 
13920ff2de8bSMartin Sperl 		if (us <= 10)
13930ff2de8bSMartin Sperl 			udelay(us);
13940ff2de8bSMartin Sperl 		else
13950ff2de8bSMartin Sperl 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
13960ff2de8bSMartin Sperl 	}
13970ff2de8bSMartin Sperl }
13980ff2de8bSMartin Sperl 
spi_delay_to_ns(struct spi_delay * _delay,struct spi_transfer * xfer)13993984d39bSAlexandru Ardelean int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
14000ff2de8bSMartin Sperl {
1401b2c98153SAlexandru Ardelean 	u32 delay = _delay->value;
1402b2c98153SAlexandru Ardelean 	u32 unit = _delay->unit;
1403d5864e5bSMartin Sperl 	u32 hz;
14040ff2de8bSMartin Sperl 
1405b2c98153SAlexandru Ardelean 	if (!delay)
1406b2c98153SAlexandru Ardelean 		return 0;
14070ff2de8bSMartin Sperl 
14080ff2de8bSMartin Sperl 	switch (unit) {
14090ff2de8bSMartin Sperl 	case SPI_DELAY_UNIT_USECS:
141086b8bff7SAndy Shevchenko 		delay *= NSEC_PER_USEC;
14110ff2de8bSMartin Sperl 		break;
141286b8bff7SAndy Shevchenko 	case SPI_DELAY_UNIT_NSECS:
141386b8bff7SAndy Shevchenko 		/* Nothing to do here */
14140ff2de8bSMartin Sperl 		break;
1415d5864e5bSMartin Sperl 	case SPI_DELAY_UNIT_SCK:
141695c8222fSDavid Jander 		/* Clock cycles need to be obtained from spi_transfer */
1417b2c98153SAlexandru Ardelean 		if (!xfer)
1418b2c98153SAlexandru Ardelean 			return -EINVAL;
141986b8bff7SAndy Shevchenko 		/*
142086b8bff7SAndy Shevchenko 		 * If there is unknown effective speed, approximate it
1421702ca026SAndy Shevchenko 		 * by underestimating with half of the requested Hz.
1422d5864e5bSMartin Sperl 		 */
1423d5864e5bSMartin Sperl 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1424b2c98153SAlexandru Ardelean 		if (!hz)
1425b2c98153SAlexandru Ardelean 			return -EINVAL;
142686b8bff7SAndy Shevchenko 
142786b8bff7SAndy Shevchenko 		/* Convert delay to nanoseconds */
142886b8bff7SAndy Shevchenko 		delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1429d5864e5bSMartin Sperl 		break;
14300ff2de8bSMartin Sperl 	default:
1431b2c98153SAlexandru Ardelean 		return -EINVAL;
1432b2c98153SAlexandru Ardelean 	}
1433b2c98153SAlexandru Ardelean 
1434b2c98153SAlexandru Ardelean 	return delay;
1435b2c98153SAlexandru Ardelean }
14363984d39bSAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1437b2c98153SAlexandru Ardelean 
spi_delay_exec(struct spi_delay * _delay,struct spi_transfer * xfer)1438b2c98153SAlexandru Ardelean int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1439b2c98153SAlexandru Ardelean {
1440b2c98153SAlexandru Ardelean 	int delay;
1441b2c98153SAlexandru Ardelean 
14428fede89fSMark Brown 	might_sleep();
14438fede89fSMark Brown 
1444b2c98153SAlexandru Ardelean 	if (!_delay)
1445b2c98153SAlexandru Ardelean 		return -EINVAL;
1446b2c98153SAlexandru Ardelean 
14473984d39bSAlexandru Ardelean 	delay = spi_delay_to_ns(_delay, xfer);
1448b2c98153SAlexandru Ardelean 	if (delay < 0)
1449b2c98153SAlexandru Ardelean 		return delay;
1450b2c98153SAlexandru Ardelean 
1451b2c98153SAlexandru Ardelean 	_spi_transfer_delay_ns(delay);
1452b2c98153SAlexandru Ardelean 
1453b2c98153SAlexandru Ardelean 	return 0;
1454b2c98153SAlexandru Ardelean }
1455b2c98153SAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_exec);
1456b2c98153SAlexandru Ardelean 
_spi_transfer_cs_change_delay(struct spi_message * msg,struct spi_transfer * xfer)14570ff2de8bSMartin Sperl static void _spi_transfer_cs_change_delay(struct spi_message *msg,
14580ff2de8bSMartin Sperl 					  struct spi_transfer *xfer)
14590ff2de8bSMartin Sperl {
146086b8bff7SAndy Shevchenko 	u32 default_delay_ns = 10 * NSEC_PER_USEC;
1461329f0dacSAlexandru Ardelean 	u32 delay = xfer->cs_change_delay.value;
1462329f0dacSAlexandru Ardelean 	u32 unit = xfer->cs_change_delay.unit;
1463329f0dacSAlexandru Ardelean 	int ret;
14640ff2de8bSMartin Sperl 
146595c8222fSDavid Jander 	/* Return early on "fast" mode - for everything but USECS */
14666b3f236aSAlexandru Ardelean 	if (!delay) {
14676b3f236aSAlexandru Ardelean 		if (unit == SPI_DELAY_UNIT_USECS)
146886b8bff7SAndy Shevchenko 			_spi_transfer_delay_ns(default_delay_ns);
14690ff2de8bSMartin Sperl 		return;
14706b3f236aSAlexandru Ardelean 	}
14710ff2de8bSMartin Sperl 
1472329f0dacSAlexandru Ardelean 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1473329f0dacSAlexandru Ardelean 	if (ret) {
14740ff2de8bSMartin Sperl 		dev_err_once(&msg->spi->dev,
147586b8bff7SAndy Shevchenko 			     "Use of unsupported delay unit %i, using default of %luus\n",
147686b8bff7SAndy Shevchenko 			     unit, default_delay_ns / NSEC_PER_USEC);
147786b8bff7SAndy Shevchenko 		_spi_transfer_delay_ns(default_delay_ns);
14780ff2de8bSMartin Sperl 	}
14790ff2de8bSMartin Sperl }
14800ff2de8bSMartin Sperl 
spi_transfer_cs_change_delay_exec(struct spi_message * msg,struct spi_transfer * xfer)14816e80133aSWilliam Zhang void spi_transfer_cs_change_delay_exec(struct spi_message *msg,
14826e80133aSWilliam Zhang 						  struct spi_transfer *xfer)
14836e80133aSWilliam Zhang {
14846e80133aSWilliam Zhang 	_spi_transfer_cs_change_delay(msg, xfer);
14856e80133aSWilliam Zhang }
14866e80133aSWilliam Zhang EXPORT_SYMBOL_GPL(spi_transfer_cs_change_delay_exec);
14876e80133aSWilliam Zhang 
1488b158935fSMark Brown /*
1489b158935fSMark Brown  * spi_transfer_one_message - Default implementation of transfer_one_message()
1490b158935fSMark Brown  *
1491b158935fSMark Brown  * This is a standard implementation of transfer_one_message() for
14928ba811a7SMoritz Fischer  * drivers which implement a transfer_one() operation.  It provides
1493b158935fSMark Brown  * standard handling of delays and chip select management.
1494b158935fSMark Brown  */
spi_transfer_one_message(struct spi_controller * ctlr,struct spi_message * msg)14958caab75fSGeert Uytterhoeven static int spi_transfer_one_message(struct spi_controller *ctlr,
1496b158935fSMark Brown 				    struct spi_message *msg)
1497b158935fSMark Brown {
1498b158935fSMark Brown 	struct spi_transfer *xfer;
1499b158935fSMark Brown 	bool keep_cs = false;
1500b158935fSMark Brown 	int ret = 0;
1501d501cc4cSDavid Jander 	struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1502d501cc4cSDavid Jander 	struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1503b158935fSMark Brown 
15045e0531f6SChristophe Leroy 	xfer = list_first_entry(&msg->transfers, struct spi_transfer, transfer_list);
15055e0531f6SChristophe Leroy 	spi_set_cs(msg->spi, !xfer->cs_off, false);
1506b158935fSMark Brown 
1507eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1508eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1509eca2ebc7SMartin Sperl 
1510b158935fSMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1511b158935fSMark Brown 		trace_spi_transfer_start(msg, xfer);
1512b158935fSMark Brown 
15138caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
15148caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1515eca2ebc7SMartin Sperl 
1516b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1517b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1518b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1519b42faeeeSVladimir Oltean 		}
1520b42faeeeSVladimir Oltean 
1521b3063203SNicolas Saenz Julienne 		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
15228caab75fSGeert Uytterhoeven 			reinit_completion(&ctlr->xfer_completion);
1523b158935fSMark Brown 
1524809b1b04SRobin Gong fallback_pio:
15250c17ba73SVincent Whitchurch 			spi_dma_sync_for_device(ctlr, xfer);
15268caab75fSGeert Uytterhoeven 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1527b158935fSMark Brown 			if (ret < 0) {
15280c17ba73SVincent Whitchurch 				spi_dma_sync_for_cpu(ctlr, xfer);
15290c17ba73SVincent Whitchurch 
1530809b1b04SRobin Gong 				if (ctlr->cur_msg_mapped &&
1531809b1b04SRobin Gong 				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1532809b1b04SRobin Gong 					__spi_unmap_msg(ctlr, msg);
1533809b1b04SRobin Gong 					ctlr->fallback = true;
1534809b1b04SRobin Gong 					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1535809b1b04SRobin Gong 					goto fallback_pio;
1536809b1b04SRobin Gong 				}
1537809b1b04SRobin Gong 
1538eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1539eca2ebc7SMartin Sperl 							       errors);
1540eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1541eca2ebc7SMartin Sperl 							       errors);
1542b158935fSMark Brown 				dev_err(&msg->spi->dev,
1543b158935fSMark Brown 					"SPI transfer failed: %d\n", ret);
1544b158935fSMark Brown 				goto out;
1545b158935fSMark Brown 			}
1546b158935fSMark Brown 
1547d57e7960SMark Brown 			if (ret > 0) {
1548810923f3SLubomir Rintel 				ret = spi_transfer_wait(ctlr, msg, xfer);
1549810923f3SLubomir Rintel 				if (ret < 0)
1550810923f3SLubomir Rintel 					msg->status = ret;
1551d57e7960SMark Brown 			}
15520c17ba73SVincent Whitchurch 
15530c17ba73SVincent Whitchurch 			spi_dma_sync_for_cpu(ctlr, xfer);
155438ec10f6SMark Brown 		} else {
155538ec10f6SMark Brown 			if (xfer->len)
155638ec10f6SMark Brown 				dev_err(&msg->spi->dev,
155738ec10f6SMark Brown 					"Bufferless transfer has length %u\n",
155838ec10f6SMark Brown 					xfer->len);
155938ec10f6SMark Brown 		}
1560b158935fSMark Brown 
1561b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1562b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1563b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1564b42faeeeSVladimir Oltean 		}
1565b42faeeeSVladimir Oltean 
1566b158935fSMark Brown 		trace_spi_transfer_stop(msg, xfer);
1567b158935fSMark Brown 
1568b158935fSMark Brown 		if (msg->status != -EINPROGRESS)
1569b158935fSMark Brown 			goto out;
1570b158935fSMark Brown 
1571bebcfd27SAlexandru Ardelean 		spi_transfer_delay_exec(xfer);
1572b158935fSMark Brown 
1573b158935fSMark Brown 		if (xfer->cs_change) {
1574b158935fSMark Brown 			if (list_is_last(&xfer->transfer_list,
1575b158935fSMark Brown 					 &msg->transfers)) {
1576b158935fSMark Brown 				keep_cs = true;
1577b158935fSMark Brown 			} else {
15785e0531f6SChristophe Leroy 				if (!xfer->cs_off)
1579d347b4aaSDavid Bauer 					spi_set_cs(msg->spi, false, false);
15800ff2de8bSMartin Sperl 				_spi_transfer_cs_change_delay(msg, xfer);
15815e0531f6SChristophe Leroy 				if (!list_next_entry(xfer, transfer_list)->cs_off)
1582d347b4aaSDavid Bauer 					spi_set_cs(msg->spi, true, false);
1583b158935fSMark Brown 			}
15845e0531f6SChristophe Leroy 		} else if (!list_is_last(&xfer->transfer_list, &msg->transfers) &&
15855e0531f6SChristophe Leroy 			   xfer->cs_off != list_next_entry(xfer, transfer_list)->cs_off) {
15865e0531f6SChristophe Leroy 			spi_set_cs(msg->spi, xfer->cs_off, false);
1587b158935fSMark Brown 		}
1588b158935fSMark Brown 
1589b158935fSMark Brown 		msg->actual_length += xfer->len;
1590b158935fSMark Brown 	}
1591b158935fSMark Brown 
1592b158935fSMark Brown out:
1593b158935fSMark Brown 	if (ret != 0 || !keep_cs)
1594d347b4aaSDavid Bauer 		spi_set_cs(msg->spi, false, false);
1595b158935fSMark Brown 
1596b158935fSMark Brown 	if (msg->status == -EINPROGRESS)
1597b158935fSMark Brown 		msg->status = ret;
1598b158935fSMark Brown 
15998caab75fSGeert Uytterhoeven 	if (msg->status && ctlr->handle_err)
16008caab75fSGeert Uytterhoeven 		ctlr->handle_err(ctlr, msg);
1601b716c4ffSAndy Shevchenko 
16020ed56252SMark Brown 	spi_finalize_current_message(ctlr);
16030ed56252SMark Brown 
1604b158935fSMark Brown 	return ret;
1605b158935fSMark Brown }
1606b158935fSMark Brown 
1607b158935fSMark Brown /**
1608b158935fSMark Brown  * spi_finalize_current_transfer - report completion of a transfer
16098caab75fSGeert Uytterhoeven  * @ctlr: the controller reporting completion
1610b158935fSMark Brown  *
1611b158935fSMark Brown  * Called by SPI drivers using the core transfer_one_message()
1612b158935fSMark Brown  * implementation to notify it that the current interrupt driven
16139e8f4882SGeert Uytterhoeven  * transfer has finished and the next one may be scheduled.
1614b158935fSMark Brown  */
spi_finalize_current_transfer(struct spi_controller * ctlr)16158caab75fSGeert Uytterhoeven void spi_finalize_current_transfer(struct spi_controller *ctlr)
1616b158935fSMark Brown {
16178caab75fSGeert Uytterhoeven 	complete(&ctlr->xfer_completion);
1618b158935fSMark Brown }
1619b158935fSMark Brown EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1620b158935fSMark Brown 
spi_idle_runtime_pm(struct spi_controller * ctlr)1621e1268597SMark Brown static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1622e1268597SMark Brown {
1623e1268597SMark Brown 	if (ctlr->auto_runtime_pm) {
1624e1268597SMark Brown 		pm_runtime_mark_last_busy(ctlr->dev.parent);
1625e1268597SMark Brown 		pm_runtime_put_autosuspend(ctlr->dev.parent);
1626e1268597SMark Brown 	}
1627e1268597SMark Brown }
1628e1268597SMark Brown 
__spi_pump_transfer_message(struct spi_controller * ctlr,struct spi_message * msg,bool was_busy)1629ae7d2346SDavid Jander static int __spi_pump_transfer_message(struct spi_controller *ctlr,
1630ae7d2346SDavid Jander 		struct spi_message *msg, bool was_busy)
1631ae7d2346SDavid Jander {
1632ae7d2346SDavid Jander 	struct spi_transfer *xfer;
1633ae7d2346SDavid Jander 	int ret;
1634ae7d2346SDavid Jander 
1635ae7d2346SDavid Jander 	if (!was_busy && ctlr->auto_runtime_pm) {
1636ae7d2346SDavid Jander 		ret = pm_runtime_get_sync(ctlr->dev.parent);
1637ae7d2346SDavid Jander 		if (ret < 0) {
1638ae7d2346SDavid Jander 			pm_runtime_put_noidle(ctlr->dev.parent);
1639ae7d2346SDavid Jander 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
1640ae7d2346SDavid Jander 				ret);
16410232a19aSDavid Lechner 
16420232a19aSDavid Lechner 			msg->status = ret;
16430232a19aSDavid Lechner 			spi_finalize_current_message(ctlr);
16440232a19aSDavid Lechner 
1645ae7d2346SDavid Jander 			return ret;
1646ae7d2346SDavid Jander 		}
1647ae7d2346SDavid Jander 	}
1648ae7d2346SDavid Jander 
1649ae7d2346SDavid Jander 	if (!was_busy)
1650ae7d2346SDavid Jander 		trace_spi_controller_busy(ctlr);
1651ae7d2346SDavid Jander 
1652ae7d2346SDavid Jander 	if (!was_busy && ctlr->prepare_transfer_hardware) {
1653ae7d2346SDavid Jander 		ret = ctlr->prepare_transfer_hardware(ctlr);
1654ae7d2346SDavid Jander 		if (ret) {
1655ae7d2346SDavid Jander 			dev_err(&ctlr->dev,
1656ae7d2346SDavid Jander 				"failed to prepare transfer hardware: %d\n",
1657ae7d2346SDavid Jander 				ret);
1658ae7d2346SDavid Jander 
1659ae7d2346SDavid Jander 			if (ctlr->auto_runtime_pm)
1660ae7d2346SDavid Jander 				pm_runtime_put(ctlr->dev.parent);
1661ae7d2346SDavid Jander 
1662ae7d2346SDavid Jander 			msg->status = ret;
1663ae7d2346SDavid Jander 			spi_finalize_current_message(ctlr);
1664ae7d2346SDavid Jander 
1665ae7d2346SDavid Jander 			return ret;
1666ae7d2346SDavid Jander 		}
1667ae7d2346SDavid Jander 	}
1668ae7d2346SDavid Jander 
1669ae7d2346SDavid Jander 	trace_spi_message_start(msg);
1670ae7d2346SDavid Jander 
16718d699ff9SVincent Whitchurch 	ret = spi_split_transfers_maxsize(ctlr, msg,
16728d699ff9SVincent Whitchurch 					  spi_max_transfer_size(msg->spi),
16738d699ff9SVincent Whitchurch 					  GFP_KERNEL | GFP_DMA);
16748d699ff9SVincent Whitchurch 	if (ret) {
16758d699ff9SVincent Whitchurch 		msg->status = ret;
16768d699ff9SVincent Whitchurch 		spi_finalize_current_message(ctlr);
16778d699ff9SVincent Whitchurch 		return ret;
16788d699ff9SVincent Whitchurch 	}
16798d699ff9SVincent Whitchurch 
1680ae7d2346SDavid Jander 	if (ctlr->prepare_message) {
1681ae7d2346SDavid Jander 		ret = ctlr->prepare_message(ctlr, msg);
1682ae7d2346SDavid Jander 		if (ret) {
1683ae7d2346SDavid Jander 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1684ae7d2346SDavid Jander 				ret);
1685ae7d2346SDavid Jander 			msg->status = ret;
1686ae7d2346SDavid Jander 			spi_finalize_current_message(ctlr);
1687ae7d2346SDavid Jander 			return ret;
1688ae7d2346SDavid Jander 		}
1689ae7d2346SDavid Jander 		msg->prepared = true;
1690ae7d2346SDavid Jander 	}
1691ae7d2346SDavid Jander 
1692ae7d2346SDavid Jander 	ret = spi_map_msg(ctlr, msg);
1693ae7d2346SDavid Jander 	if (ret) {
1694ae7d2346SDavid Jander 		msg->status = ret;
1695ae7d2346SDavid Jander 		spi_finalize_current_message(ctlr);
1696ae7d2346SDavid Jander 		return ret;
1697ae7d2346SDavid Jander 	}
1698ae7d2346SDavid Jander 
1699ae7d2346SDavid Jander 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1700ae7d2346SDavid Jander 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1701ae7d2346SDavid Jander 			xfer->ptp_sts_word_pre = 0;
1702ae7d2346SDavid Jander 			ptp_read_system_prets(xfer->ptp_sts);
1703ae7d2346SDavid Jander 		}
1704ae7d2346SDavid Jander 	}
1705ae7d2346SDavid Jander 
1706dc302905SDavid Jander 	/*
1707dc302905SDavid Jander 	 * Drivers implementation of transfer_one_message() must arrange for
1708dc302905SDavid Jander 	 * spi_finalize_current_message() to get called. Most drivers will do
1709dc302905SDavid Jander 	 * this in the calling context, but some don't. For those cases, a
1710dc302905SDavid Jander 	 * completion is used to guarantee that this function does not return
1711dc302905SDavid Jander 	 * until spi_finalize_current_message() is done accessing
1712dc302905SDavid Jander 	 * ctlr->cur_msg.
1713dc302905SDavid Jander 	 * Use of the following two flags enable to opportunistically skip the
1714dc302905SDavid Jander 	 * use of the completion since its use involves expensive spin locks.
1715dc302905SDavid Jander 	 * In case of a race with the context that calls
1716dc302905SDavid Jander 	 * spi_finalize_current_message() the completion will always be used,
1717dc302905SDavid Jander 	 * due to strict ordering of these flags using barriers.
1718dc302905SDavid Jander 	 */
1719dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_incomplete, true);
1720dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_need_completion, false);
172169fa9590SDavid Jander 	reinit_completion(&ctlr->cur_msg_completion);
172295c8222fSDavid Jander 	smp_wmb(); /* Make these available to spi_finalize_current_message() */
1723dc302905SDavid Jander 
1724ae7d2346SDavid Jander 	ret = ctlr->transfer_one_message(ctlr, msg);
1725ae7d2346SDavid Jander 	if (ret) {
1726ae7d2346SDavid Jander 		dev_err(&ctlr->dev,
1727ae7d2346SDavid Jander 			"failed to transfer one message from queue\n");
1728ae7d2346SDavid Jander 		return ret;
172931d4c1bdSDavid Jander 	}
173031d4c1bdSDavid Jander 
1731dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_need_completion, true);
173231d4c1bdSDavid Jander 	smp_mb(); /* See spi_finalize_current_message()... */
1733dc302905SDavid Jander 	if (READ_ONCE(ctlr->cur_msg_incomplete))
173469fa9590SDavid Jander 		wait_for_completion(&ctlr->cur_msg_completion);
1735ae7d2346SDavid Jander 
1736ae7d2346SDavid Jander 	return 0;
1737ae7d2346SDavid Jander }
1738ae7d2346SDavid Jander 
1739ffbbdd21SLinus Walleij /**
1740702ca026SAndy Shevchenko  * __spi_pump_messages - function which processes SPI message queue
17418caab75fSGeert Uytterhoeven  * @ctlr: controller to process queue for
1742fc9e0f71SMark Brown  * @in_kthread: true if we are in the context of the message pump thread
1743ffbbdd21SLinus Walleij  *
1744702ca026SAndy Shevchenko  * This function checks if there is any SPI message in the queue that
1745ffbbdd21SLinus Walleij  * needs processing and if so call out to the driver to initialize hardware
1746ffbbdd21SLinus Walleij  * and transfer each message.
1747ffbbdd21SLinus Walleij  *
17480461a414SMark Brown  * Note that it is called both from the kthread itself and also from
17490461a414SMark Brown  * inside spi_sync(); the queue extraction handling at the top of the
17500461a414SMark Brown  * function should deal with this safely.
1751ffbbdd21SLinus Walleij  */
__spi_pump_messages(struct spi_controller * ctlr,bool in_kthread)17528caab75fSGeert Uytterhoeven static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1753ffbbdd21SLinus Walleij {
1754d1c44c93SVladimir Oltean 	struct spi_message *msg;
1755ffbbdd21SLinus Walleij 	bool was_busy = false;
1756d1c44c93SVladimir Oltean 	unsigned long flags;
1757ffbbdd21SLinus Walleij 	int ret;
1758ffbbdd21SLinus Walleij 
1759702ca026SAndy Shevchenko 	/* Take the I/O mutex */
1760c1038165SDavid Jander 	mutex_lock(&ctlr->io_mutex);
1761c1038165SDavid Jander 
1762983aee5dSMark Brown 	/* Lock queue */
17638caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1764983aee5dSMark Brown 
1765983aee5dSMark Brown 	/* Make sure we are not already running a message */
17668711a2abSDavid Jander 	if (ctlr->cur_msg)
1767c1038165SDavid Jander 		goto out_unlock;
1768983aee5dSMark Brown 
1769983aee5dSMark Brown 	/* Check if the queue is idle */
17708caab75fSGeert Uytterhoeven 	if (list_empty(&ctlr->queue) || !ctlr->running) {
17718711a2abSDavid Jander 		if (!ctlr->busy)
1772c1038165SDavid Jander 			goto out_unlock;
1773fc9e0f71SMark Brown 
1774e1268597SMark Brown 		/* Defer any non-atomic teardown to the thread */
1775f0125f1aSMark Brown 		if (!in_kthread) {
1776e1268597SMark Brown 			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1777e1268597SMark Brown 			    !ctlr->unprepare_transfer_hardware) {
1778e1268597SMark Brown 				spi_idle_runtime_pm(ctlr);
1779e1268597SMark Brown 				ctlr->busy = false;
1780ae7d2346SDavid Jander 				ctlr->queue_empty = true;
1781e1268597SMark Brown 				trace_spi_controller_idle(ctlr);
1782e1268597SMark Brown 			} else {
178360a883d1SMarek Szyprowski 				kthread_queue_work(ctlr->kworker,
1784f0125f1aSMark Brown 						   &ctlr->pump_messages);
1785e1268597SMark Brown 			}
1786c1038165SDavid Jander 			goto out_unlock;
1787f0125f1aSMark Brown 		}
1788f0125f1aSMark Brown 
1789f0125f1aSMark Brown 		ctlr->busy = false;
1790f0125f1aSMark Brown 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1791f0125f1aSMark Brown 
1792f0125f1aSMark Brown 		kfree(ctlr->dummy_rx);
1793f0125f1aSMark Brown 		ctlr->dummy_rx = NULL;
1794f0125f1aSMark Brown 		kfree(ctlr->dummy_tx);
1795f0125f1aSMark Brown 		ctlr->dummy_tx = NULL;
1796f0125f1aSMark Brown 		if (ctlr->unprepare_transfer_hardware &&
1797f0125f1aSMark Brown 		    ctlr->unprepare_transfer_hardware(ctlr))
1798f0125f1aSMark Brown 			dev_err(&ctlr->dev,
1799f0125f1aSMark Brown 				"failed to unprepare transfer hardware\n");
1800e1268597SMark Brown 		spi_idle_runtime_pm(ctlr);
1801f0125f1aSMark Brown 		trace_spi_controller_idle(ctlr);
1802f0125f1aSMark Brown 
1803f0125f1aSMark Brown 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1804ae7d2346SDavid Jander 		ctlr->queue_empty = true;
1805c1038165SDavid Jander 		goto out_unlock;
1806ffbbdd21SLinus Walleij 	}
1807ffbbdd21SLinus Walleij 
1808ffbbdd21SLinus Walleij 	/* Extract head of queue */
1809d1c44c93SVladimir Oltean 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1810d1c44c93SVladimir Oltean 	ctlr->cur_msg = msg;
1811ffbbdd21SLinus Walleij 
1812d1c44c93SVladimir Oltean 	list_del_init(&msg->queue);
18138caab75fSGeert Uytterhoeven 	if (ctlr->busy)
1814ffbbdd21SLinus Walleij 		was_busy = true;
1815ffbbdd21SLinus Walleij 	else
18168caab75fSGeert Uytterhoeven 		ctlr->busy = true;
18178caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1818ffbbdd21SLinus Walleij 
1819ae7d2346SDavid Jander 	ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
182069fa9590SDavid Jander 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1821c191543eSDavid Jander 
182269fa9590SDavid Jander 	ctlr->cur_msg = NULL;
182369fa9590SDavid Jander 	ctlr->fallback = false;
182469fa9590SDavid Jander 
18258caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->io_mutex);
182662826970SMark Brown 
182762826970SMark Brown 	/* Prod the scheduler in case transfer_one() was busy waiting */
182849023d2eSJon Hunter 	if (!ret)
182962826970SMark Brown 		cond_resched();
1830c1038165SDavid Jander 	return;
1831c1038165SDavid Jander 
1832c1038165SDavid Jander out_unlock:
18338711a2abSDavid Jander 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1834c1038165SDavid Jander 	mutex_unlock(&ctlr->io_mutex);
1835ffbbdd21SLinus Walleij }
1836ffbbdd21SLinus Walleij 
1837fc9e0f71SMark Brown /**
1838fc9e0f71SMark Brown  * spi_pump_messages - kthread work function which processes spi message queue
18398caab75fSGeert Uytterhoeven  * @work: pointer to kthread work struct contained in the controller struct
1840fc9e0f71SMark Brown  */
spi_pump_messages(struct kthread_work * work)1841fc9e0f71SMark Brown static void spi_pump_messages(struct kthread_work *work)
1842fc9e0f71SMark Brown {
18438caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr =
18448caab75fSGeert Uytterhoeven 		container_of(work, struct spi_controller, pump_messages);
1845fc9e0f71SMark Brown 
18468caab75fSGeert Uytterhoeven 	__spi_pump_messages(ctlr, true);
1847fc9e0f71SMark Brown }
1848fc9e0f71SMark Brown 
1849924b5867SDouglas Anderson /**
1850350de7ceSAndy Shevchenko  * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1851b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1852b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1853862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1854b42faeeeSVladimir Oltean  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1855b42faeeeSVladimir Oltean  *	      transfer, for less jitter in time measurement. Only compatible
1856b42faeeeSVladimir Oltean  *	      with PIO drivers. If true, must follow up with
1857b42faeeeSVladimir Oltean  *	      spi_take_timestamp_post or otherwise system will crash.
1858b42faeeeSVladimir Oltean  *	      WARNING: for fully predictable results, the CPU frequency must
1859b42faeeeSVladimir Oltean  *	      also be under control (governor).
1860350de7ceSAndy Shevchenko  *
1861350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the beginning of the TX timestamp
1862350de7ceSAndy Shevchenko  * for the requested byte from the SPI transfer. The frequency with which this
1863350de7ceSAndy Shevchenko  * function must be called (once per word, once for the whole transfer, once
1864350de7ceSAndy Shevchenko  * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1865350de7ceSAndy Shevchenko  * greater than or equal to the requested byte at the time of the call. The
1866350de7ceSAndy Shevchenko  * timestamp is only taken once, at the first such call. It is assumed that
1867350de7ceSAndy Shevchenko  * the driver advances its @tx buffer pointer monotonically.
1868b42faeeeSVladimir Oltean  */
spi_take_timestamp_pre(struct spi_controller * ctlr,struct spi_transfer * xfer,size_t progress,bool irqs_off)1869b42faeeeSVladimir Oltean void spi_take_timestamp_pre(struct spi_controller *ctlr,
1870b42faeeeSVladimir Oltean 			    struct spi_transfer *xfer,
1871862dd2a9SVladimir Oltean 			    size_t progress, bool irqs_off)
1872b42faeeeSVladimir Oltean {
1873b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1874b42faeeeSVladimir Oltean 		return;
1875b42faeeeSVladimir Oltean 
18766a726824SVladimir Oltean 	if (xfer->timestamped)
1877b42faeeeSVladimir Oltean 		return;
1878b42faeeeSVladimir Oltean 
18796a726824SVladimir Oltean 	if (progress > xfer->ptp_sts_word_pre)
1880b42faeeeSVladimir Oltean 		return;
1881b42faeeeSVladimir Oltean 
1882b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1883862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_pre = progress;
1884b42faeeeSVladimir Oltean 
1885b42faeeeSVladimir Oltean 	if (irqs_off) {
1886b42faeeeSVladimir Oltean 		local_irq_save(ctlr->irq_flags);
1887b42faeeeSVladimir Oltean 		preempt_disable();
1888b42faeeeSVladimir Oltean 	}
1889b42faeeeSVladimir Oltean 
1890b42faeeeSVladimir Oltean 	ptp_read_system_prets(xfer->ptp_sts);
1891b42faeeeSVladimir Oltean }
1892b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1893b42faeeeSVladimir Oltean 
1894b42faeeeSVladimir Oltean /**
1895350de7ceSAndy Shevchenko  * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1896b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1897b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1898862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1899b42faeeeSVladimir Oltean  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1900350de7ceSAndy Shevchenko  *
1901350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the end of the TX timestamp for
1902350de7ceSAndy Shevchenko  * the requested byte from the SPI transfer. Can be called with an arbitrary
1903350de7ceSAndy Shevchenko  * frequency: only the first call where @tx exceeds or is equal to the
1904350de7ceSAndy Shevchenko  * requested word will be timestamped.
1905b42faeeeSVladimir Oltean  */
spi_take_timestamp_post(struct spi_controller * ctlr,struct spi_transfer * xfer,size_t progress,bool irqs_off)1906b42faeeeSVladimir Oltean void spi_take_timestamp_post(struct spi_controller *ctlr,
1907b42faeeeSVladimir Oltean 			     struct spi_transfer *xfer,
1908862dd2a9SVladimir Oltean 			     size_t progress, bool irqs_off)
1909b42faeeeSVladimir Oltean {
1910b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1911b42faeeeSVladimir Oltean 		return;
1912b42faeeeSVladimir Oltean 
19136a726824SVladimir Oltean 	if (xfer->timestamped)
1914b42faeeeSVladimir Oltean 		return;
1915b42faeeeSVladimir Oltean 
1916862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_post)
1917b42faeeeSVladimir Oltean 		return;
1918b42faeeeSVladimir Oltean 
1919b42faeeeSVladimir Oltean 	ptp_read_system_postts(xfer->ptp_sts);
1920b42faeeeSVladimir Oltean 
1921b42faeeeSVladimir Oltean 	if (irqs_off) {
1922b42faeeeSVladimir Oltean 		local_irq_restore(ctlr->irq_flags);
1923b42faeeeSVladimir Oltean 		preempt_enable();
1924b42faeeeSVladimir Oltean 	}
1925b42faeeeSVladimir Oltean 
1926b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1927862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_post = progress;
1928b42faeeeSVladimir Oltean 
19299d77522bSChristophe JAILLET 	xfer->timestamped = 1;
1930b42faeeeSVladimir Oltean }
1931b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1932b42faeeeSVladimir Oltean 
1933b42faeeeSVladimir Oltean /**
1934924b5867SDouglas Anderson  * spi_set_thread_rt - set the controller to pump at realtime priority
1935924b5867SDouglas Anderson  * @ctlr: controller to boost priority of
1936924b5867SDouglas Anderson  *
1937924b5867SDouglas Anderson  * This can be called because the controller requested realtime priority
1938924b5867SDouglas Anderson  * (by setting the ->rt value before calling spi_register_controller()) or
1939924b5867SDouglas Anderson  * because a device on the bus said that its transfers needed realtime
1940924b5867SDouglas Anderson  * priority.
1941924b5867SDouglas Anderson  *
1942924b5867SDouglas Anderson  * NOTE: at the moment if any device on a bus says it needs realtime then
1943924b5867SDouglas Anderson  * the thread will be at realtime priority for all transfers on that
1944924b5867SDouglas Anderson  * controller.  If this eventually becomes a problem we may see if we can
1945924b5867SDouglas Anderson  * find a way to boost the priority only temporarily during relevant
1946924b5867SDouglas Anderson  * transfers.
1947924b5867SDouglas Anderson  */
spi_set_thread_rt(struct spi_controller * ctlr)1948924b5867SDouglas Anderson static void spi_set_thread_rt(struct spi_controller *ctlr)
1949ffbbdd21SLinus Walleij {
1950924b5867SDouglas Anderson 	dev_info(&ctlr->dev,
1951924b5867SDouglas Anderson 		"will run message pump with realtime priority\n");
19526d2b84a4SLinus Torvalds 	sched_set_fifo(ctlr->kworker->task);
1953924b5867SDouglas Anderson }
1954924b5867SDouglas Anderson 
spi_init_queue(struct spi_controller * ctlr)1955924b5867SDouglas Anderson static int spi_init_queue(struct spi_controller *ctlr)
1956924b5867SDouglas Anderson {
19578caab75fSGeert Uytterhoeven 	ctlr->running = false;
19588caab75fSGeert Uytterhoeven 	ctlr->busy = false;
1959ae7d2346SDavid Jander 	ctlr->queue_empty = true;
1960ffbbdd21SLinus Walleij 
196160a883d1SMarek Szyprowski 	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
196260a883d1SMarek Szyprowski 	if (IS_ERR(ctlr->kworker)) {
196360a883d1SMarek Szyprowski 		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
196460a883d1SMarek Szyprowski 		return PTR_ERR(ctlr->kworker);
1965ffbbdd21SLinus Walleij 	}
196660a883d1SMarek Szyprowski 
19678caab75fSGeert Uytterhoeven 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1968f0125f1aSMark Brown 
1969ffbbdd21SLinus Walleij 	/*
19708caab75fSGeert Uytterhoeven 	 * Controller config will indicate if this controller should run the
1971ffbbdd21SLinus Walleij 	 * message pump with high (realtime) priority to reduce the transfer
1972ffbbdd21SLinus Walleij 	 * latency on the bus by minimising the delay between a transfer
1973ffbbdd21SLinus Walleij 	 * request and the scheduling of the message pump thread. Without this
1974ffbbdd21SLinus Walleij 	 * setting the message pump thread will remain at default priority.
1975ffbbdd21SLinus Walleij 	 */
1976924b5867SDouglas Anderson 	if (ctlr->rt)
1977924b5867SDouglas Anderson 		spi_set_thread_rt(ctlr);
1978ffbbdd21SLinus Walleij 
1979ffbbdd21SLinus Walleij 	return 0;
1980ffbbdd21SLinus Walleij }
1981ffbbdd21SLinus Walleij 
1982ffbbdd21SLinus Walleij /**
1983ffbbdd21SLinus Walleij  * spi_get_next_queued_message() - called by driver to check for queued
1984ffbbdd21SLinus Walleij  * messages
19858caab75fSGeert Uytterhoeven  * @ctlr: the controller to check for queued messages
1986ffbbdd21SLinus Walleij  *
1987ffbbdd21SLinus Walleij  * If there are more messages in the queue, the next message is returned from
1988ffbbdd21SLinus Walleij  * this call.
198997d56dc6SJavier Martinez Canillas  *
199097d56dc6SJavier Martinez Canillas  * Return: the next message in the queue, else NULL if the queue is empty.
1991ffbbdd21SLinus Walleij  */
spi_get_next_queued_message(struct spi_controller * ctlr)19928caab75fSGeert Uytterhoeven struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1993ffbbdd21SLinus Walleij {
1994ffbbdd21SLinus Walleij 	struct spi_message *next;
1995ffbbdd21SLinus Walleij 	unsigned long flags;
1996ffbbdd21SLinus Walleij 
199795c8222fSDavid Jander 	/* Get a pointer to the next message, if any */
19988caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
19998caab75fSGeert Uytterhoeven 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
20001cfd97f9SAxel Lin 					queue);
20018caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2002ffbbdd21SLinus Walleij 
2003ffbbdd21SLinus Walleij 	return next;
2004ffbbdd21SLinus Walleij }
2005ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
2006ffbbdd21SLinus Walleij 
2007ffbbdd21SLinus Walleij /**
2008ffbbdd21SLinus Walleij  * spi_finalize_current_message() - the current message is complete
20098caab75fSGeert Uytterhoeven  * @ctlr: the controller to return the message to
2010ffbbdd21SLinus Walleij  *
2011ffbbdd21SLinus Walleij  * Called by the driver to notify the core that the message in the front of the
2012ffbbdd21SLinus Walleij  * queue is complete and can be removed from the queue.
2013ffbbdd21SLinus Walleij  */
spi_finalize_current_message(struct spi_controller * ctlr)20148caab75fSGeert Uytterhoeven void spi_finalize_current_message(struct spi_controller *ctlr)
2015ffbbdd21SLinus Walleij {
2016b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
2017ffbbdd21SLinus Walleij 	struct spi_message *mesg;
20182841a5fcSMark Brown 	int ret;
2019ffbbdd21SLinus Walleij 
20208caab75fSGeert Uytterhoeven 	mesg = ctlr->cur_msg;
2021ffbbdd21SLinus Walleij 
2022b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
2023b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
2024b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
2025b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
2026b42faeeeSVladimir Oltean 		}
2027b42faeeeSVladimir Oltean 	}
2028b42faeeeSVladimir Oltean 
20296a726824SVladimir Oltean 	if (unlikely(ctlr->ptp_sts_supported))
20306a726824SVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
20316a726824SVladimir Oltean 			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
2032f971a207SVladimir Oltean 
20338caab75fSGeert Uytterhoeven 	spi_unmap_msg(ctlr, mesg);
203499adef31SMark Brown 
2035350de7ceSAndy Shevchenko 	/*
2036350de7ceSAndy Shevchenko 	 * In the prepare_messages callback the SPI bus has the opportunity
2037350de7ceSAndy Shevchenko 	 * to split a transfer to smaller chunks.
2038350de7ceSAndy Shevchenko 	 *
2039350de7ceSAndy Shevchenko 	 * Release the split transfers here since spi_map_msg() is done on
2040350de7ceSAndy Shevchenko 	 * the split transfers.
2041b59a7ca1SGustav Wiklander 	 */
2042b59a7ca1SGustav Wiklander 	spi_res_release(ctlr, mesg);
2043b59a7ca1SGustav Wiklander 
20441714582aSDavid Jander 	if (mesg->prepared && ctlr->unprepare_message) {
20458caab75fSGeert Uytterhoeven 		ret = ctlr->unprepare_message(ctlr, mesg);
20462841a5fcSMark Brown 		if (ret) {
20478caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
20488caab75fSGeert Uytterhoeven 				ret);
20492841a5fcSMark Brown 		}
20502841a5fcSMark Brown 	}
2051391949b6SUwe Kleine-König 
20521714582aSDavid Jander 	mesg->prepared = false;
20531714582aSDavid Jander 
2054dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_incomplete, false);
2055dc302905SDavid Jander 	smp_mb(); /* See __spi_pump_transfer_message()... */
2056dc302905SDavid Jander 	if (READ_ONCE(ctlr->cur_msg_need_completion))
205769fa9590SDavid Jander 		complete(&ctlr->cur_msg_completion);
20588e76ef88SMartin Sperl 
20598e76ef88SMartin Sperl 	trace_spi_message_done(mesg);
20602841a5fcSMark Brown 
2061ffbbdd21SLinus Walleij 	mesg->state = NULL;
2062ffbbdd21SLinus Walleij 	if (mesg->complete)
2063ffbbdd21SLinus Walleij 		mesg->complete(mesg->context);
2064ffbbdd21SLinus Walleij }
2065ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_finalize_current_message);
2066ffbbdd21SLinus Walleij 
spi_start_queue(struct spi_controller * ctlr)20678caab75fSGeert Uytterhoeven static int spi_start_queue(struct spi_controller *ctlr)
2068ffbbdd21SLinus Walleij {
2069ffbbdd21SLinus Walleij 	unsigned long flags;
2070ffbbdd21SLinus Walleij 
20718caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2072ffbbdd21SLinus Walleij 
20738caab75fSGeert Uytterhoeven 	if (ctlr->running || ctlr->busy) {
20748caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2075ffbbdd21SLinus Walleij 		return -EBUSY;
2076ffbbdd21SLinus Walleij 	}
2077ffbbdd21SLinus Walleij 
20788caab75fSGeert Uytterhoeven 	ctlr->running = true;
20798caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
20808caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2081ffbbdd21SLinus Walleij 
208260a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2083ffbbdd21SLinus Walleij 
2084ffbbdd21SLinus Walleij 	return 0;
2085ffbbdd21SLinus Walleij }
2086ffbbdd21SLinus Walleij 
spi_stop_queue(struct spi_controller * ctlr)20878caab75fSGeert Uytterhoeven static int spi_stop_queue(struct spi_controller *ctlr)
2088ffbbdd21SLinus Walleij {
2089ffbbdd21SLinus Walleij 	unsigned long flags;
2090ffbbdd21SLinus Walleij 	unsigned limit = 500;
2091ffbbdd21SLinus Walleij 	int ret = 0;
2092ffbbdd21SLinus Walleij 
20938caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2094ffbbdd21SLinus Walleij 
2095ffbbdd21SLinus Walleij 	/*
2096ffbbdd21SLinus Walleij 	 * This is a bit lame, but is optimized for the common execution path.
20978caab75fSGeert Uytterhoeven 	 * A wait_queue on the ctlr->busy could be used, but then the common
2098ffbbdd21SLinus Walleij 	 * execution path (pump_messages) would be required to call wake_up or
2099ffbbdd21SLinus Walleij 	 * friends on every SPI message. Do this instead.
2100ffbbdd21SLinus Walleij 	 */
21018caab75fSGeert Uytterhoeven 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
21028caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2103f97b26b0SAxel Lin 		usleep_range(10000, 11000);
21048caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->queue_lock, flags);
2105ffbbdd21SLinus Walleij 	}
2106ffbbdd21SLinus Walleij 
21078caab75fSGeert Uytterhoeven 	if (!list_empty(&ctlr->queue) || ctlr->busy)
2108ffbbdd21SLinus Walleij 		ret = -EBUSY;
2109ffbbdd21SLinus Walleij 	else
21108caab75fSGeert Uytterhoeven 		ctlr->running = false;
2111ffbbdd21SLinus Walleij 
21128caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2113ffbbdd21SLinus Walleij 
2114ffbbdd21SLinus Walleij 	if (ret) {
21158caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "could not stop message queue\n");
2116ffbbdd21SLinus Walleij 		return ret;
2117ffbbdd21SLinus Walleij 	}
2118ffbbdd21SLinus Walleij 	return ret;
2119ffbbdd21SLinus Walleij }
2120ffbbdd21SLinus Walleij 
spi_destroy_queue(struct spi_controller * ctlr)21218caab75fSGeert Uytterhoeven static int spi_destroy_queue(struct spi_controller *ctlr)
2122ffbbdd21SLinus Walleij {
2123ffbbdd21SLinus Walleij 	int ret;
2124ffbbdd21SLinus Walleij 
21258caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
2126ffbbdd21SLinus Walleij 
2127ffbbdd21SLinus Walleij 	/*
21283989144fSPetr Mladek 	 * kthread_flush_worker will block until all work is done.
2129ffbbdd21SLinus Walleij 	 * If the reason that stop_queue timed out is that the work will never
2130ffbbdd21SLinus Walleij 	 * finish, then it does no good to call flush/stop thread, so
2131ffbbdd21SLinus Walleij 	 * return anyway.
2132ffbbdd21SLinus Walleij 	 */
2133ffbbdd21SLinus Walleij 	if (ret) {
21348caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem destroying queue\n");
2135ffbbdd21SLinus Walleij 		return ret;
2136ffbbdd21SLinus Walleij 	}
2137ffbbdd21SLinus Walleij 
213860a883d1SMarek Szyprowski 	kthread_destroy_worker(ctlr->kworker);
2139ffbbdd21SLinus Walleij 
2140ffbbdd21SLinus Walleij 	return 0;
2141ffbbdd21SLinus Walleij }
2142ffbbdd21SLinus Walleij 
__spi_queued_transfer(struct spi_device * spi,struct spi_message * msg,bool need_pump)21430461a414SMark Brown static int __spi_queued_transfer(struct spi_device *spi,
21440461a414SMark Brown 				 struct spi_message *msg,
21450461a414SMark Brown 				 bool need_pump)
2146ffbbdd21SLinus Walleij {
21478caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
2148ffbbdd21SLinus Walleij 	unsigned long flags;
2149ffbbdd21SLinus Walleij 
21508caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2151ffbbdd21SLinus Walleij 
21528caab75fSGeert Uytterhoeven 	if (!ctlr->running) {
21538caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2154ffbbdd21SLinus Walleij 		return -ESHUTDOWN;
2155ffbbdd21SLinus Walleij 	}
2156ffbbdd21SLinus Walleij 	msg->actual_length = 0;
2157ffbbdd21SLinus Walleij 	msg->status = -EINPROGRESS;
2158ffbbdd21SLinus Walleij 
21598caab75fSGeert Uytterhoeven 	list_add_tail(&msg->queue, &ctlr->queue);
2160ae7d2346SDavid Jander 	ctlr->queue_empty = false;
2161f0125f1aSMark Brown 	if (!ctlr->busy && need_pump)
216260a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2163ffbbdd21SLinus Walleij 
21648caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2165ffbbdd21SLinus Walleij 	return 0;
2166ffbbdd21SLinus Walleij }
2167ffbbdd21SLinus Walleij 
21680461a414SMark Brown /**
21690461a414SMark Brown  * spi_queued_transfer - transfer function for queued transfers
2170702ca026SAndy Shevchenko  * @spi: SPI device which is requesting transfer
2171702ca026SAndy Shevchenko  * @msg: SPI message which is to handled is queued to driver queue
217297d56dc6SJavier Martinez Canillas  *
217397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
21740461a414SMark Brown  */
spi_queued_transfer(struct spi_device * spi,struct spi_message * msg)21750461a414SMark Brown static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
21760461a414SMark Brown {
21770461a414SMark Brown 	return __spi_queued_transfer(spi, msg, true);
21780461a414SMark Brown }
21790461a414SMark Brown 
spi_controller_initialize_queue(struct spi_controller * ctlr)21808caab75fSGeert Uytterhoeven static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2181ffbbdd21SLinus Walleij {
2182ffbbdd21SLinus Walleij 	int ret;
2183ffbbdd21SLinus Walleij 
21848caab75fSGeert Uytterhoeven 	ctlr->transfer = spi_queued_transfer;
21858caab75fSGeert Uytterhoeven 	if (!ctlr->transfer_one_message)
21868caab75fSGeert Uytterhoeven 		ctlr->transfer_one_message = spi_transfer_one_message;
2187ffbbdd21SLinus Walleij 
2188ffbbdd21SLinus Walleij 	/* Initialize and start queue */
21898caab75fSGeert Uytterhoeven 	ret = spi_init_queue(ctlr);
2190ffbbdd21SLinus Walleij 	if (ret) {
21918caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem initializing queue\n");
2192ffbbdd21SLinus Walleij 		goto err_init_queue;
2193ffbbdd21SLinus Walleij 	}
21948caab75fSGeert Uytterhoeven 	ctlr->queued = true;
21958caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
2196ffbbdd21SLinus Walleij 	if (ret) {
21978caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem starting queue\n");
2198ffbbdd21SLinus Walleij 		goto err_start_queue;
2199ffbbdd21SLinus Walleij 	}
2200ffbbdd21SLinus Walleij 
2201ffbbdd21SLinus Walleij 	return 0;
2202ffbbdd21SLinus Walleij 
2203ffbbdd21SLinus Walleij err_start_queue:
22048caab75fSGeert Uytterhoeven 	spi_destroy_queue(ctlr);
2205c3676d5cSMark Brown err_init_queue:
2206ffbbdd21SLinus Walleij 	return ret;
2207ffbbdd21SLinus Walleij }
2208ffbbdd21SLinus Walleij 
2209988f259bSBoris Brezillon /**
2210988f259bSBoris Brezillon  * spi_flush_queue - Send all pending messages in the queue from the callers'
2211988f259bSBoris Brezillon  *		     context
2212988f259bSBoris Brezillon  * @ctlr: controller to process queue for
2213988f259bSBoris Brezillon  *
2214988f259bSBoris Brezillon  * This should be used when one wants to ensure all pending messages have been
2215988f259bSBoris Brezillon  * sent before doing something. Is used by the spi-mem code to make sure SPI
2216988f259bSBoris Brezillon  * memory operations do not preempt regular SPI transfers that have been queued
2217988f259bSBoris Brezillon  * before the spi-mem operation.
2218988f259bSBoris Brezillon  */
spi_flush_queue(struct spi_controller * ctlr)2219988f259bSBoris Brezillon void spi_flush_queue(struct spi_controller *ctlr)
2220988f259bSBoris Brezillon {
2221988f259bSBoris Brezillon 	if (ctlr->transfer == spi_queued_transfer)
2222988f259bSBoris Brezillon 		__spi_pump_messages(ctlr, false);
2223988f259bSBoris Brezillon }
2224988f259bSBoris Brezillon 
2225ffbbdd21SLinus Walleij /*-------------------------------------------------------------------------*/
2226ffbbdd21SLinus Walleij 
22277cb94361SAndreas Larsson #if defined(CONFIG_OF)
of_spi_parse_dt_cs_delay(struct device_node * nc,struct spi_delay * delay,const char * prop)2228f276aacfSJanne Grunau static void of_spi_parse_dt_cs_delay(struct device_node *nc,
2229f276aacfSJanne Grunau 				     struct spi_delay *delay, const char *prop)
2230f276aacfSJanne Grunau {
2231f276aacfSJanne Grunau 	u32 value;
2232f276aacfSJanne Grunau 
2233f276aacfSJanne Grunau 	if (!of_property_read_u32(nc, prop, &value)) {
2234f276aacfSJanne Grunau 		if (value > U16_MAX) {
2235f276aacfSJanne Grunau 			delay->value = DIV_ROUND_UP(value, 1000);
2236f276aacfSJanne Grunau 			delay->unit = SPI_DELAY_UNIT_USECS;
2237f276aacfSJanne Grunau 		} else {
2238f276aacfSJanne Grunau 			delay->value = value;
2239f276aacfSJanne Grunau 			delay->unit = SPI_DELAY_UNIT_NSECS;
2240f276aacfSJanne Grunau 		}
2241f276aacfSJanne Grunau 	}
2242f276aacfSJanne Grunau }
2243f276aacfSJanne Grunau 
of_spi_parse_dt(struct spi_controller * ctlr,struct spi_device * spi,struct device_node * nc)22448caab75fSGeert Uytterhoeven static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2245c2e51ac3SGeert Uytterhoeven 			   struct device_node *nc)
2246d57a4282SGrant Likely {
224789da4293STrent Piepho 	u32 value;
2248c2e51ac3SGeert Uytterhoeven 	int rc;
2249d57a4282SGrant Likely 
2250d57a4282SGrant Likely 	/* Mode (clock phase/polarity/etc.) */
2251e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpha"))
2252d57a4282SGrant Likely 		spi->mode |= SPI_CPHA;
2253e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpol"))
2254d57a4282SGrant Likely 		spi->mode |= SPI_CPOL;
2255e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-3wire"))
2256c20151dfSLars-Peter Clausen 		spi->mode |= SPI_3WIRE;
2257e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-lsb-first"))
2258cd6339e6SZhao Qiang 		spi->mode |= SPI_LSB_FIRST;
22593e5ec1dbSGregory CLEMENT 	if (of_property_read_bool(nc, "spi-cs-high"))
2260f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
2261f3186dd8SLinus Walleij 
2262f477b7fbSwangyuhang 	/* Device DUAL/QUAD mode */
226389da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
226489da4293STrent Piepho 		switch (value) {
2265d962608cSDragos Bogdan 		case 0:
2266d962608cSDragos Bogdan 			spi->mode |= SPI_NO_TX;
2267d962608cSDragos Bogdan 			break;
226889da4293STrent Piepho 		case 1:
2269f477b7fbSwangyuhang 			break;
227089da4293STrent Piepho 		case 2:
2271f477b7fbSwangyuhang 			spi->mode |= SPI_TX_DUAL;
2272f477b7fbSwangyuhang 			break;
227389da4293STrent Piepho 		case 4:
2274f477b7fbSwangyuhang 			spi->mode |= SPI_TX_QUAD;
2275f477b7fbSwangyuhang 			break;
22766b03061fSYogesh Narayan Gaur 		case 8:
22776b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_TX_OCTAL;
22786b03061fSYogesh Narayan Gaur 			break;
2279f477b7fbSwangyuhang 		default:
22808caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2281a110f93dSwangyuhang 				"spi-tx-bus-width %d not supported\n",
228289da4293STrent Piepho 				value);
228380874d8cSGeert Uytterhoeven 			break;
2284f477b7fbSwangyuhang 		}
2285a822e99cSMark Brown 	}
2286f477b7fbSwangyuhang 
228789da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
228889da4293STrent Piepho 		switch (value) {
2289d962608cSDragos Bogdan 		case 0:
2290d962608cSDragos Bogdan 			spi->mode |= SPI_NO_RX;
2291d962608cSDragos Bogdan 			break;
229289da4293STrent Piepho 		case 1:
2293f477b7fbSwangyuhang 			break;
229489da4293STrent Piepho 		case 2:
2295f477b7fbSwangyuhang 			spi->mode |= SPI_RX_DUAL;
2296f477b7fbSwangyuhang 			break;
229789da4293STrent Piepho 		case 4:
2298f477b7fbSwangyuhang 			spi->mode |= SPI_RX_QUAD;
2299f477b7fbSwangyuhang 			break;
23006b03061fSYogesh Narayan Gaur 		case 8:
23016b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_RX_OCTAL;
23026b03061fSYogesh Narayan Gaur 			break;
2303f477b7fbSwangyuhang 		default:
23048caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2305a110f93dSwangyuhang 				"spi-rx-bus-width %d not supported\n",
230689da4293STrent Piepho 				value);
230780874d8cSGeert Uytterhoeven 			break;
2308f477b7fbSwangyuhang 		}
2309a822e99cSMark Brown 	}
2310f477b7fbSwangyuhang 
23118caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr)) {
2312194276b0SRob Herring 		if (!of_node_name_eq(nc, "slave")) {
231325c56c88SRob Herring 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
231425c56c88SRob Herring 				nc);
23156c364062SGeert Uytterhoeven 			return -EINVAL;
23166c364062SGeert Uytterhoeven 		}
23176c364062SGeert Uytterhoeven 		return 0;
23186c364062SGeert Uytterhoeven 	}
23196c364062SGeert Uytterhoeven 
23206c364062SGeert Uytterhoeven 	/* Device address */
23216c364062SGeert Uytterhoeven 	rc = of_property_read_u32(nc, "reg", &value);
23226c364062SGeert Uytterhoeven 	if (rc) {
232325c56c88SRob Herring 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
232425c56c88SRob Herring 			nc, rc);
23256c364062SGeert Uytterhoeven 		return rc;
23266c364062SGeert Uytterhoeven 	}
2327303feb3cSAmit Kumar Mahapatra 	spi_set_chipselect(spi, 0, value);
23286c364062SGeert Uytterhoeven 
2329d57a4282SGrant Likely 	/* Device speed */
2330671c3bf5SChuanhong Guo 	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
233189da4293STrent Piepho 		spi->max_speed_hz = value;
2332d57a4282SGrant Likely 
2333f276aacfSJanne Grunau 	/* Device CS delays */
2334f276aacfSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_setup, "spi-cs-setup-delay-ns");
23355827b31dSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_hold, "spi-cs-hold-delay-ns");
23365827b31dSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_inactive, "spi-cs-inactive-delay-ns");
233733a2fde5STudor Ambarus 
2338c2e51ac3SGeert Uytterhoeven 	return 0;
2339c2e51ac3SGeert Uytterhoeven }
2340c2e51ac3SGeert Uytterhoeven 
2341c2e51ac3SGeert Uytterhoeven static struct spi_device *
of_register_spi_device(struct spi_controller * ctlr,struct device_node * nc)23428caab75fSGeert Uytterhoeven of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2343c2e51ac3SGeert Uytterhoeven {
2344c2e51ac3SGeert Uytterhoeven 	struct spi_device *spi;
2345c2e51ac3SGeert Uytterhoeven 	int rc;
2346c2e51ac3SGeert Uytterhoeven 
2347c2e51ac3SGeert Uytterhoeven 	/* Alloc an spi_device */
23488caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
2349c2e51ac3SGeert Uytterhoeven 	if (!spi) {
235025c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2351c2e51ac3SGeert Uytterhoeven 		rc = -ENOMEM;
2352c2e51ac3SGeert Uytterhoeven 		goto err_out;
2353c2e51ac3SGeert Uytterhoeven 	}
2354c2e51ac3SGeert Uytterhoeven 
2355c2e51ac3SGeert Uytterhoeven 	/* Select device driver */
2356673aa1edSMiquel Raynal 	rc = of_alias_from_compatible(nc, spi->modalias,
2357c2e51ac3SGeert Uytterhoeven 				      sizeof(spi->modalias));
2358c2e51ac3SGeert Uytterhoeven 	if (rc < 0) {
235925c56c88SRob Herring 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2360c2e51ac3SGeert Uytterhoeven 		goto err_out;
2361c2e51ac3SGeert Uytterhoeven 	}
2362c2e51ac3SGeert Uytterhoeven 
23638caab75fSGeert Uytterhoeven 	rc = of_spi_parse_dt(ctlr, spi, nc);
2364c2e51ac3SGeert Uytterhoeven 	if (rc)
2365c2e51ac3SGeert Uytterhoeven 		goto err_out;
2366c2e51ac3SGeert Uytterhoeven 
2367d57a4282SGrant Likely 	/* Store a pointer to the node in the device structure */
2368d57a4282SGrant Likely 	of_node_get(nc);
2369c7cc588bSAndy Shevchenko 
2370c7cc588bSAndy Shevchenko 	device_set_node(&spi->dev, of_fwnode_handle(nc));
2371d57a4282SGrant Likely 
2372d57a4282SGrant Likely 	/* Register the new device */
2373d57a4282SGrant Likely 	rc = spi_add_device(spi);
2374d57a4282SGrant Likely 	if (rc) {
237525c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
23768324147fSJohan Hovold 		goto err_of_node_put;
2377d57a4282SGrant Likely 	}
2378d57a4282SGrant Likely 
2379aff5e3f8SPantelis Antoniou 	return spi;
2380aff5e3f8SPantelis Antoniou 
23818324147fSJohan Hovold err_of_node_put:
23828324147fSJohan Hovold 	of_node_put(nc);
2383aff5e3f8SPantelis Antoniou err_out:
2384aff5e3f8SPantelis Antoniou 	spi_dev_put(spi);
2385aff5e3f8SPantelis Antoniou 	return ERR_PTR(rc);
2386aff5e3f8SPantelis Antoniou }
2387aff5e3f8SPantelis Antoniou 
2388aff5e3f8SPantelis Antoniou /**
2389aff5e3f8SPantelis Antoniou  * of_register_spi_devices() - Register child devices onto the SPI bus
23908caab75fSGeert Uytterhoeven  * @ctlr:	Pointer to spi_controller device
2391aff5e3f8SPantelis Antoniou  *
23926c364062SGeert Uytterhoeven  * Registers an spi_device for each child node of controller node which
23936c364062SGeert Uytterhoeven  * represents a valid SPI slave.
2394aff5e3f8SPantelis Antoniou  */
of_register_spi_devices(struct spi_controller * ctlr)23958caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr)
2396aff5e3f8SPantelis Antoniou {
2397aff5e3f8SPantelis Antoniou 	struct spi_device *spi;
2398aff5e3f8SPantelis Antoniou 	struct device_node *nc;
2399aff5e3f8SPantelis Antoniou 
24008caab75fSGeert Uytterhoeven 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2401bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2402bd6c1644SGeert Uytterhoeven 			continue;
24038caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, nc);
2404e0af98a7SRalf Ramsauer 		if (IS_ERR(spi)) {
24058caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
240625c56c88SRob Herring 				 "Failed to create SPI device for %pOF\n", nc);
2407e0af98a7SRalf Ramsauer 			of_node_clear_flag(nc, OF_POPULATED);
2408e0af98a7SRalf Ramsauer 		}
2409d57a4282SGrant Likely 	}
2410d57a4282SGrant Likely }
2411d57a4282SGrant Likely #else
of_register_spi_devices(struct spi_controller * ctlr)24128caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr) { }
2413d57a4282SGrant Likely #endif
2414d57a4282SGrant Likely 
24150c79378cSSebastian Reichel /**
24160c79378cSSebastian Reichel  * spi_new_ancillary_device() - Register ancillary SPI device
24170c79378cSSebastian Reichel  * @spi:         Pointer to the main SPI device registering the ancillary device
24180c79378cSSebastian Reichel  * @chip_select: Chip Select of the ancillary device
24190c79378cSSebastian Reichel  *
24200c79378cSSebastian Reichel  * Register an ancillary SPI device; for example some chips have a chip-select
24210c79378cSSebastian Reichel  * for normal device usage and another one for setup/firmware upload.
24220c79378cSSebastian Reichel  *
24230c79378cSSebastian Reichel  * This may only be called from main SPI device's probe routine.
24240c79378cSSebastian Reichel  *
24250c79378cSSebastian Reichel  * Return: 0 on success; negative errno on failure
24260c79378cSSebastian Reichel  */
spi_new_ancillary_device(struct spi_device * spi,u8 chip_select)24270c79378cSSebastian Reichel struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
24280c79378cSSebastian Reichel 					     u8 chip_select)
24290c79378cSSebastian Reichel {
24307b5c6a54SAndy Shevchenko 	struct spi_controller *ctlr = spi->controller;
24310c79378cSSebastian Reichel 	struct spi_device *ancillary;
24320c79378cSSebastian Reichel 	int rc = 0;
24330c79378cSSebastian Reichel 
24340c79378cSSebastian Reichel 	/* Alloc an spi_device */
24357b5c6a54SAndy Shevchenko 	ancillary = spi_alloc_device(ctlr);
24360c79378cSSebastian Reichel 	if (!ancillary) {
24370c79378cSSebastian Reichel 		rc = -ENOMEM;
24380c79378cSSebastian Reichel 		goto err_out;
24390c79378cSSebastian Reichel 	}
24400c79378cSSebastian Reichel 
244151e99de5SWolfram Sang 	strscpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
24420c79378cSSebastian Reichel 
24430c79378cSSebastian Reichel 	/* Use provided chip-select for ancillary device */
2444303feb3cSAmit Kumar Mahapatra 	spi_set_chipselect(ancillary, 0, chip_select);
24450c79378cSSebastian Reichel 
24460c79378cSSebastian Reichel 	/* Take over SPI mode/speed from SPI main device */
24470c79378cSSebastian Reichel 	ancillary->max_speed_hz = spi->max_speed_hz;
2448b01d5506SColin Ian King 	ancillary->mode = spi->mode;
24490c79378cSSebastian Reichel 
24507b5c6a54SAndy Shevchenko 	WARN_ON(!mutex_is_locked(&ctlr->add_lock));
24517b5c6a54SAndy Shevchenko 
24520c79378cSSebastian Reichel 	/* Register the new device */
24537b5c6a54SAndy Shevchenko 	rc = __spi_add_device(ancillary);
24540c79378cSSebastian Reichel 	if (rc) {
24550c79378cSSebastian Reichel 		dev_err(&spi->dev, "failed to register ancillary device\n");
24560c79378cSSebastian Reichel 		goto err_out;
24570c79378cSSebastian Reichel 	}
24580c79378cSSebastian Reichel 
24590c79378cSSebastian Reichel 	return ancillary;
24600c79378cSSebastian Reichel 
24610c79378cSSebastian Reichel err_out:
24620c79378cSSebastian Reichel 	spi_dev_put(ancillary);
24630c79378cSSebastian Reichel 	return ERR_PTR(rc);
24640c79378cSSebastian Reichel }
24650c79378cSSebastian Reichel EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
24660c79378cSSebastian Reichel 
246764bee4d2SMika Westerberg #ifdef CONFIG_ACPI
24684c3c5954SArd Biesheuvel struct acpi_spi_lookup {
24694c3c5954SArd Biesheuvel 	struct spi_controller 	*ctlr;
24704c3c5954SArd Biesheuvel 	u32			max_speed_hz;
24714c3c5954SArd Biesheuvel 	u32			mode;
24724c3c5954SArd Biesheuvel 	int			irq;
24734c3c5954SArd Biesheuvel 	u8			bits_per_word;
24744c3c5954SArd Biesheuvel 	u8			chip_select;
247587e59b36SStefan Binding 	int			n;
247687e59b36SStefan Binding 	int			index;
24774c3c5954SArd Biesheuvel };
24784c3c5954SArd Biesheuvel 
acpi_spi_count(struct acpi_resource * ares,void * data)2479e612af7aSStefan Binding static int acpi_spi_count(struct acpi_resource *ares, void *data)
2480e612af7aSStefan Binding {
2481e612af7aSStefan Binding 	struct acpi_resource_spi_serialbus *sb;
2482e612af7aSStefan Binding 	int *count = data;
2483e612af7aSStefan Binding 
2484e612af7aSStefan Binding 	if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2485e612af7aSStefan Binding 		return 1;
2486e612af7aSStefan Binding 
2487e612af7aSStefan Binding 	sb = &ares->data.spi_serial_bus;
2488e612af7aSStefan Binding 	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2489e612af7aSStefan Binding 		return 1;
2490e612af7aSStefan Binding 
2491e612af7aSStefan Binding 	*count = *count + 1;
2492e612af7aSStefan Binding 
2493e612af7aSStefan Binding 	return 1;
2494e612af7aSStefan Binding }
2495e612af7aSStefan Binding 
2496e612af7aSStefan Binding /**
2497e612af7aSStefan Binding  * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2498e612af7aSStefan Binding  * @adev:	ACPI device
2499e612af7aSStefan Binding  *
2500702ca026SAndy Shevchenko  * Return: the number of SpiSerialBus resources in the ACPI-device's
2501e612af7aSStefan Binding  * resource-list; or a negative error code.
2502e612af7aSStefan Binding  */
acpi_spi_count_resources(struct acpi_device * adev)2503e612af7aSStefan Binding int acpi_spi_count_resources(struct acpi_device *adev)
2504e612af7aSStefan Binding {
2505e612af7aSStefan Binding 	LIST_HEAD(r);
2506e612af7aSStefan Binding 	int count = 0;
2507e612af7aSStefan Binding 	int ret;
2508e612af7aSStefan Binding 
2509e612af7aSStefan Binding 	ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2510e612af7aSStefan Binding 	if (ret < 0)
2511e612af7aSStefan Binding 		return ret;
2512e612af7aSStefan Binding 
2513e612af7aSStefan Binding 	acpi_dev_free_resource_list(&r);
2514e612af7aSStefan Binding 
2515e612af7aSStefan Binding 	return count;
2516e612af7aSStefan Binding }
2517e612af7aSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2518e612af7aSStefan Binding 
acpi_spi_parse_apple_properties(struct acpi_device * dev,struct acpi_spi_lookup * lookup)25194c3c5954SArd Biesheuvel static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
25204c3c5954SArd Biesheuvel 					    struct acpi_spi_lookup *lookup)
25218a2e487eSLukas Wunner {
25228a2e487eSLukas Wunner 	const union acpi_object *obj;
25238a2e487eSLukas Wunner 
25248a2e487eSLukas Wunner 	if (!x86_apple_machine)
25258a2e487eSLukas Wunner 		return;
25268a2e487eSLukas Wunner 
25278a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
25288a2e487eSLukas Wunner 	    && obj->buffer.length >= 4)
25294c3c5954SArd Biesheuvel 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
25308a2e487eSLukas Wunner 
25318a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
25328a2e487eSLukas Wunner 	    && obj->buffer.length == 8)
25334c3c5954SArd Biesheuvel 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
25348a2e487eSLukas Wunner 
25358a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
25368a2e487eSLukas Wunner 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
25374c3c5954SArd Biesheuvel 		lookup->mode |= SPI_LSB_FIRST;
25388a2e487eSLukas Wunner 
25398a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
25408a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
25414c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPOL;
25428a2e487eSLukas Wunner 
25438a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
25448a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
25454c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPHA;
25468a2e487eSLukas Wunner }
25478a2e487eSLukas Wunner 
254887e59b36SStefan Binding static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev);
254987e59b36SStefan Binding 
acpi_spi_add_resource(struct acpi_resource * ares,void * data)255064bee4d2SMika Westerberg static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
255164bee4d2SMika Westerberg {
25524c3c5954SArd Biesheuvel 	struct acpi_spi_lookup *lookup = data;
25534c3c5954SArd Biesheuvel 	struct spi_controller *ctlr = lookup->ctlr;
255464bee4d2SMika Westerberg 
255564bee4d2SMika Westerberg 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
255664bee4d2SMika Westerberg 		struct acpi_resource_spi_serialbus *sb;
25574c3c5954SArd Biesheuvel 		acpi_handle parent_handle;
25584c3c5954SArd Biesheuvel 		acpi_status status;
255964bee4d2SMika Westerberg 
256064bee4d2SMika Westerberg 		sb = &ares->data.spi_serial_bus;
256164bee4d2SMika Westerberg 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
25624c3c5954SArd Biesheuvel 
256387e59b36SStefan Binding 			if (lookup->index != -1 && lookup->n++ != lookup->index)
256487e59b36SStefan Binding 				return 1;
256587e59b36SStefan Binding 
25664c3c5954SArd Biesheuvel 			status = acpi_get_handle(NULL,
25674c3c5954SArd Biesheuvel 						 sb->resource_source.string_ptr,
25684c3c5954SArd Biesheuvel 						 &parent_handle);
25694c3c5954SArd Biesheuvel 
257087e59b36SStefan Binding 			if (ACPI_FAILURE(status))
25714c3c5954SArd Biesheuvel 				return -ENODEV;
25724c3c5954SArd Biesheuvel 
257387e59b36SStefan Binding 			if (ctlr) {
257487e59b36SStefan Binding 				if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
257587e59b36SStefan Binding 					return -ENODEV;
257687e59b36SStefan Binding 			} else {
257787e59b36SStefan Binding 				struct acpi_device *adev;
257887e59b36SStefan Binding 
2579ac2a3feeSRafael J. Wysocki 				adev = acpi_fetch_acpi_dev(parent_handle);
2580ac2a3feeSRafael J. Wysocki 				if (!adev)
258187e59b36SStefan Binding 					return -ENODEV;
258287e59b36SStefan Binding 
258387e59b36SStefan Binding 				ctlr = acpi_spi_find_controller_by_adev(adev);
258487e59b36SStefan Binding 				if (!ctlr)
25859c22ec4aSAndy Shevchenko 					return -EPROBE_DEFER;
258687e59b36SStefan Binding 
258787e59b36SStefan Binding 				lookup->ctlr = ctlr;
258887e59b36SStefan Binding 			}
258987e59b36SStefan Binding 
2590a0a90718SMika Westerberg 			/*
2591a0a90718SMika Westerberg 			 * ACPI DeviceSelection numbering is handled by the
2592a0a90718SMika Westerberg 			 * host controller driver in Windows and can vary
2593a0a90718SMika Westerberg 			 * from driver to driver. In Linux we always expect
2594a0a90718SMika Westerberg 			 * 0 .. max - 1 so we need to ask the driver to
2595a0a90718SMika Westerberg 			 * translate between the two schemes.
2596a0a90718SMika Westerberg 			 */
25978caab75fSGeert Uytterhoeven 			if (ctlr->fw_translate_cs) {
25988caab75fSGeert Uytterhoeven 				int cs = ctlr->fw_translate_cs(ctlr,
2599a0a90718SMika Westerberg 						sb->device_selection);
2600a0a90718SMika Westerberg 				if (cs < 0)
2601a0a90718SMika Westerberg 					return cs;
26024c3c5954SArd Biesheuvel 				lookup->chip_select = cs;
2603a0a90718SMika Westerberg 			} else {
26044c3c5954SArd Biesheuvel 				lookup->chip_select = sb->device_selection;
2605a0a90718SMika Westerberg 			}
2606a0a90718SMika Westerberg 
26074c3c5954SArd Biesheuvel 			lookup->max_speed_hz = sb->connection_speed;
26080dadde34SAndy Shevchenko 			lookup->bits_per_word = sb->data_bit_length;
260964bee4d2SMika Westerberg 
261064bee4d2SMika Westerberg 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
26114c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPHA;
261264bee4d2SMika Westerberg 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
26134c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPOL;
261464bee4d2SMika Westerberg 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
26154c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CS_HIGH;
261664bee4d2SMika Westerberg 		}
26174c3c5954SArd Biesheuvel 	} else if (lookup->irq < 0) {
261864bee4d2SMika Westerberg 		struct resource r;
261964bee4d2SMika Westerberg 
262064bee4d2SMika Westerberg 		if (acpi_dev_resource_interrupt(ares, 0, &r))
26214c3c5954SArd Biesheuvel 			lookup->irq = r.start;
262264bee4d2SMika Westerberg 	}
262364bee4d2SMika Westerberg 
262464bee4d2SMika Westerberg 	/* Always tell the ACPI core to skip this resource */
262564bee4d2SMika Westerberg 	return 1;
262664bee4d2SMika Westerberg }
262764bee4d2SMika Westerberg 
2628000bee0eSStefan Binding /**
2629000bee0eSStefan Binding  * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2630000bee0eSStefan Binding  * @ctlr: controller to which the spi device belongs
2631000bee0eSStefan Binding  * @adev: ACPI Device for the spi device
263287e59b36SStefan Binding  * @index: Index of the spi resource inside the ACPI Node
2633000bee0eSStefan Binding  *
2634702ca026SAndy Shevchenko  * This should be used to allocate a new SPI device from and ACPI Device node.
2635702ca026SAndy Shevchenko  * The caller is responsible for calling spi_add_device to register the SPI device.
2636000bee0eSStefan Binding  *
2637702ca026SAndy Shevchenko  * If ctlr is set to NULL, the Controller for the SPI device will be looked up
263887e59b36SStefan Binding  * using the resource.
263987e59b36SStefan Binding  * If index is set to -1, index is not used.
264087e59b36SStefan Binding  * Note: If index is -1, ctlr must be set.
264187e59b36SStefan Binding  *
2642000bee0eSStefan Binding  * Return: a pointer to the new device, or ERR_PTR on error.
2643000bee0eSStefan Binding  */
acpi_spi_device_alloc(struct spi_controller * ctlr,struct acpi_device * adev,int index)2644000bee0eSStefan Binding struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
264587e59b36SStefan Binding 					 struct acpi_device *adev,
264687e59b36SStefan Binding 					 int index)
264764bee4d2SMika Westerberg {
26484c3c5954SArd Biesheuvel 	acpi_handle parent_handle = NULL;
264964bee4d2SMika Westerberg 	struct list_head resource_list;
2650b28944c6SArd Biesheuvel 	struct acpi_spi_lookup lookup = {};
265164bee4d2SMika Westerberg 	struct spi_device *spi;
265264bee4d2SMika Westerberg 	int ret;
265364bee4d2SMika Westerberg 
265487e59b36SStefan Binding 	if (!ctlr && index == -1)
265587e59b36SStefan Binding 		return ERR_PTR(-EINVAL);
265687e59b36SStefan Binding 
26574c3c5954SArd Biesheuvel 	lookup.ctlr		= ctlr;
26584c3c5954SArd Biesheuvel 	lookup.irq		= -1;
265987e59b36SStefan Binding 	lookup.index		= index;
266087e59b36SStefan Binding 	lookup.n		= 0;
26614c3c5954SArd Biesheuvel 
26624c3c5954SArd Biesheuvel 	INIT_LIST_HEAD(&resource_list);
26634c3c5954SArd Biesheuvel 	ret = acpi_dev_get_resources(adev, &resource_list,
26644c3c5954SArd Biesheuvel 				     acpi_spi_add_resource, &lookup);
26654c3c5954SArd Biesheuvel 	acpi_dev_free_resource_list(&resource_list);
26664c3c5954SArd Biesheuvel 
26674c3c5954SArd Biesheuvel 	if (ret < 0)
266895c8222fSDavid Jander 		/* Found SPI in _CRS but it points to another controller */
2669b6747f4fSAndy Shevchenko 		return ERR_PTR(ret);
26704c3c5954SArd Biesheuvel 
26714c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz &&
267210e92724SBjorn Helgaas 	    ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
267387e59b36SStefan Binding 	    ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
26744c3c5954SArd Biesheuvel 		/* Apple does not use _CRS but nested devices for SPI slaves */
26754c3c5954SArd Biesheuvel 		acpi_spi_parse_apple_properties(adev, &lookup);
26764c3c5954SArd Biesheuvel 	}
26774c3c5954SArd Biesheuvel 
26784c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz)
2679000bee0eSStefan Binding 		return ERR_PTR(-ENODEV);
26804c3c5954SArd Biesheuvel 
268187e59b36SStefan Binding 	spi = spi_alloc_device(lookup.ctlr);
268264bee4d2SMika Westerberg 	if (!spi) {
268387e59b36SStefan Binding 		dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
268464bee4d2SMika Westerberg 			dev_name(&adev->dev));
2685000bee0eSStefan Binding 		return ERR_PTR(-ENOMEM);
268664bee4d2SMika Westerberg 	}
268764bee4d2SMika Westerberg 
26887b199811SRafael J. Wysocki 	ACPI_COMPANION_SET(&spi->dev, adev);
26894c3c5954SArd Biesheuvel 	spi->max_speed_hz	= lookup.max_speed_hz;
2690ea235786SJohn Garry 	spi->mode		|= lookup.mode;
26914c3c5954SArd Biesheuvel 	spi->irq		= lookup.irq;
26924c3c5954SArd Biesheuvel 	spi->bits_per_word	= lookup.bits_per_word;
2693303feb3cSAmit Kumar Mahapatra 	spi_set_chipselect(spi, 0, lookup.chip_select);
269464bee4d2SMika Westerberg 
2695000bee0eSStefan Binding 	return spi;
2696000bee0eSStefan Binding }
2697000bee0eSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2698000bee0eSStefan Binding 
acpi_register_spi_device(struct spi_controller * ctlr,struct acpi_device * adev)2699000bee0eSStefan Binding static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2700000bee0eSStefan Binding 					    struct acpi_device *adev)
2701000bee0eSStefan Binding {
2702000bee0eSStefan Binding 	struct spi_device *spi;
2703000bee0eSStefan Binding 
2704000bee0eSStefan Binding 	if (acpi_bus_get_status(adev) || !adev->status.present ||
2705000bee0eSStefan Binding 	    acpi_device_enumerated(adev))
2706000bee0eSStefan Binding 		return AE_OK;
2707000bee0eSStefan Binding 
270887e59b36SStefan Binding 	spi = acpi_spi_device_alloc(ctlr, adev, -1);
2709000bee0eSStefan Binding 	if (IS_ERR(spi)) {
2710000bee0eSStefan Binding 		if (PTR_ERR(spi) == -ENOMEM)
2711000bee0eSStefan Binding 			return AE_NO_MEMORY;
2712000bee0eSStefan Binding 		else
2713000bee0eSStefan Binding 			return AE_OK;
2714000bee0eSStefan Binding 	}
2715000bee0eSStefan Binding 
27160c6543f6SDan O'Donovan 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
27170c6543f6SDan O'Donovan 			  sizeof(spi->modalias));
27180c6543f6SDan O'Donovan 
27197f24467fSOctavian Purdila 	acpi_device_set_enumerated(adev);
27207f24467fSOctavian Purdila 
272133cf00e5SMika Westerberg 	adev->power.flags.ignore_parent = true;
272264bee4d2SMika Westerberg 	if (spi_add_device(spi)) {
272333cf00e5SMika Westerberg 		adev->power.flags.ignore_parent = false;
27248caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
272564bee4d2SMika Westerberg 			dev_name(&adev->dev));
272664bee4d2SMika Westerberg 		spi_dev_put(spi);
272764bee4d2SMika Westerberg 	}
272864bee4d2SMika Westerberg 
272964bee4d2SMika Westerberg 	return AE_OK;
273064bee4d2SMika Westerberg }
273164bee4d2SMika Westerberg 
acpi_spi_add_device(acpi_handle handle,u32 level,void * data,void ** return_value)27327f24467fSOctavian Purdila static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
27337f24467fSOctavian Purdila 				       void *data, void **return_value)
27347f24467fSOctavian Purdila {
27357030c428SRafael J. Wysocki 	struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
27368caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = data;
27377f24467fSOctavian Purdila 
27387030c428SRafael J. Wysocki 	if (!adev)
27397f24467fSOctavian Purdila 		return AE_OK;
27407f24467fSOctavian Purdila 
27418caab75fSGeert Uytterhoeven 	return acpi_register_spi_device(ctlr, adev);
27427f24467fSOctavian Purdila }
27437f24467fSOctavian Purdila 
27444c3c5954SArd Biesheuvel #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
27454c3c5954SArd Biesheuvel 
acpi_register_spi_devices(struct spi_controller * ctlr)27468caab75fSGeert Uytterhoeven static void acpi_register_spi_devices(struct spi_controller *ctlr)
274764bee4d2SMika Westerberg {
274864bee4d2SMika Westerberg 	acpi_status status;
274964bee4d2SMika Westerberg 	acpi_handle handle;
275064bee4d2SMika Westerberg 
27518caab75fSGeert Uytterhoeven 	handle = ACPI_HANDLE(ctlr->dev.parent);
275264bee4d2SMika Westerberg 	if (!handle)
275364bee4d2SMika Westerberg 		return;
275464bee4d2SMika Westerberg 
27554c3c5954SArd Biesheuvel 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
27564c3c5954SArd Biesheuvel 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
27578caab75fSGeert Uytterhoeven 				     acpi_spi_add_device, NULL, ctlr, NULL);
275864bee4d2SMika Westerberg 	if (ACPI_FAILURE(status))
27598caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
276064bee4d2SMika Westerberg }
276164bee4d2SMika Westerberg #else
acpi_register_spi_devices(struct spi_controller * ctlr)27628caab75fSGeert Uytterhoeven static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
276364bee4d2SMika Westerberg #endif /* CONFIG_ACPI */
276464bee4d2SMika Westerberg 
spi_controller_release(struct device * dev)27658caab75fSGeert Uytterhoeven static void spi_controller_release(struct device *dev)
27668ae12a0dSDavid Brownell {
27678caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
27688ae12a0dSDavid Brownell 
27698caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
27708caab75fSGeert Uytterhoeven 	kfree(ctlr);
27718ae12a0dSDavid Brownell }
27728ae12a0dSDavid Brownell 
27738ae12a0dSDavid Brownell static struct class spi_master_class = {
27748ae12a0dSDavid Brownell 	.name		= "spi_master",
27758caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
2776eca2ebc7SMartin Sperl 	.dev_groups	= spi_master_groups,
27778ae12a0dSDavid Brownell };
27788ae12a0dSDavid Brownell 
27796c364062SGeert Uytterhoeven #ifdef CONFIG_SPI_SLAVE
27806c364062SGeert Uytterhoeven /**
27816c364062SGeert Uytterhoeven  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
27826c364062SGeert Uytterhoeven  *		     controller
27836c364062SGeert Uytterhoeven  * @spi: device used for the current transfer
27846c364062SGeert Uytterhoeven  */
spi_slave_abort(struct spi_device * spi)27856c364062SGeert Uytterhoeven int spi_slave_abort(struct spi_device *spi)
27866c364062SGeert Uytterhoeven {
27878caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
27886c364062SGeert Uytterhoeven 
27898caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
27908caab75fSGeert Uytterhoeven 		return ctlr->slave_abort(ctlr);
27916c364062SGeert Uytterhoeven 
27926c364062SGeert Uytterhoeven 	return -ENOTSUPP;
27936c364062SGeert Uytterhoeven }
27946c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_slave_abort);
27956c364062SGeert Uytterhoeven 
spi_target_abort(struct spi_device * spi)2796b8d3b056SYang Yingliang int spi_target_abort(struct spi_device *spi)
2797b8d3b056SYang Yingliang {
2798b8d3b056SYang Yingliang 	struct spi_controller *ctlr = spi->controller;
2799b8d3b056SYang Yingliang 
2800b8d3b056SYang Yingliang 	if (spi_controller_is_target(ctlr) && ctlr->target_abort)
2801b8d3b056SYang Yingliang 		return ctlr->target_abort(ctlr);
2802b8d3b056SYang Yingliang 
2803b8d3b056SYang Yingliang 	return -ENOTSUPP;
2804b8d3b056SYang Yingliang }
2805b8d3b056SYang Yingliang EXPORT_SYMBOL_GPL(spi_target_abort);
2806b8d3b056SYang Yingliang 
slave_show(struct device * dev,struct device_attribute * attr,char * buf)2807cc8b4659SGeert Uytterhoeven static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2808cc8b4659SGeert Uytterhoeven 			  char *buf)
28096c364062SGeert Uytterhoeven {
28108caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
28118caab75fSGeert Uytterhoeven 						   dev);
28126c364062SGeert Uytterhoeven 	struct device *child;
28136c364062SGeert Uytterhoeven 
2814c21b0837SAndy Shevchenko 	child = device_find_any_child(&ctlr->dev);
2815f2daa466SAndy Shevchenko 	return sysfs_emit(buf, "%s\n", child ? to_spi_device(child)->modalias : NULL);
28166c364062SGeert Uytterhoeven }
28176c364062SGeert Uytterhoeven 
slave_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)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",
28768caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
28776c364062SGeert Uytterhoeven 	.dev_groups	= spi_slave_groups,
28786c364062SGeert Uytterhoeven };
28796c364062SGeert Uytterhoeven #else
28806c364062SGeert Uytterhoeven extern struct class spi_slave_class;	/* dummy */
28816c364062SGeert Uytterhoeven #endif
28828ae12a0dSDavid Brownell 
28838ae12a0dSDavid Brownell /**
28846c364062SGeert Uytterhoeven  * __spi_alloc_controller - allocate an SPI master or slave controller
28858ae12a0dSDavid Brownell  * @dev: the controller, possibly using the platform_bus
288633e34dc6SDavid Brownell  * @size: how much zeroed driver-private data to allocate; the pointer to this
2887229e6af1SLukas Wunner  *	memory is in the driver_data field of the returned device, accessible
2888229e6af1SLukas Wunner  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2889229e6af1SLukas Wunner  *	drivers granting DMA access to portions of their private data need to
2890229e6af1SLukas Wunner  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
28916c364062SGeert Uytterhoeven  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
28926c364062SGeert Uytterhoeven  *	slave (true) controller
289333e34dc6SDavid Brownell  * Context: can sleep
28948ae12a0dSDavid Brownell  *
28956c364062SGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
28968ae12a0dSDavid Brownell  * only ones directly touching chip registers.  It's how they allocate
28978caab75fSGeert Uytterhoeven  * an spi_controller structure, prior to calling spi_register_controller().
28988ae12a0dSDavid Brownell  *
289997d56dc6SJavier Martinez Canillas  * This must be called from context that can sleep.
29008ae12a0dSDavid Brownell  *
29016c364062SGeert Uytterhoeven  * The caller is responsible for assigning the bus number and initializing the
29028caab75fSGeert Uytterhoeven  * controller's methods before calling spi_register_controller(); and (after
29038caab75fSGeert Uytterhoeven  * errors adding the device) calling spi_controller_put() to prevent a memory
29048caab75fSGeert Uytterhoeven  * leak.
290597d56dc6SJavier Martinez Canillas  *
29066c364062SGeert Uytterhoeven  * Return: the SPI controller structure on success, else NULL.
29078ae12a0dSDavid Brownell  */
__spi_alloc_controller(struct device * dev,unsigned int size,bool slave)29088caab75fSGeert Uytterhoeven struct spi_controller *__spi_alloc_controller(struct device *dev,
29096c364062SGeert Uytterhoeven 					      unsigned int size, bool slave)
29108ae12a0dSDavid Brownell {
29118caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr;
2912229e6af1SLukas Wunner 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
29138ae12a0dSDavid Brownell 
29140c868461SDavid Brownell 	if (!dev)
29150c868461SDavid Brownell 		return NULL;
29160c868461SDavid Brownell 
2917229e6af1SLukas Wunner 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
29188caab75fSGeert Uytterhoeven 	if (!ctlr)
29198ae12a0dSDavid Brownell 		return NULL;
29208ae12a0dSDavid Brownell 
29218caab75fSGeert Uytterhoeven 	device_initialize(&ctlr->dev);
292216a8e2fbSUwe Kleine-König 	INIT_LIST_HEAD(&ctlr->queue);
292316a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->queue_lock);
292416a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->bus_lock_spinlock);
292516a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->bus_lock_mutex);
292616a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->io_mutex);
292716a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->add_lock);
29288caab75fSGeert Uytterhoeven 	ctlr->bus_num = -1;
29298caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = 1;
29308caab75fSGeert Uytterhoeven 	ctlr->slave = slave;
29316c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
29328caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_slave_class;
29336c364062SGeert Uytterhoeven 	else
29348caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_master_class;
29358caab75fSGeert Uytterhoeven 	ctlr->dev.parent = dev;
29368caab75fSGeert Uytterhoeven 	pm_suspend_ignore_children(&ctlr->dev, true);
2937229e6af1SLukas Wunner 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
29388ae12a0dSDavid Brownell 
29398caab75fSGeert Uytterhoeven 	return ctlr;
29408ae12a0dSDavid Brownell }
29416c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(__spi_alloc_controller);
29428ae12a0dSDavid Brownell 
devm_spi_release_controller(struct device * dev,void * ctlr)29435e844cc3SLukas Wunner static void devm_spi_release_controller(struct device *dev, void *ctlr)
29445e844cc3SLukas Wunner {
29455e844cc3SLukas Wunner 	spi_controller_put(*(struct spi_controller **)ctlr);
29465e844cc3SLukas Wunner }
29475e844cc3SLukas Wunner 
29485e844cc3SLukas Wunner /**
29495e844cc3SLukas Wunner  * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
29505e844cc3SLukas Wunner  * @dev: physical device of SPI controller
29515e844cc3SLukas Wunner  * @size: how much zeroed driver-private data to allocate
29525e844cc3SLukas Wunner  * @slave: whether to allocate an SPI master (false) or SPI slave (true)
29535e844cc3SLukas Wunner  * Context: can sleep
29545e844cc3SLukas Wunner  *
29555e844cc3SLukas Wunner  * Allocate an SPI controller and automatically release a reference on it
29565e844cc3SLukas Wunner  * when @dev is unbound from its driver.  Drivers are thus relieved from
29575e844cc3SLukas Wunner  * having to call spi_controller_put().
29585e844cc3SLukas Wunner  *
29595e844cc3SLukas Wunner  * The arguments to this function are identical to __spi_alloc_controller().
29605e844cc3SLukas Wunner  *
29615e844cc3SLukas Wunner  * Return: the SPI controller structure on success, else NULL.
29625e844cc3SLukas Wunner  */
__devm_spi_alloc_controller(struct device * dev,unsigned int size,bool slave)29635e844cc3SLukas Wunner struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
29645e844cc3SLukas Wunner 						   unsigned int size,
29655e844cc3SLukas Wunner 						   bool slave)
29665e844cc3SLukas Wunner {
29675e844cc3SLukas Wunner 	struct spi_controller **ptr, *ctlr;
29685e844cc3SLukas Wunner 
29695e844cc3SLukas Wunner 	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
29705e844cc3SLukas Wunner 			   GFP_KERNEL);
29715e844cc3SLukas Wunner 	if (!ptr)
29725e844cc3SLukas Wunner 		return NULL;
29735e844cc3SLukas Wunner 
29745e844cc3SLukas Wunner 	ctlr = __spi_alloc_controller(dev, size, slave);
29755e844cc3SLukas Wunner 	if (ctlr) {
2976794aaf01SWilliam A. Kennington III 		ctlr->devm_allocated = true;
29775e844cc3SLukas Wunner 		*ptr = ctlr;
29785e844cc3SLukas Wunner 		devres_add(dev, ptr);
29795e844cc3SLukas Wunner 	} else {
29805e844cc3SLukas Wunner 		devres_free(ptr);
29815e844cc3SLukas Wunner 	}
29825e844cc3SLukas Wunner 
29835e844cc3SLukas Wunner 	return ctlr;
29845e844cc3SLukas Wunner }
29855e844cc3SLukas Wunner EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
29865e844cc3SLukas Wunner 
2987f3186dd8SLinus Walleij /**
2988f3186dd8SLinus Walleij  * spi_get_gpio_descs() - grab chip select GPIOs for the master
2989f3186dd8SLinus Walleij  * @ctlr: The SPI master to grab GPIO descriptors for
2990f3186dd8SLinus Walleij  */
spi_get_gpio_descs(struct spi_controller * ctlr)2991f3186dd8SLinus Walleij static int spi_get_gpio_descs(struct spi_controller *ctlr)
2992f3186dd8SLinus Walleij {
2993f3186dd8SLinus Walleij 	int nb, i;
2994f3186dd8SLinus Walleij 	struct gpio_desc **cs;
2995f3186dd8SLinus Walleij 	struct device *dev = &ctlr->dev;
29967d93aecdSGeert Uytterhoeven 	unsigned long native_cs_mask = 0;
29977d93aecdSGeert Uytterhoeven 	unsigned int num_cs_gpios = 0;
2998f3186dd8SLinus Walleij 
2999f3186dd8SLinus Walleij 	nb = gpiod_count(dev, "cs");
300031ed8ebcSAndy Shevchenko 	if (nb < 0) {
3001f3186dd8SLinus Walleij 		/* No GPIOs at all is fine, else return the error */
300231ed8ebcSAndy Shevchenko 		if (nb == -ENOENT)
3003f3186dd8SLinus Walleij 			return 0;
3004f3186dd8SLinus Walleij 		return nb;
300531ed8ebcSAndy Shevchenko 	}
300631ed8ebcSAndy Shevchenko 
300731ed8ebcSAndy Shevchenko 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
3008f3186dd8SLinus Walleij 
3009f3186dd8SLinus Walleij 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
3010f3186dd8SLinus Walleij 			  GFP_KERNEL);
3011f3186dd8SLinus Walleij 	if (!cs)
3012f3186dd8SLinus Walleij 		return -ENOMEM;
3013f3186dd8SLinus Walleij 	ctlr->cs_gpiods = cs;
3014f3186dd8SLinus Walleij 
3015f3186dd8SLinus Walleij 	for (i = 0; i < nb; i++) {
3016f3186dd8SLinus Walleij 		/*
3017f3186dd8SLinus Walleij 		 * Most chipselects are active low, the inverted
3018f3186dd8SLinus Walleij 		 * semantics are handled by special quirks in gpiolib,
3019f3186dd8SLinus Walleij 		 * so initializing them GPIOD_OUT_LOW here means
3020f3186dd8SLinus Walleij 		 * "unasserted", in most cases this will drive the physical
3021f3186dd8SLinus Walleij 		 * line high.
3022f3186dd8SLinus Walleij 		 */
3023f3186dd8SLinus Walleij 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
3024f3186dd8SLinus Walleij 						      GPIOD_OUT_LOW);
30251723fdecSGeert Uytterhoeven 		if (IS_ERR(cs[i]))
30261723fdecSGeert Uytterhoeven 			return PTR_ERR(cs[i]);
3027f3186dd8SLinus Walleij 
3028f3186dd8SLinus Walleij 		if (cs[i]) {
3029f3186dd8SLinus Walleij 			/*
3030f3186dd8SLinus Walleij 			 * If we find a CS GPIO, name it after the device and
3031f3186dd8SLinus Walleij 			 * chip select line.
3032f3186dd8SLinus Walleij 			 */
3033f3186dd8SLinus Walleij 			char *gpioname;
3034f3186dd8SLinus Walleij 
3035f3186dd8SLinus Walleij 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
3036f3186dd8SLinus Walleij 						  dev_name(dev), i);
3037f3186dd8SLinus Walleij 			if (!gpioname)
3038f3186dd8SLinus Walleij 				return -ENOMEM;
3039f3186dd8SLinus Walleij 			gpiod_set_consumer_name(cs[i], gpioname);
30407d93aecdSGeert Uytterhoeven 			num_cs_gpios++;
30417d93aecdSGeert Uytterhoeven 			continue;
3042f3186dd8SLinus Walleij 		}
30437d93aecdSGeert Uytterhoeven 
30447d93aecdSGeert Uytterhoeven 		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
30457d93aecdSGeert Uytterhoeven 			dev_err(dev, "Invalid native chip select %d\n", i);
30467d93aecdSGeert Uytterhoeven 			return -EINVAL;
30477d93aecdSGeert Uytterhoeven 		}
30487d93aecdSGeert Uytterhoeven 		native_cs_mask |= BIT(i);
30497d93aecdSGeert Uytterhoeven 	}
30507d93aecdSGeert Uytterhoeven 
3051f60d7270SAndy Shevchenko 	ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
3052dbaca8e5SAndy Shevchenko 
305382238d2cSAndy Shevchenko 	if ((ctlr->flags & SPI_CONTROLLER_GPIO_SS) && num_cs_gpios &&
3054dbaca8e5SAndy Shevchenko 	    ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
30557d93aecdSGeert Uytterhoeven 		dev_err(dev, "No unused native chip select available\n");
30567d93aecdSGeert Uytterhoeven 		return -EINVAL;
3057f3186dd8SLinus Walleij 	}
3058f3186dd8SLinus Walleij 
3059f3186dd8SLinus Walleij 	return 0;
3060f3186dd8SLinus Walleij }
3061f3186dd8SLinus Walleij 
spi_controller_check_ops(struct spi_controller * ctlr)3062bdf3a3b5SBoris Brezillon static int spi_controller_check_ops(struct spi_controller *ctlr)
3063bdf3a3b5SBoris Brezillon {
3064bdf3a3b5SBoris Brezillon 	/*
3065b5932f5cSBoris Brezillon 	 * The controller may implement only the high-level SPI-memory like
3066b5932f5cSBoris Brezillon 	 * operations if it does not support regular SPI transfers, and this is
3067b5932f5cSBoris Brezillon 	 * valid use case.
306876a85704SWilliam Zhang 	 * If ->mem_ops or ->mem_ops->exec_op is NULL, we request that at least
306976a85704SWilliam Zhang 	 * one of the ->transfer_xxx() method be implemented.
3070bdf3a3b5SBoris Brezillon 	 */
307120064c47SWilliam Zhang 	if (!ctlr->mem_ops || !ctlr->mem_ops->exec_op) {
307276a85704SWilliam Zhang 		if (!ctlr->transfer && !ctlr->transfer_one &&
3073b5932f5cSBoris Brezillon 		   !ctlr->transfer_one_message) {
3074b5932f5cSBoris Brezillon 			return -EINVAL;
3075b5932f5cSBoris Brezillon 		}
307676a85704SWilliam Zhang 	}
3077bdf3a3b5SBoris Brezillon 
3078bdf3a3b5SBoris Brezillon 	return 0;
3079bdf3a3b5SBoris Brezillon }
3080bdf3a3b5SBoris Brezillon 
3081440c4733SAndy Shevchenko /* Allocate dynamic bus number using Linux idr */
spi_controller_id_alloc(struct spi_controller * ctlr,int start,int end)3082440c4733SAndy Shevchenko static int spi_controller_id_alloc(struct spi_controller *ctlr, int start, int end)
3083440c4733SAndy Shevchenko {
3084440c4733SAndy Shevchenko 	int id;
3085440c4733SAndy Shevchenko 
3086440c4733SAndy Shevchenko 	mutex_lock(&board_lock);
3087440c4733SAndy Shevchenko 	id = idr_alloc(&spi_master_idr, ctlr, start, end, GFP_KERNEL);
3088440c4733SAndy Shevchenko 	mutex_unlock(&board_lock);
3089440c4733SAndy Shevchenko 	if (WARN(id < 0, "couldn't get idr"))
3090440c4733SAndy Shevchenko 		return id == -ENOSPC ? -EBUSY : id;
3091440c4733SAndy Shevchenko 	ctlr->bus_num = id;
3092440c4733SAndy Shevchenko 	return 0;
3093440c4733SAndy Shevchenko }
3094440c4733SAndy Shevchenko 
30958ae12a0dSDavid Brownell /**
30968caab75fSGeert Uytterhoeven  * spi_register_controller - register SPI master or slave controller
30978caab75fSGeert Uytterhoeven  * @ctlr: initialized master, originally from spi_alloc_master() or
30988caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
309933e34dc6SDavid Brownell  * Context: can sleep
31008ae12a0dSDavid Brownell  *
31018caab75fSGeert Uytterhoeven  * SPI controllers connect to their drivers using some non-SPI bus,
31028ae12a0dSDavid Brownell  * such as the platform bus.  The final stage of probe() in that code
31038caab75fSGeert Uytterhoeven  * includes calling spi_register_controller() to hook up to this SPI bus glue.
31048ae12a0dSDavid Brownell  *
31058ae12a0dSDavid Brownell  * SPI controllers use board specific (often SOC specific) bus numbers,
31068ae12a0dSDavid Brownell  * and board-specific addressing for SPI devices combines those numbers
31078ae12a0dSDavid Brownell  * with chip select numbers.  Since SPI does not directly support dynamic
31088ae12a0dSDavid Brownell  * device identification, boards need configuration tables telling which
31098ae12a0dSDavid Brownell  * chip is at which address.
31108ae12a0dSDavid Brownell  *
31118ae12a0dSDavid Brownell  * This must be called from context that can sleep.  It returns zero on
31128caab75fSGeert Uytterhoeven  * success, else a negative error code (dropping the controller's refcount).
31130c868461SDavid Brownell  * After a successful return, the caller is responsible for calling
31148caab75fSGeert Uytterhoeven  * spi_unregister_controller().
311597d56dc6SJavier Martinez Canillas  *
311697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
31178ae12a0dSDavid Brownell  */
spi_register_controller(struct spi_controller * ctlr)31188caab75fSGeert Uytterhoeven int spi_register_controller(struct spi_controller *ctlr)
31198ae12a0dSDavid Brownell {
31208caab75fSGeert Uytterhoeven 	struct device		*dev = ctlr->dev.parent;
31212b9603a0SFeng Tang 	struct boardinfo	*bi;
3122440c4733SAndy Shevchenko 	int			first_dynamic;
3123b93318a2SSergei Shtylyov 	int			status;
31248ae12a0dSDavid Brownell 
31250c868461SDavid Brownell 	if (!dev)
31260c868461SDavid Brownell 		return -ENODEV;
31270c868461SDavid Brownell 
3128bdf3a3b5SBoris Brezillon 	/*
3129bdf3a3b5SBoris Brezillon 	 * Make sure all necessary hooks are implemented before registering
3130bdf3a3b5SBoris Brezillon 	 * the SPI controller.
3131bdf3a3b5SBoris Brezillon 	 */
3132bdf3a3b5SBoris Brezillon 	status = spi_controller_check_ops(ctlr);
3133bdf3a3b5SBoris Brezillon 	if (status)
3134bdf3a3b5SBoris Brezillon 		return status;
3135bdf3a3b5SBoris Brezillon 
3136440c4733SAndy Shevchenko 	if (ctlr->bus_num < 0)
3137440c4733SAndy Shevchenko 		ctlr->bus_num = of_alias_get_id(ctlr->dev.of_node, "spi");
313804b2d03aSGeert Uytterhoeven 	if (ctlr->bus_num >= 0) {
313995c8222fSDavid Jander 		/* Devices with a fixed bus num must check-in with the num */
3140440c4733SAndy Shevchenko 		status = spi_controller_id_alloc(ctlr, ctlr->bus_num, ctlr->bus_num + 1);
3141440c4733SAndy Shevchenko 		if (status)
3142440c4733SAndy Shevchenko 			return status;
31439b61e302SSuniel Mahesh 	}
31448caab75fSGeert Uytterhoeven 	if (ctlr->bus_num < 0) {
314542bdd706SLucas Stach 		first_dynamic = of_alias_get_highest_id("spi");
314642bdd706SLucas Stach 		if (first_dynamic < 0)
314742bdd706SLucas Stach 			first_dynamic = 0;
314842bdd706SLucas Stach 		else
314942bdd706SLucas Stach 			first_dynamic++;
315042bdd706SLucas Stach 
3151440c4733SAndy Shevchenko 		status = spi_controller_id_alloc(ctlr, first_dynamic, 0);
3152440c4733SAndy Shevchenko 		if (status)
3153440c4733SAndy Shevchenko 			return status;
31548ae12a0dSDavid Brownell 	}
31558caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
31568caab75fSGeert Uytterhoeven 	init_completion(&ctlr->xfer_completion);
315769fa9590SDavid Jander 	init_completion(&ctlr->cur_msg_completion);
31588caab75fSGeert Uytterhoeven 	if (!ctlr->max_dma_len)
31598caab75fSGeert Uytterhoeven 		ctlr->max_dma_len = INT_MAX;
3160cf32b71eSErnst Schwab 
3161350de7ceSAndy Shevchenko 	/*
3162350de7ceSAndy Shevchenko 	 * Register the device, then userspace will see it.
3163350de7ceSAndy Shevchenko 	 * Registration fails if the bus ID is in use.
31648ae12a0dSDavid Brownell 	 */
31658caab75fSGeert Uytterhoeven 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
31660a919ae4SAndrey Smirnov 
3167f48dc6b9SLinus Walleij 	if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
31680a919ae4SAndrey Smirnov 		status = spi_get_gpio_descs(ctlr);
31690a919ae4SAndrey Smirnov 		if (status)
3170f9981d4fSAaro Koskinen 			goto free_bus_id;
31710a919ae4SAndrey Smirnov 		/*
31720a919ae4SAndrey Smirnov 		 * A controller using GPIO descriptors always
31730a919ae4SAndrey Smirnov 		 * supports SPI_CS_HIGH if need be.
31740a919ae4SAndrey Smirnov 		 */
31750a919ae4SAndrey Smirnov 		ctlr->mode_bits |= SPI_CS_HIGH;
31760a919ae4SAndrey Smirnov 	}
31770a919ae4SAndrey Smirnov 
3178f9481b08STudor Ambarus 	/*
3179f9481b08STudor Ambarus 	 * Even if it's just one always-selected device, there must
3180f9481b08STudor Ambarus 	 * be at least one chipselect.
3181f9481b08STudor Ambarus 	 */
3182f9981d4fSAaro Koskinen 	if (!ctlr->num_chipselect) {
3183f9981d4fSAaro Koskinen 		status = -EINVAL;
3184f9981d4fSAaro Koskinen 		goto free_bus_id;
3185f9981d4fSAaro Koskinen 	}
3186f9481b08STudor Ambarus 
318795c8222fSDavid Jander 	/* Setting last_cs to -1 means no chip selected */
31886bb477dfSYun Zhou 	ctlr->last_cs = -1;
31896bb477dfSYun Zhou 
31908caab75fSGeert Uytterhoeven 	status = device_add(&ctlr->dev);
3191f9981d4fSAaro Koskinen 	if (status < 0)
3192f9981d4fSAaro Koskinen 		goto free_bus_id;
31939b61e302SSuniel Mahesh 	dev_dbg(dev, "registered %s %s\n",
31948caab75fSGeert Uytterhoeven 			spi_controller_is_slave(ctlr) ? "slave" : "master",
31959b61e302SSuniel Mahesh 			dev_name(&ctlr->dev));
31968ae12a0dSDavid Brownell 
3197b5932f5cSBoris Brezillon 	/*
3198b5932f5cSBoris Brezillon 	 * If we're using a queued driver, start the queue. Note that we don't
3199b5932f5cSBoris Brezillon 	 * need the queueing logic if the driver is only supporting high-level
3200b5932f5cSBoris Brezillon 	 * memory operations.
3201b5932f5cSBoris Brezillon 	 */
3202b5932f5cSBoris Brezillon 	if (ctlr->transfer) {
32038caab75fSGeert Uytterhoeven 		dev_info(dev, "controller is unqueued, this is deprecated\n");
3204b5932f5cSBoris Brezillon 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
32058caab75fSGeert Uytterhoeven 		status = spi_controller_initialize_queue(ctlr);
3206ffbbdd21SLinus Walleij 		if (status) {
32078caab75fSGeert Uytterhoeven 			device_del(&ctlr->dev);
3208f9981d4fSAaro Koskinen 			goto free_bus_id;
3209ffbbdd21SLinus Walleij 		}
3210ffbbdd21SLinus Walleij 	}
321195c8222fSDavid Jander 	/* Add statistics */
32126598b91bSDavid Jander 	ctlr->pcpu_statistics = spi_alloc_pcpu_stats(dev);
32136598b91bSDavid Jander 	if (!ctlr->pcpu_statistics) {
32146598b91bSDavid Jander 		dev_err(dev, "Error allocating per-cpu statistics\n");
3215d52b095bSDan Carpenter 		status = -ENOMEM;
32166598b91bSDavid Jander 		goto destroy_queue;
32176598b91bSDavid Jander 	}
3218ffbbdd21SLinus Walleij 
32192b9603a0SFeng Tang 	mutex_lock(&board_lock);
32208caab75fSGeert Uytterhoeven 	list_add_tail(&ctlr->list, &spi_controller_list);
32212b9603a0SFeng Tang 	list_for_each_entry(bi, &board_list, list)
32228caab75fSGeert Uytterhoeven 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
32232b9603a0SFeng Tang 	mutex_unlock(&board_lock);
32242b9603a0SFeng Tang 
322564bee4d2SMika Westerberg 	/* Register devices from the device tree and ACPI */
32268caab75fSGeert Uytterhoeven 	of_register_spi_devices(ctlr);
32278caab75fSGeert Uytterhoeven 	acpi_register_spi_devices(ctlr);
3228f9981d4fSAaro Koskinen 	return status;
3229f9981d4fSAaro Koskinen 
32306598b91bSDavid Jander destroy_queue:
32316598b91bSDavid Jander 	spi_destroy_queue(ctlr);
3232f9981d4fSAaro Koskinen free_bus_id:
3233f9981d4fSAaro Koskinen 	mutex_lock(&board_lock);
3234f9981d4fSAaro Koskinen 	idr_remove(&spi_master_idr, ctlr->bus_num);
3235f9981d4fSAaro Koskinen 	mutex_unlock(&board_lock);
32368ae12a0dSDavid Brownell 	return status;
32378ae12a0dSDavid Brownell }
32388caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_register_controller);
32398ae12a0dSDavid Brownell 
devm_spi_unregister(struct device * dev,void * res)324043cc5a0aSYang Yingliang static void devm_spi_unregister(struct device *dev, void *res)
3241666d5b4cSMark Brown {
324243cc5a0aSYang Yingliang 	spi_unregister_controller(*(struct spi_controller **)res);
3243666d5b4cSMark Brown }
3244666d5b4cSMark Brown 
3245666d5b4cSMark Brown /**
32468caab75fSGeert Uytterhoeven  * devm_spi_register_controller - register managed SPI master or slave
32478caab75fSGeert Uytterhoeven  *	controller
32488caab75fSGeert Uytterhoeven  * @dev:    device managing SPI controller
32498caab75fSGeert Uytterhoeven  * @ctlr: initialized controller, originally from spi_alloc_master() or
32508caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
3251666d5b4cSMark Brown  * Context: can sleep
3252666d5b4cSMark Brown  *
32538caab75fSGeert Uytterhoeven  * Register a SPI device as with spi_register_controller() which will
325468b892f1SJohan Hovold  * automatically be unregistered and freed.
325597d56dc6SJavier Martinez Canillas  *
325697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3257666d5b4cSMark Brown  */
devm_spi_register_controller(struct device * dev,struct spi_controller * ctlr)32588caab75fSGeert Uytterhoeven int devm_spi_register_controller(struct device *dev,
32598caab75fSGeert Uytterhoeven 				 struct spi_controller *ctlr)
3260666d5b4cSMark Brown {
326143cc5a0aSYang Yingliang 	struct spi_controller **ptr;
3262666d5b4cSMark Brown 	int ret;
3263666d5b4cSMark Brown 
326443cc5a0aSYang Yingliang 	ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
326543cc5a0aSYang Yingliang 	if (!ptr)
326643cc5a0aSYang Yingliang 		return -ENOMEM;
326759ebbe40STian Tao 
326843cc5a0aSYang Yingliang 	ret = spi_register_controller(ctlr);
326943cc5a0aSYang Yingliang 	if (!ret) {
327043cc5a0aSYang Yingliang 		*ptr = ctlr;
327143cc5a0aSYang Yingliang 		devres_add(dev, ptr);
327243cc5a0aSYang Yingliang 	} else {
327343cc5a0aSYang Yingliang 		devres_free(ptr);
327443cc5a0aSYang Yingliang 	}
327543cc5a0aSYang Yingliang 
327643cc5a0aSYang Yingliang 	return ret;
3277666d5b4cSMark Brown }
32788caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3279666d5b4cSMark Brown 
__unregister(struct device * dev,void * null)328034860089SDavid Lamparter static int __unregister(struct device *dev, void *null)
32818ae12a0dSDavid Brownell {
32820c868461SDavid Brownell 	spi_unregister_device(to_spi_device(dev));
32838ae12a0dSDavid Brownell 	return 0;
32848ae12a0dSDavid Brownell }
32858ae12a0dSDavid Brownell 
32868ae12a0dSDavid Brownell /**
32878caab75fSGeert Uytterhoeven  * spi_unregister_controller - unregister SPI master or slave controller
32888caab75fSGeert Uytterhoeven  * @ctlr: the controller being unregistered
328933e34dc6SDavid Brownell  * Context: can sleep
32908ae12a0dSDavid Brownell  *
32918caab75fSGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
32928ae12a0dSDavid Brownell  * only ones directly touching chip registers.
32938ae12a0dSDavid Brownell  *
32948ae12a0dSDavid Brownell  * This must be called from context that can sleep.
329568b892f1SJohan Hovold  *
329668b892f1SJohan Hovold  * Note that this function also drops a reference to the controller.
32978ae12a0dSDavid Brownell  */
spi_unregister_controller(struct spi_controller * ctlr)32988caab75fSGeert Uytterhoeven void spi_unregister_controller(struct spi_controller *ctlr)
32998ae12a0dSDavid Brownell {
33009b61e302SSuniel Mahesh 	struct spi_controller *found;
330167f7b278SJohan Hovold 	int id = ctlr->bus_num;
330289fc9a1aSJeff Garzik 
3303ddf75be4SLukas Wunner 	/* Prevent addition of new devices, unregister existing ones */
3304ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
33056098475dSMark Brown 		mutex_lock(&ctlr->add_lock);
3306ddf75be4SLukas Wunner 
330784855678SLukas Wunner 	device_for_each_child(&ctlr->dev, NULL, __unregister);
330884855678SLukas Wunner 
33099b61e302SSuniel Mahesh 	/* First make sure that this controller was ever added */
33109b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
331167f7b278SJohan Hovold 	found = idr_find(&spi_master_idr, id);
33129b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
33138caab75fSGeert Uytterhoeven 	if (ctlr->queued) {
33148caab75fSGeert Uytterhoeven 		if (spi_destroy_queue(ctlr))
33158caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue remove failed\n");
3316ffbbdd21SLinus Walleij 	}
33172b9603a0SFeng Tang 	mutex_lock(&board_lock);
33188caab75fSGeert Uytterhoeven 	list_del(&ctlr->list);
33192b9603a0SFeng Tang 	mutex_unlock(&board_lock);
33202b9603a0SFeng Tang 
33215e844cc3SLukas Wunner 	device_del(&ctlr->dev);
33225e844cc3SLukas Wunner 
332395c8222fSDavid Jander 	/* Free bus id */
33249b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
3325613bd1eaSJarkko Nikula 	if (found == ctlr)
332667f7b278SJohan Hovold 		idr_remove(&spi_master_idr, id);
33279b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
3328ddf75be4SLukas Wunner 
3329ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
33306098475dSMark Brown 		mutex_unlock(&ctlr->add_lock);
33316c53b45cSMichael Walle 
3332702ca026SAndy Shevchenko 	/*
3333702ca026SAndy Shevchenko 	 * Release the last reference on the controller if its driver
33346c53b45cSMichael Walle 	 * has not yet been converted to devm_spi_alloc_master/slave().
33356c53b45cSMichael Walle 	 */
33366c53b45cSMichael Walle 	if (!ctlr->devm_allocated)
33376c53b45cSMichael Walle 		put_device(&ctlr->dev);
33388ae12a0dSDavid Brownell }
33398caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_controller);
33408ae12a0dSDavid Brownell 
__spi_check_suspended(const struct spi_controller * ctlr)334196474ea4SMark Hasemeyer static inline int __spi_check_suspended(const struct spi_controller *ctlr)
334296474ea4SMark Hasemeyer {
334396474ea4SMark Hasemeyer 	return ctlr->flags & SPI_CONTROLLER_SUSPENDED ? -ESHUTDOWN : 0;
334496474ea4SMark Hasemeyer }
334596474ea4SMark Hasemeyer 
__spi_mark_suspended(struct spi_controller * ctlr)334696474ea4SMark Hasemeyer static inline void __spi_mark_suspended(struct spi_controller *ctlr)
334796474ea4SMark Hasemeyer {
334896474ea4SMark Hasemeyer 	mutex_lock(&ctlr->bus_lock_mutex);
334996474ea4SMark Hasemeyer 	ctlr->flags |= SPI_CONTROLLER_SUSPENDED;
335096474ea4SMark Hasemeyer 	mutex_unlock(&ctlr->bus_lock_mutex);
335196474ea4SMark Hasemeyer }
335296474ea4SMark Hasemeyer 
__spi_mark_resumed(struct spi_controller * ctlr)335396474ea4SMark Hasemeyer static inline void __spi_mark_resumed(struct spi_controller *ctlr)
335496474ea4SMark Hasemeyer {
335596474ea4SMark Hasemeyer 	mutex_lock(&ctlr->bus_lock_mutex);
335696474ea4SMark Hasemeyer 	ctlr->flags &= ~SPI_CONTROLLER_SUSPENDED;
335796474ea4SMark Hasemeyer 	mutex_unlock(&ctlr->bus_lock_mutex);
335896474ea4SMark Hasemeyer }
335996474ea4SMark Hasemeyer 
spi_controller_suspend(struct spi_controller * ctlr)33608caab75fSGeert Uytterhoeven int spi_controller_suspend(struct spi_controller *ctlr)
3361ffbbdd21SLinus Walleij {
336296474ea4SMark Hasemeyer 	int ret = 0;
3363ffbbdd21SLinus Walleij 
33648caab75fSGeert Uytterhoeven 	/* Basically no-ops for non-queued controllers */
336596474ea4SMark Hasemeyer 	if (ctlr->queued) {
33668caab75fSGeert Uytterhoeven 		ret = spi_stop_queue(ctlr);
3367ffbbdd21SLinus Walleij 		if (ret)
33688caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue stop failed\n");
336996474ea4SMark Hasemeyer 	}
3370ffbbdd21SLinus Walleij 
337196474ea4SMark Hasemeyer 	__spi_mark_suspended(ctlr);
3372ffbbdd21SLinus Walleij 	return ret;
3373ffbbdd21SLinus Walleij }
33748caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_suspend);
3375ffbbdd21SLinus Walleij 
spi_controller_resume(struct spi_controller * ctlr)33768caab75fSGeert Uytterhoeven int spi_controller_resume(struct spi_controller *ctlr)
3377ffbbdd21SLinus Walleij {
337896474ea4SMark Hasemeyer 	int ret = 0;
3379ffbbdd21SLinus Walleij 
338096474ea4SMark Hasemeyer 	__spi_mark_resumed(ctlr);
3381ffbbdd21SLinus Walleij 
338296474ea4SMark Hasemeyer 	if (ctlr->queued) {
33838caab75fSGeert Uytterhoeven 		ret = spi_start_queue(ctlr);
3384ffbbdd21SLinus Walleij 		if (ret)
33858caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue restart failed\n");
338696474ea4SMark Hasemeyer 	}
3387ffbbdd21SLinus Walleij 	return ret;
3388ffbbdd21SLinus Walleij }
33898caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_resume);
3390ffbbdd21SLinus Walleij 
33918ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
33928ae12a0dSDavid Brownell 
3393523baf5aSMartin Sperl /* Core methods for spi_message alterations */
3394523baf5aSMartin Sperl 
__spi_replace_transfers_release(struct spi_controller * ctlr,struct spi_message * msg,void * res)33958caab75fSGeert Uytterhoeven static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3396523baf5aSMartin Sperl 					    struct spi_message *msg,
3397523baf5aSMartin Sperl 					    void *res)
3398523baf5aSMartin Sperl {
3399523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer = res;
3400523baf5aSMartin Sperl 	size_t i;
3401523baf5aSMartin Sperl 
340295c8222fSDavid Jander 	/* Call extra callback if requested */
3403523baf5aSMartin Sperl 	if (rxfer->release)
34048caab75fSGeert Uytterhoeven 		rxfer->release(ctlr, msg, res);
3405523baf5aSMartin Sperl 
340695c8222fSDavid Jander 	/* Insert replaced transfers back into the message */
3407523baf5aSMartin Sperl 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3408523baf5aSMartin Sperl 
340995c8222fSDavid Jander 	/* Remove the formerly inserted entries */
3410523baf5aSMartin Sperl 	for (i = 0; i < rxfer->inserted; i++)
3411523baf5aSMartin Sperl 		list_del(&rxfer->inserted_transfers[i].transfer_list);
3412523baf5aSMartin Sperl }
3413523baf5aSMartin Sperl 
3414523baf5aSMartin Sperl /**
3415523baf5aSMartin Sperl  * spi_replace_transfers - replace transfers with several transfers
3416523baf5aSMartin Sperl  *                         and register change with spi_message.resources
3417523baf5aSMartin Sperl  * @msg:           the spi_message we work upon
3418523baf5aSMartin Sperl  * @xfer_first:    the first spi_transfer we want to replace
3419523baf5aSMartin Sperl  * @remove:        number of transfers to remove
3420523baf5aSMartin Sperl  * @insert:        the number of transfers we want to insert instead
3421523baf5aSMartin Sperl  * @release:       extra release code necessary in some circumstances
3422523baf5aSMartin Sperl  * @extradatasize: extra data to allocate (with alignment guarantees
3423523baf5aSMartin Sperl  *                 of struct @spi_transfer)
342405885397SMartin Sperl  * @gfp:           gfp flags
3425523baf5aSMartin Sperl  *
3426523baf5aSMartin Sperl  * Returns: pointer to @spi_replaced_transfers,
3427523baf5aSMartin Sperl  *          PTR_ERR(...) in case of errors.
3428523baf5aSMartin Sperl  */
spi_replace_transfers(struct spi_message * msg,struct spi_transfer * xfer_first,size_t remove,size_t insert,spi_replaced_release_t release,size_t extradatasize,gfp_t gfp)3429da21fde0SUwe Kleine-König static struct spi_replaced_transfers *spi_replace_transfers(
3430523baf5aSMartin Sperl 	struct spi_message *msg,
3431523baf5aSMartin Sperl 	struct spi_transfer *xfer_first,
3432523baf5aSMartin Sperl 	size_t remove,
3433523baf5aSMartin Sperl 	size_t insert,
3434523baf5aSMartin Sperl 	spi_replaced_release_t release,
3435523baf5aSMartin Sperl 	size_t extradatasize,
3436523baf5aSMartin Sperl 	gfp_t gfp)
3437523baf5aSMartin Sperl {
3438523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer;
3439523baf5aSMartin Sperl 	struct spi_transfer *xfer;
3440523baf5aSMartin Sperl 	size_t i;
3441523baf5aSMartin Sperl 
344295c8222fSDavid Jander 	/* Allocate the structure using spi_res */
3443523baf5aSMartin Sperl 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3444aef97522SGustavo A. R. Silva 			      struct_size(rxfer, inserted_transfers, insert)
3445523baf5aSMartin Sperl 			      + extradatasize,
3446523baf5aSMartin Sperl 			      gfp);
3447523baf5aSMartin Sperl 	if (!rxfer)
3448523baf5aSMartin Sperl 		return ERR_PTR(-ENOMEM);
3449523baf5aSMartin Sperl 
345095c8222fSDavid Jander 	/* The release code to invoke before running the generic release */
3451523baf5aSMartin Sperl 	rxfer->release = release;
3452523baf5aSMartin Sperl 
345395c8222fSDavid Jander 	/* Assign extradata */
3454523baf5aSMartin Sperl 	if (extradatasize)
3455523baf5aSMartin Sperl 		rxfer->extradata =
3456523baf5aSMartin Sperl 			&rxfer->inserted_transfers[insert];
3457523baf5aSMartin Sperl 
345895c8222fSDavid Jander 	/* Init the replaced_transfers list */
3459523baf5aSMartin Sperl 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3460523baf5aSMartin Sperl 
3461350de7ceSAndy Shevchenko 	/*
3462350de7ceSAndy Shevchenko 	 * Assign the list_entry after which we should reinsert
3463523baf5aSMartin Sperl 	 * the @replaced_transfers - it may be spi_message.messages!
3464523baf5aSMartin Sperl 	 */
3465523baf5aSMartin Sperl 	rxfer->replaced_after = xfer_first->transfer_list.prev;
3466523baf5aSMartin Sperl 
346795c8222fSDavid Jander 	/* Remove the requested number of transfers */
3468523baf5aSMartin Sperl 	for (i = 0; i < remove; i++) {
3469350de7ceSAndy Shevchenko 		/*
3470350de7ceSAndy Shevchenko 		 * If the entry after replaced_after it is msg->transfers
3471523baf5aSMartin Sperl 		 * then we have been requested to remove more transfers
3472350de7ceSAndy Shevchenko 		 * than are in the list.
3473523baf5aSMartin Sperl 		 */
3474523baf5aSMartin Sperl 		if (rxfer->replaced_after->next == &msg->transfers) {
3475523baf5aSMartin Sperl 			dev_err(&msg->spi->dev,
3476523baf5aSMartin Sperl 				"requested to remove more spi_transfers than are available\n");
347795c8222fSDavid Jander 			/* Insert replaced transfers back into the message */
3478523baf5aSMartin Sperl 			list_splice(&rxfer->replaced_transfers,
3479523baf5aSMartin Sperl 				    rxfer->replaced_after);
3480523baf5aSMartin Sperl 
348195c8222fSDavid Jander 			/* Free the spi_replace_transfer structure... */
3482523baf5aSMartin Sperl 			spi_res_free(rxfer);
3483523baf5aSMartin Sperl 
348495c8222fSDavid Jander 			/* ...and return with an error */
3485523baf5aSMartin Sperl 			return ERR_PTR(-EINVAL);
3486523baf5aSMartin Sperl 		}
3487523baf5aSMartin Sperl 
3488350de7ceSAndy Shevchenko 		/*
3489350de7ceSAndy Shevchenko 		 * Remove the entry after replaced_after from list of
3490350de7ceSAndy Shevchenko 		 * transfers and add it to list of replaced_transfers.
3491523baf5aSMartin Sperl 		 */
3492523baf5aSMartin Sperl 		list_move_tail(rxfer->replaced_after->next,
3493523baf5aSMartin Sperl 			       &rxfer->replaced_transfers);
3494523baf5aSMartin Sperl 	}
3495523baf5aSMartin Sperl 
3496350de7ceSAndy Shevchenko 	/*
3497350de7ceSAndy Shevchenko 	 * Create copy of the given xfer with identical settings
3498350de7ceSAndy Shevchenko 	 * based on the first transfer to get removed.
3499523baf5aSMartin Sperl 	 */
3500523baf5aSMartin Sperl 	for (i = 0; i < insert; i++) {
350195c8222fSDavid Jander 		/* We need to run in reverse order */
3502523baf5aSMartin Sperl 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3503523baf5aSMartin Sperl 
350495c8222fSDavid Jander 		/* Copy all spi_transfer data */
3505523baf5aSMartin Sperl 		memcpy(xfer, xfer_first, sizeof(*xfer));
3506523baf5aSMartin Sperl 
350795c8222fSDavid Jander 		/* Add to list */
3508523baf5aSMartin Sperl 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3509523baf5aSMartin Sperl 
351095c8222fSDavid Jander 		/* Clear cs_change and delay for all but the last */
3511523baf5aSMartin Sperl 		if (i) {
3512523baf5aSMartin Sperl 			xfer->cs_change = false;
3513bebcfd27SAlexandru Ardelean 			xfer->delay.value = 0;
3514523baf5aSMartin Sperl 		}
3515523baf5aSMartin Sperl 	}
3516523baf5aSMartin Sperl 
351795c8222fSDavid Jander 	/* Set up inserted... */
3518523baf5aSMartin Sperl 	rxfer->inserted = insert;
3519523baf5aSMartin Sperl 
352095c8222fSDavid Jander 	/* ...and register it with spi_res/spi_message */
3521523baf5aSMartin Sperl 	spi_res_add(msg, rxfer);
3522523baf5aSMartin Sperl 
3523523baf5aSMartin Sperl 	return rxfer;
3524523baf5aSMartin Sperl }
3525523baf5aSMartin Sperl 
__spi_split_transfer_maxsize(struct spi_controller * ctlr,struct spi_message * msg,struct spi_transfer ** xferp,size_t maxsize,gfp_t gfp)35268caab75fSGeert Uytterhoeven static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3527d9f12122SMartin Sperl 					struct spi_message *msg,
3528d9f12122SMartin Sperl 					struct spi_transfer **xferp,
3529d9f12122SMartin Sperl 					size_t maxsize,
3530d9f12122SMartin Sperl 					gfp_t gfp)
3531d9f12122SMartin Sperl {
3532d9f12122SMartin Sperl 	struct spi_transfer *xfer = *xferp, *xfers;
3533d9f12122SMartin Sperl 	struct spi_replaced_transfers *srt;
3534d9f12122SMartin Sperl 	size_t offset;
3535d9f12122SMartin Sperl 	size_t count, i;
3536d9f12122SMartin Sperl 
353795c8222fSDavid Jander 	/* Calculate how many we have to replace */
3538d9f12122SMartin Sperl 	count = DIV_ROUND_UP(xfer->len, maxsize);
3539d9f12122SMartin Sperl 
354095c8222fSDavid Jander 	/* Create replacement */
3541d9f12122SMartin Sperl 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3542657d32efSDan Carpenter 	if (IS_ERR(srt))
3543657d32efSDan Carpenter 		return PTR_ERR(srt);
3544d9f12122SMartin Sperl 	xfers = srt->inserted_transfers;
3545d9f12122SMartin Sperl 
3546350de7ceSAndy Shevchenko 	/*
3547350de7ceSAndy Shevchenko 	 * Now handle each of those newly inserted spi_transfers.
3548350de7ceSAndy Shevchenko 	 * Note that the replacements spi_transfers all are preset
3549d9f12122SMartin Sperl 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3550d9f12122SMartin Sperl 	 * are all identical (as well as most others)
3551d9f12122SMartin Sperl 	 * so we just have to fix up len and the pointers.
3552d9f12122SMartin Sperl 	 *
3553350de7ceSAndy Shevchenko 	 * This also includes support for the depreciated
3554350de7ceSAndy Shevchenko 	 * spi_message.is_dma_mapped interface.
3555d9f12122SMartin Sperl 	 */
3556d9f12122SMartin Sperl 
3557350de7ceSAndy Shevchenko 	/*
3558350de7ceSAndy Shevchenko 	 * The first transfer just needs the length modified, so we
3559350de7ceSAndy Shevchenko 	 * run it outside the loop.
3560d9f12122SMartin Sperl 	 */
3561c8dab77aSFabio Estevam 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3562d9f12122SMartin Sperl 
356395c8222fSDavid Jander 	/* All the others need rx_buf/tx_buf also set */
3564d9f12122SMartin Sperl 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3565702ca026SAndy Shevchenko 		/* Update rx_buf, tx_buf and DMA */
3566d9f12122SMartin Sperl 		if (xfers[i].rx_buf)
3567d9f12122SMartin Sperl 			xfers[i].rx_buf += offset;
3568d9f12122SMartin Sperl 		if (xfers[i].rx_dma)
3569d9f12122SMartin Sperl 			xfers[i].rx_dma += offset;
3570d9f12122SMartin Sperl 		if (xfers[i].tx_buf)
3571d9f12122SMartin Sperl 			xfers[i].tx_buf += offset;
3572d9f12122SMartin Sperl 		if (xfers[i].tx_dma)
3573d9f12122SMartin Sperl 			xfers[i].tx_dma += offset;
3574d9f12122SMartin Sperl 
357595c8222fSDavid Jander 		/* Update length */
3576d9f12122SMartin Sperl 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3577d9f12122SMartin Sperl 	}
3578d9f12122SMartin Sperl 
3579350de7ceSAndy Shevchenko 	/*
3580350de7ceSAndy Shevchenko 	 * We set up xferp to the last entry we have inserted,
3581350de7ceSAndy Shevchenko 	 * so that we skip those already split transfers.
3582d9f12122SMartin Sperl 	 */
3583d9f12122SMartin Sperl 	*xferp = &xfers[count - 1];
3584d9f12122SMartin Sperl 
358595c8222fSDavid Jander 	/* Increment statistics counters */
35866598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics,
3587d9f12122SMartin Sperl 				       transfers_split_maxsize);
35886598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics,
3589d9f12122SMartin Sperl 				       transfers_split_maxsize);
3590d9f12122SMartin Sperl 
3591d9f12122SMartin Sperl 	return 0;
3592d9f12122SMartin Sperl }
3593d9f12122SMartin Sperl 
3594d9f12122SMartin Sperl /**
3595ce2424d7SMauro Carvalho Chehab  * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3596d9f12122SMartin Sperl  *                               when an individual transfer exceeds a
3597d9f12122SMartin Sperl  *                               certain size
35988caab75fSGeert Uytterhoeven  * @ctlr:    the @spi_controller for this transfer
35993700ce95SMasanari Iida  * @msg:   the @spi_message to transform
36003700ce95SMasanari Iida  * @maxsize:  the maximum when to apply this
360110f11a22SJavier Martinez Canillas  * @gfp: GFP allocation flags
3602d9f12122SMartin Sperl  *
3603d9f12122SMartin Sperl  * Return: status of transformation
3604d9f12122SMartin Sperl  */
spi_split_transfers_maxsize(struct spi_controller * ctlr,struct spi_message * msg,size_t maxsize,gfp_t gfp)36058caab75fSGeert Uytterhoeven int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3606d9f12122SMartin Sperl 				struct spi_message *msg,
3607d9f12122SMartin Sperl 				size_t maxsize,
3608d9f12122SMartin Sperl 				gfp_t gfp)
3609d9f12122SMartin Sperl {
3610d9f12122SMartin Sperl 	struct spi_transfer *xfer;
3611d9f12122SMartin Sperl 	int ret;
3612d9f12122SMartin Sperl 
3613350de7ceSAndy Shevchenko 	/*
3614350de7ceSAndy Shevchenko 	 * Iterate over the transfer_list,
3615d9f12122SMartin Sperl 	 * but note that xfer is advanced to the last transfer inserted
3616d9f12122SMartin Sperl 	 * to avoid checking sizes again unnecessarily (also xfer does
3617350de7ceSAndy Shevchenko 	 * potentially belong to a different list by the time the
3618350de7ceSAndy Shevchenko 	 * replacement has happened).
3619d9f12122SMartin Sperl 	 */
3620d9f12122SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3621d9f12122SMartin Sperl 		if (xfer->len > maxsize) {
36228caab75fSGeert Uytterhoeven 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
36238caab75fSGeert Uytterhoeven 							   maxsize, gfp);
3624d9f12122SMartin Sperl 			if (ret)
3625d9f12122SMartin Sperl 				return ret;
3626d9f12122SMartin Sperl 		}
3627d9f12122SMartin Sperl 	}
3628d9f12122SMartin Sperl 
3629d9f12122SMartin Sperl 	return 0;
3630d9f12122SMartin Sperl }
3631d9f12122SMartin Sperl EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
36328ae12a0dSDavid Brownell 
3633027781f3SLeonard Göhrs 
3634027781f3SLeonard Göhrs /**
3635702ca026SAndy Shevchenko  * spi_split_transfers_maxwords - split SPI transfers into multiple transfers
3636027781f3SLeonard Göhrs  *                                when an individual transfer exceeds a
3637027781f3SLeonard Göhrs  *                                certain number of SPI words
3638027781f3SLeonard Göhrs  * @ctlr:     the @spi_controller for this transfer
3639027781f3SLeonard Göhrs  * @msg:      the @spi_message to transform
3640027781f3SLeonard Göhrs  * @maxwords: the number of words to limit each transfer to
3641027781f3SLeonard Göhrs  * @gfp:      GFP allocation flags
3642027781f3SLeonard Göhrs  *
3643027781f3SLeonard Göhrs  * Return: status of transformation
3644027781f3SLeonard Göhrs  */
spi_split_transfers_maxwords(struct spi_controller * ctlr,struct spi_message * msg,size_t maxwords,gfp_t gfp)3645027781f3SLeonard Göhrs int spi_split_transfers_maxwords(struct spi_controller *ctlr,
3646027781f3SLeonard Göhrs 				 struct spi_message *msg,
3647027781f3SLeonard Göhrs 				 size_t maxwords,
3648027781f3SLeonard Göhrs 				 gfp_t gfp)
3649027781f3SLeonard Göhrs {
3650027781f3SLeonard Göhrs 	struct spi_transfer *xfer;
3651027781f3SLeonard Göhrs 
3652027781f3SLeonard Göhrs 	/*
3653027781f3SLeonard Göhrs 	 * Iterate over the transfer_list,
3654027781f3SLeonard Göhrs 	 * but note that xfer is advanced to the last transfer inserted
3655027781f3SLeonard Göhrs 	 * to avoid checking sizes again unnecessarily (also xfer does
3656027781f3SLeonard Göhrs 	 * potentially belong to a different list by the time the
3657027781f3SLeonard Göhrs 	 * replacement has happened).
3658027781f3SLeonard Göhrs 	 */
3659027781f3SLeonard Göhrs 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3660027781f3SLeonard Göhrs 		size_t maxsize;
3661027781f3SLeonard Göhrs 		int ret;
3662027781f3SLeonard Göhrs 
36632b308e71SAndy Shevchenko 		maxsize = maxwords * roundup_pow_of_two(BITS_TO_BYTES(xfer->bits_per_word));
3664027781f3SLeonard Göhrs 		if (xfer->len > maxsize) {
3665027781f3SLeonard Göhrs 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3666027781f3SLeonard Göhrs 							   maxsize, gfp);
3667027781f3SLeonard Göhrs 			if (ret)
3668027781f3SLeonard Göhrs 				return ret;
3669027781f3SLeonard Göhrs 		}
3670027781f3SLeonard Göhrs 	}
3671027781f3SLeonard Göhrs 
3672027781f3SLeonard Göhrs 	return 0;
3673027781f3SLeonard Göhrs }
3674027781f3SLeonard Göhrs EXPORT_SYMBOL_GPL(spi_split_transfers_maxwords);
3675027781f3SLeonard Göhrs 
36768ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
36778ae12a0dSDavid Brownell 
3678702ca026SAndy Shevchenko /*
3679702ca026SAndy Shevchenko  * Core methods for SPI controller protocol drivers. Some of the
36807d077197SDavid Brownell  * other core methods are currently defined as inline functions.
36817d077197SDavid Brownell  */
36827d077197SDavid Brownell 
__spi_validate_bits_per_word(struct spi_controller * ctlr,u8 bits_per_word)36838caab75fSGeert Uytterhoeven static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
36848caab75fSGeert Uytterhoeven 					u8 bits_per_word)
368563ab645fSStefan Brüns {
36868caab75fSGeert Uytterhoeven 	if (ctlr->bits_per_word_mask) {
368763ab645fSStefan Brüns 		/* Only 32 bits fit in the mask */
368863ab645fSStefan Brüns 		if (bits_per_word > 32)
368963ab645fSStefan Brüns 			return -EINVAL;
36908caab75fSGeert Uytterhoeven 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
369163ab645fSStefan Brüns 			return -EINVAL;
369263ab645fSStefan Brüns 	}
369363ab645fSStefan Brüns 
369463ab645fSStefan Brüns 	return 0;
369563ab645fSStefan Brüns }
369663ab645fSStefan Brüns 
36977d077197SDavid Brownell /**
3698684a4784STudor Ambarus  * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3699684a4784STudor Ambarus  * @spi: the device that requires specific CS timing configuration
3700684a4784STudor Ambarus  *
3701684a4784STudor Ambarus  * Return: zero on success, else a negative error code.
3702684a4784STudor Ambarus  */
spi_set_cs_timing(struct spi_device * spi)3703684a4784STudor Ambarus static int spi_set_cs_timing(struct spi_device *spi)
3704684a4784STudor Ambarus {
3705684a4784STudor Ambarus 	struct device *parent = spi->controller->dev.parent;
3706684a4784STudor Ambarus 	int status = 0;
3707684a4784STudor Ambarus 
3708303feb3cSAmit Kumar Mahapatra 	if (spi->controller->set_cs_timing && !spi_get_csgpiod(spi, 0)) {
3709684a4784STudor Ambarus 		if (spi->controller->auto_runtime_pm) {
3710684a4784STudor Ambarus 			status = pm_runtime_get_sync(parent);
3711684a4784STudor Ambarus 			if (status < 0) {
3712684a4784STudor Ambarus 				pm_runtime_put_noidle(parent);
3713684a4784STudor Ambarus 				dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3714684a4784STudor Ambarus 					status);
3715684a4784STudor Ambarus 				return status;
3716684a4784STudor Ambarus 			}
3717684a4784STudor Ambarus 
3718684a4784STudor Ambarus 			status = spi->controller->set_cs_timing(spi);
3719684a4784STudor Ambarus 			pm_runtime_mark_last_busy(parent);
3720684a4784STudor Ambarus 			pm_runtime_put_autosuspend(parent);
3721684a4784STudor Ambarus 		} else {
3722684a4784STudor Ambarus 			status = spi->controller->set_cs_timing(spi);
3723684a4784STudor Ambarus 		}
3724684a4784STudor Ambarus 	}
3725684a4784STudor Ambarus 	return status;
3726684a4784STudor Ambarus }
3727684a4784STudor Ambarus 
3728684a4784STudor Ambarus /**
37297d077197SDavid Brownell  * spi_setup - setup SPI mode and clock rate
37307d077197SDavid Brownell  * @spi: the device whose settings are being modified
37317d077197SDavid Brownell  * Context: can sleep, and no requests are queued to the device
37327d077197SDavid Brownell  *
37337d077197SDavid Brownell  * SPI protocol drivers may need to update the transfer mode if the
37347d077197SDavid Brownell  * device doesn't work with its default.  They may likewise need
37357d077197SDavid Brownell  * to update clock rates or word sizes from initial values.  This function
37367d077197SDavid Brownell  * changes those settings, and must be called from a context that can sleep.
37377d077197SDavid Brownell  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
37387d077197SDavid Brownell  * effect the next time the device is selected and data is transferred to
3739702ca026SAndy Shevchenko  * or from it.  When this function returns, the SPI device is deselected.
37407d077197SDavid Brownell  *
37417d077197SDavid Brownell  * Note that this call will fail if the protocol driver specifies an option
37427d077197SDavid Brownell  * that the underlying controller or its driver does not support.  For
37437d077197SDavid Brownell  * example, not all hardware supports wire transfers using nine bit words,
37447d077197SDavid Brownell  * LSB-first wire encoding, or active-high chipselects.
374597d56dc6SJavier Martinez Canillas  *
374697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
37477d077197SDavid Brownell  */
spi_setup(struct spi_device * spi)37487d077197SDavid Brownell int spi_setup(struct spi_device *spi)
37497d077197SDavid Brownell {
375083596fbeSGeert Uytterhoeven 	unsigned	bad_bits, ugly_bits;
375173f93db5SPaul Kocialkowski 	int		status = 0;
37527d077197SDavid Brownell 
3753d962608cSDragos Bogdan 	/*
3754350de7ceSAndy Shevchenko 	 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3755350de7ceSAndy Shevchenko 	 * are set at the same time.
3756f477b7fbSwangyuhang 	 */
3757d962608cSDragos Bogdan 	if ((hweight_long(spi->mode &
3758d962608cSDragos Bogdan 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3759d962608cSDragos Bogdan 	    (hweight_long(spi->mode &
3760d962608cSDragos Bogdan 		(SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3761f477b7fbSwangyuhang 		dev_err(&spi->dev,
3762d962608cSDragos Bogdan 		"setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3763f477b7fbSwangyuhang 		return -EINVAL;
3764f477b7fbSwangyuhang 	}
3765350de7ceSAndy Shevchenko 	/* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3766f477b7fbSwangyuhang 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
37676b03061fSYogesh Narayan Gaur 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
37686b03061fSYogesh Narayan Gaur 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3769f477b7fbSwangyuhang 		return -EINVAL;
3770350de7ceSAndy Shevchenko 	/*
3771350de7ceSAndy Shevchenko 	 * Help drivers fail *cleanly* when they need options
3772350de7ceSAndy Shevchenko 	 * that aren't supported with their current controller.
3773cbaa62e0SDavid Lechner 	 * SPI_CS_WORD has a fallback software implementation,
3774cbaa62e0SDavid Lechner 	 * so it is ignored here.
3775e7db06b5SDavid Brownell 	 */
3776d962608cSDragos Bogdan 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3777d962608cSDragos Bogdan 				 SPI_NO_TX | SPI_NO_RX);
377883596fbeSGeert Uytterhoeven 	ugly_bits = bad_bits &
37796b03061fSYogesh Narayan Gaur 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
37806b03061fSYogesh Narayan Gaur 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
378183596fbeSGeert Uytterhoeven 	if (ugly_bits) {
378283596fbeSGeert Uytterhoeven 		dev_warn(&spi->dev,
378383596fbeSGeert Uytterhoeven 			 "setup: ignoring unsupported mode bits %x\n",
378483596fbeSGeert Uytterhoeven 			 ugly_bits);
378583596fbeSGeert Uytterhoeven 		spi->mode &= ~ugly_bits;
378683596fbeSGeert Uytterhoeven 		bad_bits &= ~ugly_bits;
378783596fbeSGeert Uytterhoeven 	}
3788e7db06b5SDavid Brownell 	if (bad_bits) {
3789eb288a1fSLinus Walleij 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3790e7db06b5SDavid Brownell 			bad_bits);
3791e7db06b5SDavid Brownell 		return -EINVAL;
3792e7db06b5SDavid Brownell 	}
3793e7db06b5SDavid Brownell 
3794b3fe2e51SPaul Kocialkowski 	if (!spi->bits_per_word) {
37957d077197SDavid Brownell 		spi->bits_per_word = 8;
3796b3fe2e51SPaul Kocialkowski 	} else {
3797b3fe2e51SPaul Kocialkowski 		/*
3798b3fe2e51SPaul Kocialkowski 		 * Some controllers may not support the default 8 bits-per-word
3799b3fe2e51SPaul Kocialkowski 		 * so only perform the check when this is explicitly provided.
3800b3fe2e51SPaul Kocialkowski 		 */
38018caab75fSGeert Uytterhoeven 		status = __spi_validate_bits_per_word(spi->controller,
38028caab75fSGeert Uytterhoeven 						      spi->bits_per_word);
38035ab8d262SAndy Shevchenko 		if (status)
38045ab8d262SAndy Shevchenko 			return status;
3805b3fe2e51SPaul Kocialkowski 	}
380663ab645fSStefan Brüns 
38076820e812STudor Ambarus 	if (spi->controller->max_speed_hz &&
38086820e812STudor Ambarus 	    (!spi->max_speed_hz ||
38096820e812STudor Ambarus 	     spi->max_speed_hz > spi->controller->max_speed_hz))
38108caab75fSGeert Uytterhoeven 		spi->max_speed_hz = spi->controller->max_speed_hz;
3811052eb2d4SAxel Lin 
38124fae3a58SSerge Semin 	mutex_lock(&spi->controller->io_mutex);
38134fae3a58SSerge Semin 
3814c914dbf8SJoe Burmeister 	if (spi->controller->setup) {
38158caab75fSGeert Uytterhoeven 		status = spi->controller->setup(spi);
3816c914dbf8SJoe Burmeister 		if (status) {
3817c914dbf8SJoe Burmeister 			mutex_unlock(&spi->controller->io_mutex);
3818c914dbf8SJoe Burmeister 			dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3819c914dbf8SJoe Burmeister 				status);
3820c914dbf8SJoe Burmeister 			return status;
3821c914dbf8SJoe Burmeister 		}
3822c914dbf8SJoe Burmeister 	}
38237d077197SDavid Brownell 
3824684a4784STudor Ambarus 	status = spi_set_cs_timing(spi);
3825684a4784STudor Ambarus 	if (status) {
3826684a4784STudor Ambarus 		mutex_unlock(&spi->controller->io_mutex);
3827684a4784STudor Ambarus 		return status;
3828684a4784STudor Ambarus 	}
3829684a4784STudor Ambarus 
3830d948e6caSLuhua Xu 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3831dd769f15SMinghao Chi 		status = pm_runtime_resume_and_get(spi->controller->dev.parent);
3832d948e6caSLuhua Xu 		if (status < 0) {
38334fae3a58SSerge Semin 			mutex_unlock(&spi->controller->io_mutex);
3834d948e6caSLuhua Xu 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3835d948e6caSLuhua Xu 				status);
3836d948e6caSLuhua Xu 			return status;
3837d948e6caSLuhua Xu 		}
383857a94607STony Lindgren 
383957a94607STony Lindgren 		/*
384057a94607STony Lindgren 		 * We do not want to return positive value from pm_runtime_get,
384157a94607STony Lindgren 		 * there are many instances of devices calling spi_setup() and
384257a94607STony Lindgren 		 * checking for a non-zero return value instead of a negative
384357a94607STony Lindgren 		 * return value.
384457a94607STony Lindgren 		 */
384557a94607STony Lindgren 		status = 0;
384657a94607STony Lindgren 
3847d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
3848d948e6caSLuhua Xu 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3849d948e6caSLuhua Xu 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3850d948e6caSLuhua Xu 	} else {
3851d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
3852d948e6caSLuhua Xu 	}
3853abeedb01SFranklin S Cooper Jr 
38544fae3a58SSerge Semin 	mutex_unlock(&spi->controller->io_mutex);
38554fae3a58SSerge Semin 
3856924b5867SDouglas Anderson 	if (spi->rt && !spi->controller->rt) {
3857924b5867SDouglas Anderson 		spi->controller->rt = true;
3858924b5867SDouglas Anderson 		spi_set_thread_rt(spi->controller);
3859924b5867SDouglas Anderson 	}
3860924b5867SDouglas Anderson 
38615cb4e1f3SAndy Shevchenko 	trace_spi_setup(spi, status);
38625cb4e1f3SAndy Shevchenko 
386340b82c2dSAndy Shevchenko 	dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
386440b82c2dSAndy Shevchenko 			spi->mode & SPI_MODE_X_MASK,
38657d077197SDavid Brownell 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
38667d077197SDavid Brownell 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
38677d077197SDavid Brownell 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
38687d077197SDavid Brownell 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
38697d077197SDavid Brownell 			spi->bits_per_word, spi->max_speed_hz,
38707d077197SDavid Brownell 			status);
38717d077197SDavid Brownell 
38727d077197SDavid Brownell 	return status;
38737d077197SDavid Brownell }
38747d077197SDavid Brownell EXPORT_SYMBOL_GPL(spi_setup);
38757d077197SDavid Brownell 
_spi_xfer_word_delay_update(struct spi_transfer * xfer,struct spi_device * spi)38766c613f68SAlexandru Ardelean static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
38776c613f68SAlexandru Ardelean 				       struct spi_device *spi)
38786c613f68SAlexandru Ardelean {
38796c613f68SAlexandru Ardelean 	int delay1, delay2;
38806c613f68SAlexandru Ardelean 
38813984d39bSAlexandru Ardelean 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
38826c613f68SAlexandru Ardelean 	if (delay1 < 0)
38836c613f68SAlexandru Ardelean 		return delay1;
38846c613f68SAlexandru Ardelean 
38853984d39bSAlexandru Ardelean 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
38866c613f68SAlexandru Ardelean 	if (delay2 < 0)
38876c613f68SAlexandru Ardelean 		return delay2;
38886c613f68SAlexandru Ardelean 
38896c613f68SAlexandru Ardelean 	if (delay1 < delay2)
38906c613f68SAlexandru Ardelean 		memcpy(&xfer->word_delay, &spi->word_delay,
38916c613f68SAlexandru Ardelean 		       sizeof(xfer->word_delay));
38926c613f68SAlexandru Ardelean 
38936c613f68SAlexandru Ardelean 	return 0;
38946c613f68SAlexandru Ardelean }
38956c613f68SAlexandru Ardelean 
__spi_validate(struct spi_device * spi,struct spi_message * message)389690808738SMark Brown static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3897cf32b71eSErnst Schwab {
38988caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3899e6811d1dSLaxman Dewangan 	struct spi_transfer *xfer;
39006ea31293SAtsushi Nemoto 	int w_size;
3901cf32b71eSErnst Schwab 
390224a0013aSMark Brown 	if (list_empty(&message->transfers))
390324a0013aSMark Brown 		return -EINVAL;
390424a0013aSMark Brown 
3905350de7ceSAndy Shevchenko 	/*
3906350de7ceSAndy Shevchenko 	 * If an SPI controller does not support toggling the CS line on each
390771388b21SDavid Lechner 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
390871388b21SDavid Lechner 	 * for the CS line, we can emulate the CS-per-word hardware function by
3909cbaa62e0SDavid Lechner 	 * splitting transfers into one-word transfers and ensuring that
3910cbaa62e0SDavid Lechner 	 * cs_change is set for each transfer.
3911cbaa62e0SDavid Lechner 	 */
391271388b21SDavid Lechner 	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3913303feb3cSAmit Kumar Mahapatra 					  spi_get_csgpiod(spi, 0))) {
3914169f5312SAndy Shevchenko 		size_t maxsize = BITS_TO_BYTES(spi->bits_per_word);
3915cbaa62e0SDavid Lechner 		int ret;
3916cbaa62e0SDavid Lechner 
3917cbaa62e0SDavid Lechner 		/* spi_split_transfers_maxsize() requires message->spi */
3918cbaa62e0SDavid Lechner 		message->spi = spi;
3919cbaa62e0SDavid Lechner 
3920cbaa62e0SDavid Lechner 		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3921cbaa62e0SDavid Lechner 						  GFP_KERNEL);
3922cbaa62e0SDavid Lechner 		if (ret)
3923cbaa62e0SDavid Lechner 			return ret;
3924cbaa62e0SDavid Lechner 
3925cbaa62e0SDavid Lechner 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
392695c8222fSDavid Jander 			/* Don't change cs_change on the last entry in the list */
3927cbaa62e0SDavid Lechner 			if (list_is_last(&xfer->transfer_list, &message->transfers))
3928cbaa62e0SDavid Lechner 				break;
3929cbaa62e0SDavid Lechner 			xfer->cs_change = 1;
3930cbaa62e0SDavid Lechner 		}
3931cbaa62e0SDavid Lechner 	}
3932cbaa62e0SDavid Lechner 
3933350de7ceSAndy Shevchenko 	/*
3934350de7ceSAndy Shevchenko 	 * Half-duplex links include original MicroWire, and ones with
3935cf32b71eSErnst Schwab 	 * only one data pin like SPI_3WIRE (switches direction) or where
3936cf32b71eSErnst Schwab 	 * either MOSI or MISO is missing.  They can also be caused by
3937cf32b71eSErnst Schwab 	 * software limitations.
3938cf32b71eSErnst Schwab 	 */
39398caab75fSGeert Uytterhoeven 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
39408caab75fSGeert Uytterhoeven 	    (spi->mode & SPI_3WIRE)) {
39418caab75fSGeert Uytterhoeven 		unsigned flags = ctlr->flags;
3942cf32b71eSErnst Schwab 
3943cf32b71eSErnst Schwab 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3944cf32b71eSErnst Schwab 			if (xfer->rx_buf && xfer->tx_buf)
3945cf32b71eSErnst Schwab 				return -EINVAL;
39468caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3947cf32b71eSErnst Schwab 				return -EINVAL;
39488caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3949cf32b71eSErnst Schwab 				return -EINVAL;
3950cf32b71eSErnst Schwab 		}
3951cf32b71eSErnst Schwab 	}
3952cf32b71eSErnst Schwab 
3953350de7ceSAndy Shevchenko 	/*
3954059b8ffeSLaxman Dewangan 	 * Set transfer bits_per_word and max speed as spi device default if
3955059b8ffeSLaxman Dewangan 	 * it is not set for this transfer.
3956f477b7fbSwangyuhang 	 * Set transfer tx_nbits and rx_nbits as single transfer default
3957f477b7fbSwangyuhang 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3958b7bb367aSJonas Bonn 	 * Ensure transfer word_delay is at least as long as that required by
3959b7bb367aSJonas Bonn 	 * device itself.
3960e6811d1dSLaxman Dewangan 	 */
396177e80588SMartin Sperl 	message->frame_length = 0;
3962e6811d1dSLaxman Dewangan 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
39635d7e2b5eSMartin Sperl 		xfer->effective_speed_hz = 0;
3964078726ceSSourav Poddar 		message->frame_length += xfer->len;
3965e6811d1dSLaxman Dewangan 		if (!xfer->bits_per_word)
3966e6811d1dSLaxman Dewangan 			xfer->bits_per_word = spi->bits_per_word;
3967a6f87fadSAxel Lin 
3968a6f87fadSAxel Lin 		if (!xfer->speed_hz)
3969059b8ffeSLaxman Dewangan 			xfer->speed_hz = spi->max_speed_hz;
3970a6f87fadSAxel Lin 
39718caab75fSGeert Uytterhoeven 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
39728caab75fSGeert Uytterhoeven 			xfer->speed_hz = ctlr->max_speed_hz;
397356ede94aSGabor Juhos 
39748caab75fSGeert Uytterhoeven 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3975543bb255SStephen Warren 			return -EINVAL;
3976a2fd4f9fSMark Brown 
39774d94bd21SIvan T. Ivanov 		/*
39784d94bd21SIvan T. Ivanov 		 * SPI transfer length should be multiple of SPI word size
3979350de7ceSAndy Shevchenko 		 * where SPI word size should be power-of-two multiple.
39804d94bd21SIvan T. Ivanov 		 */
39814d94bd21SIvan T. Ivanov 		if (xfer->bits_per_word <= 8)
39824d94bd21SIvan T. Ivanov 			w_size = 1;
39834d94bd21SIvan T. Ivanov 		else if (xfer->bits_per_word <= 16)
39844d94bd21SIvan T. Ivanov 			w_size = 2;
39854d94bd21SIvan T. Ivanov 		else
39864d94bd21SIvan T. Ivanov 			w_size = 4;
39874d94bd21SIvan T. Ivanov 
39884d94bd21SIvan T. Ivanov 		/* No partial transfers accepted */
39896ea31293SAtsushi Nemoto 		if (xfer->len % w_size)
39904d94bd21SIvan T. Ivanov 			return -EINVAL;
39914d94bd21SIvan T. Ivanov 
39928caab75fSGeert Uytterhoeven 		if (xfer->speed_hz && ctlr->min_speed_hz &&
39938caab75fSGeert Uytterhoeven 		    xfer->speed_hz < ctlr->min_speed_hz)
3994a2fd4f9fSMark Brown 			return -EINVAL;
3995f477b7fbSwangyuhang 
3996f477b7fbSwangyuhang 		if (xfer->tx_buf && !xfer->tx_nbits)
3997f477b7fbSwangyuhang 			xfer->tx_nbits = SPI_NBITS_SINGLE;
3998f477b7fbSwangyuhang 		if (xfer->rx_buf && !xfer->rx_nbits)
3999f477b7fbSwangyuhang 			xfer->rx_nbits = SPI_NBITS_SINGLE;
4000350de7ceSAndy Shevchenko 		/*
4001350de7ceSAndy Shevchenko 		 * Check transfer tx/rx_nbits:
40021afd9989SGeert Uytterhoeven 		 * 1. check the value matches one of single, dual and quad
40031afd9989SGeert Uytterhoeven 		 * 2. check tx/rx_nbits match the mode in spi_device
4004f477b7fbSwangyuhang 		 */
4005db90a441SSourav Poddar 		if (xfer->tx_buf) {
4006d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_TX)
4007d962608cSDragos Bogdan 				return -EINVAL;
4008f477b7fbSwangyuhang 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
4009f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_DUAL &&
40104bcb8e4cSPatrice Chotard 				xfer->tx_nbits != SPI_NBITS_QUAD &&
40114bcb8e4cSPatrice Chotard 				xfer->tx_nbits != SPI_NBITS_OCTAL)
4012a2fd4f9fSMark Brown 				return -EINVAL;
4013f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
4014f477b7fbSwangyuhang 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
4015f477b7fbSwangyuhang 				return -EINVAL;
4016f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
4017f477b7fbSwangyuhang 				!(spi->mode & SPI_TX_QUAD))
4018f477b7fbSwangyuhang 				return -EINVAL;
4019db90a441SSourav Poddar 		}
402095c8222fSDavid Jander 		/* Check transfer rx_nbits */
4021db90a441SSourav Poddar 		if (xfer->rx_buf) {
4022d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_RX)
4023d962608cSDragos Bogdan 				return -EINVAL;
4024f477b7fbSwangyuhang 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
4025f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_DUAL &&
40264bcb8e4cSPatrice Chotard 				xfer->rx_nbits != SPI_NBITS_QUAD &&
40274bcb8e4cSPatrice Chotard 				xfer->rx_nbits != SPI_NBITS_OCTAL)
4028f477b7fbSwangyuhang 				return -EINVAL;
4029f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
4030f477b7fbSwangyuhang 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
4031f477b7fbSwangyuhang 				return -EINVAL;
4032f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
4033f477b7fbSwangyuhang 				!(spi->mode & SPI_RX_QUAD))
4034f477b7fbSwangyuhang 				return -EINVAL;
4035e6811d1dSLaxman Dewangan 		}
4036b7bb367aSJonas Bonn 
40376c613f68SAlexandru Ardelean 		if (_spi_xfer_word_delay_update(xfer, spi))
40386c613f68SAlexandru Ardelean 			return -EINVAL;
4039e6811d1dSLaxman Dewangan 	}
4040e6811d1dSLaxman Dewangan 
4041cf32b71eSErnst Schwab 	message->status = -EINPROGRESS;
404290808738SMark Brown 
404390808738SMark Brown 	return 0;
404490808738SMark Brown }
404590808738SMark Brown 
__spi_async(struct spi_device * spi,struct spi_message * message)404690808738SMark Brown static int __spi_async(struct spi_device *spi, struct spi_message *message)
404790808738SMark Brown {
40488caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4049b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
405090808738SMark Brown 
4051b5932f5cSBoris Brezillon 	/*
4052b5932f5cSBoris Brezillon 	 * Some controllers do not support doing regular SPI transfers. Return
4053b5932f5cSBoris Brezillon 	 * ENOTSUPP when this is the case.
4054b5932f5cSBoris Brezillon 	 */
4055b5932f5cSBoris Brezillon 	if (!ctlr->transfer)
4056b5932f5cSBoris Brezillon 		return -ENOTSUPP;
4057b5932f5cSBoris Brezillon 
405890808738SMark Brown 	message->spi = spi;
405990808738SMark Brown 
40606598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async);
40616598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async);
4062eca2ebc7SMartin Sperl 
406390808738SMark Brown 	trace_spi_message_submit(message);
406490808738SMark Brown 
4065b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported) {
4066b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
4067b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
4068b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
4069b42faeeeSVladimir Oltean 		}
4070b42faeeeSVladimir Oltean 	}
4071b42faeeeSVladimir Oltean 
40728caab75fSGeert Uytterhoeven 	return ctlr->transfer(spi, message);
4073cf32b71eSErnst Schwab }
4074cf32b71eSErnst Schwab 
4075568d0697SDavid Brownell /**
4076568d0697SDavid Brownell  * spi_async - asynchronous SPI transfer
4077568d0697SDavid Brownell  * @spi: device with which data will be exchanged
4078568d0697SDavid Brownell  * @message: describes the data transfers, including completion callback
4079702ca026SAndy Shevchenko  * Context: any (IRQs may be blocked, etc)
4080568d0697SDavid Brownell  *
4081568d0697SDavid Brownell  * This call may be used in_irq and other contexts which can't sleep,
4082568d0697SDavid Brownell  * as well as from task contexts which can sleep.
4083568d0697SDavid Brownell  *
4084568d0697SDavid Brownell  * The completion callback is invoked in a context which can't sleep.
4085568d0697SDavid Brownell  * Before that invocation, the value of message->status is undefined.
4086568d0697SDavid Brownell  * When the callback is issued, message->status holds either zero (to
4087568d0697SDavid Brownell  * indicate complete success) or a negative error code.  After that
4088568d0697SDavid Brownell  * callback returns, the driver which issued the transfer request may
4089568d0697SDavid Brownell  * deallocate the associated memory; it's no longer in use by any SPI
4090568d0697SDavid Brownell  * core or controller driver code.
4091568d0697SDavid Brownell  *
4092568d0697SDavid Brownell  * Note that although all messages to a spi_device are handled in
4093568d0697SDavid Brownell  * FIFO order, messages may go to different devices in other orders.
4094568d0697SDavid Brownell  * Some device might be higher priority, or have various "hard" access
4095568d0697SDavid Brownell  * time requirements, for example.
4096568d0697SDavid Brownell  *
4097568d0697SDavid Brownell  * On detection of any fault during the transfer, processing of
4098568d0697SDavid Brownell  * the entire message is aborted, and the device is deselected.
4099568d0697SDavid Brownell  * Until returning from the associated message completion callback,
4100568d0697SDavid Brownell  * no other spi_message queued to that device will be processed.
4101568d0697SDavid Brownell  * (This rule applies equally to all the synchronous transfer calls,
4102568d0697SDavid Brownell  * which are wrappers around this core asynchronous primitive.)
410397d56dc6SJavier Martinez Canillas  *
410497d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4105568d0697SDavid Brownell  */
spi_async(struct spi_device * spi,struct spi_message * message)4106568d0697SDavid Brownell int spi_async(struct spi_device *spi, struct spi_message *message)
4107568d0697SDavid Brownell {
41088caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4109cf32b71eSErnst Schwab 	int ret;
4110cf32b71eSErnst Schwab 	unsigned long flags;
4111568d0697SDavid Brownell 
411290808738SMark Brown 	ret = __spi_validate(spi, message);
411390808738SMark Brown 	if (ret != 0)
411490808738SMark Brown 		return ret;
411590808738SMark Brown 
41168caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4117568d0697SDavid Brownell 
41188caab75fSGeert Uytterhoeven 	if (ctlr->bus_lock_flag)
4119cf32b71eSErnst Schwab 		ret = -EBUSY;
4120cf32b71eSErnst Schwab 	else
4121cf32b71eSErnst Schwab 		ret = __spi_async(spi, message);
4122568d0697SDavid Brownell 
41238caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4124cf32b71eSErnst Schwab 
4125cf32b71eSErnst Schwab 	return ret;
4126568d0697SDavid Brownell }
4127568d0697SDavid Brownell EXPORT_SYMBOL_GPL(spi_async);
4128568d0697SDavid Brownell 
4129cf32b71eSErnst Schwab /**
4130cf32b71eSErnst Schwab  * spi_async_locked - version of spi_async with exclusive bus usage
4131cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
4132cf32b71eSErnst Schwab  * @message: describes the data transfers, including completion callback
4133702ca026SAndy Shevchenko  * Context: any (IRQs may be blocked, etc)
4134cf32b71eSErnst Schwab  *
4135cf32b71eSErnst Schwab  * This call may be used in_irq and other contexts which can't sleep,
4136cf32b71eSErnst Schwab  * as well as from task contexts which can sleep.
4137cf32b71eSErnst Schwab  *
4138cf32b71eSErnst Schwab  * The completion callback is invoked in a context which can't sleep.
4139cf32b71eSErnst Schwab  * Before that invocation, the value of message->status is undefined.
4140cf32b71eSErnst Schwab  * When the callback is issued, message->status holds either zero (to
4141cf32b71eSErnst Schwab  * indicate complete success) or a negative error code.  After that
4142cf32b71eSErnst Schwab  * callback returns, the driver which issued the transfer request may
4143cf32b71eSErnst Schwab  * deallocate the associated memory; it's no longer in use by any SPI
4144cf32b71eSErnst Schwab  * core or controller driver code.
4145cf32b71eSErnst Schwab  *
4146cf32b71eSErnst Schwab  * Note that although all messages to a spi_device are handled in
4147cf32b71eSErnst Schwab  * FIFO order, messages may go to different devices in other orders.
4148cf32b71eSErnst Schwab  * Some device might be higher priority, or have various "hard" access
4149cf32b71eSErnst Schwab  * time requirements, for example.
4150cf32b71eSErnst Schwab  *
4151cf32b71eSErnst Schwab  * On detection of any fault during the transfer, processing of
4152cf32b71eSErnst Schwab  * the entire message is aborted, and the device is deselected.
4153cf32b71eSErnst Schwab  * Until returning from the associated message completion callback,
4154cf32b71eSErnst Schwab  * no other spi_message queued to that device will be processed.
4155cf32b71eSErnst Schwab  * (This rule applies equally to all the synchronous transfer calls,
4156cf32b71eSErnst Schwab  * which are wrappers around this core asynchronous primitive.)
415797d56dc6SJavier Martinez Canillas  *
415897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4159cf32b71eSErnst Schwab  */
spi_async_locked(struct spi_device * spi,struct spi_message * message)4160da21fde0SUwe Kleine-König static int spi_async_locked(struct spi_device *spi, struct spi_message *message)
4161cf32b71eSErnst Schwab {
41628caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4163cf32b71eSErnst Schwab 	int ret;
4164cf32b71eSErnst Schwab 	unsigned long flags;
4165cf32b71eSErnst Schwab 
416690808738SMark Brown 	ret = __spi_validate(spi, message);
416790808738SMark Brown 	if (ret != 0)
416890808738SMark Brown 		return ret;
416990808738SMark Brown 
41708caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4171cf32b71eSErnst Schwab 
4172cf32b71eSErnst Schwab 	ret = __spi_async(spi, message);
4173cf32b71eSErnst Schwab 
41748caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4175cf32b71eSErnst Schwab 
4176cf32b71eSErnst Schwab 	return ret;
4177cf32b71eSErnst Schwab 
4178cf32b71eSErnst Schwab }
4179cf32b71eSErnst Schwab 
__spi_transfer_message_noqueue(struct spi_controller * ctlr,struct spi_message * msg)4180ae7d2346SDavid Jander static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg)
4181ae7d2346SDavid Jander {
4182ae7d2346SDavid Jander 	bool was_busy;
4183ae7d2346SDavid Jander 	int ret;
4184ae7d2346SDavid Jander 
4185ae7d2346SDavid Jander 	mutex_lock(&ctlr->io_mutex);
4186ae7d2346SDavid Jander 
41871a9cafcbSDavid Jander 	was_busy = ctlr->busy;
4188ae7d2346SDavid Jander 
418972c5c59bSDavid Jander 	ctlr->cur_msg = msg;
4190ae7d2346SDavid Jander 	ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
4191ae7d2346SDavid Jander 	if (ret)
419296474ea4SMark Hasemeyer 		dev_err(&ctlr->dev, "noqueue transfer failed\n");
419369fa9590SDavid Jander 	ctlr->cur_msg = NULL;
419469fa9590SDavid Jander 	ctlr->fallback = false;
419569fa9590SDavid Jander 
4196ae7d2346SDavid Jander 	if (!was_busy) {
4197ae7d2346SDavid Jander 		kfree(ctlr->dummy_rx);
4198ae7d2346SDavid Jander 		ctlr->dummy_rx = NULL;
4199ae7d2346SDavid Jander 		kfree(ctlr->dummy_tx);
4200ae7d2346SDavid Jander 		ctlr->dummy_tx = NULL;
4201ae7d2346SDavid Jander 		if (ctlr->unprepare_transfer_hardware &&
4202ae7d2346SDavid Jander 		    ctlr->unprepare_transfer_hardware(ctlr))
4203ae7d2346SDavid Jander 			dev_err(&ctlr->dev,
4204ae7d2346SDavid Jander 				"failed to unprepare transfer hardware\n");
4205ae7d2346SDavid Jander 		spi_idle_runtime_pm(ctlr);
4206ae7d2346SDavid Jander 	}
4207ae7d2346SDavid Jander 
4208ae7d2346SDavid Jander 	mutex_unlock(&ctlr->io_mutex);
4209ae7d2346SDavid Jander }
4210ae7d2346SDavid Jander 
42117d077197SDavid Brownell /*-------------------------------------------------------------------------*/
42127d077197SDavid Brownell 
4213350de7ceSAndy Shevchenko /*
4214350de7ceSAndy Shevchenko  * Utility methods for SPI protocol drivers, layered on
42157d077197SDavid Brownell  * top of the core.  Some other utility methods are defined as
42167d077197SDavid Brownell  * inline functions.
42177d077197SDavid Brownell  */
42187d077197SDavid Brownell 
spi_complete(void * arg)42195d870c8eSAndrew Morton static void spi_complete(void *arg)
42205d870c8eSAndrew Morton {
42215d870c8eSAndrew Morton 	complete(arg);
42225d870c8eSAndrew Morton }
42235d870c8eSAndrew Morton 
__spi_sync(struct spi_device * spi,struct spi_message * message)4224ef4d96ecSMark Brown static int __spi_sync(struct spi_device *spi, struct spi_message *message)
4225cf32b71eSErnst Schwab {
4226cf32b71eSErnst Schwab 	DECLARE_COMPLETION_ONSTACK(done);
4227cf32b71eSErnst Schwab 	int status;
42288caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
42290461a414SMark Brown 
423096474ea4SMark Hasemeyer 	if (__spi_check_suspended(ctlr)) {
423196474ea4SMark Hasemeyer 		dev_warn_once(&spi->dev, "Attempted to sync while suspend\n");
423296474ea4SMark Hasemeyer 		return -ESHUTDOWN;
423396474ea4SMark Hasemeyer 	}
423496474ea4SMark Hasemeyer 
42350461a414SMark Brown 	status = __spi_validate(spi, message);
42360461a414SMark Brown 	if (status != 0)
42370461a414SMark Brown 		return status;
4238cf32b71eSErnst Schwab 
42390461a414SMark Brown 	message->spi = spi;
4240cf32b71eSErnst Schwab 
42416598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync);
42426598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync);
4243eca2ebc7SMartin Sperl 
4244350de7ceSAndy Shevchenko 	/*
4245ae7d2346SDavid Jander 	 * Checking queue_empty here only guarantees async/sync message
4246ae7d2346SDavid Jander 	 * ordering when coming from the same context. It does not need to
4247ae7d2346SDavid Jander 	 * guard against reentrancy from a different context. The io_mutex
4248ae7d2346SDavid Jander 	 * will catch those cases.
42490461a414SMark Brown 	 */
4250b30f7c8eSMark Brown 	if (READ_ONCE(ctlr->queue_empty) && !ctlr->must_async) {
4251ae7d2346SDavid Jander 		message->actual_length = 0;
4252ae7d2346SDavid Jander 		message->status = -EINPROGRESS;
42530461a414SMark Brown 
42540461a414SMark Brown 		trace_spi_message_submit(message);
42550461a414SMark Brown 
4256ae7d2346SDavid Jander 		SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate);
4257ae7d2346SDavid Jander 		SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate);
42580461a414SMark Brown 
4259ae7d2346SDavid Jander 		__spi_transfer_message_noqueue(ctlr, message);
4260ae7d2346SDavid Jander 
4261ae7d2346SDavid Jander 		return message->status;
4262ae7d2346SDavid Jander 	}
4263ae7d2346SDavid Jander 
4264ae7d2346SDavid Jander 	/*
4265ae7d2346SDavid Jander 	 * There are messages in the async queue that could have originated
4266ae7d2346SDavid Jander 	 * from the same context, so we need to preserve ordering.
4267ae7d2346SDavid Jander 	 * Therefor we send the message to the async queue and wait until they
4268ae7d2346SDavid Jander 	 * are completed.
4269ae7d2346SDavid Jander 	 */
4270ae7d2346SDavid Jander 	message->complete = spi_complete;
4271ae7d2346SDavid Jander 	message->context = &done;
4272cf32b71eSErnst Schwab 	status = spi_async_locked(spi, message);
4273cf32b71eSErnst Schwab 	if (status == 0) {
4274cf32b71eSErnst Schwab 		wait_for_completion(&done);
4275cf32b71eSErnst Schwab 		status = message->status;
4276cf32b71eSErnst Schwab 	}
4277a30659f1SMans Rullgard 	message->complete = NULL;
4278cf32b71eSErnst Schwab 	message->context = NULL;
4279ae7d2346SDavid Jander 
4280cf32b71eSErnst Schwab 	return status;
4281cf32b71eSErnst Schwab }
4282cf32b71eSErnst Schwab 
42838ae12a0dSDavid Brownell /**
42848ae12a0dSDavid Brownell  * spi_sync - blocking/synchronous SPI data transfers
42858ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
42868ae12a0dSDavid Brownell  * @message: describes the data transfers
428733e34dc6SDavid Brownell  * Context: can sleep
42888ae12a0dSDavid Brownell  *
42898ae12a0dSDavid Brownell  * This call may only be used from a context that may sleep.  The sleep
42908ae12a0dSDavid Brownell  * is non-interruptible, and has no timeout.  Low-overhead controller
42918ae12a0dSDavid Brownell  * drivers may DMA directly into and out of the message buffers.
42928ae12a0dSDavid Brownell  *
42938ae12a0dSDavid Brownell  * Note that the SPI device's chip select is active during the message,
42948ae12a0dSDavid Brownell  * and then is normally disabled between messages.  Drivers for some
42958ae12a0dSDavid Brownell  * frequently-used devices may want to minimize costs of selecting a chip,
42968ae12a0dSDavid Brownell  * by leaving it selected in anticipation that the next message will go
42978ae12a0dSDavid Brownell  * to the same chip.  (That may increase power usage.)
42988ae12a0dSDavid Brownell  *
42990c868461SDavid Brownell  * Also, the caller is guaranteeing that the memory associated with the
43000c868461SDavid Brownell  * message will not be freed before this call returns.
43010c868461SDavid Brownell  *
430297d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
43038ae12a0dSDavid Brownell  */
spi_sync(struct spi_device * spi,struct spi_message * message)43048ae12a0dSDavid Brownell int spi_sync(struct spi_device *spi, struct spi_message *message)
43058ae12a0dSDavid Brownell {
4306ef4d96ecSMark Brown 	int ret;
4307ef4d96ecSMark Brown 
43088caab75fSGeert Uytterhoeven 	mutex_lock(&spi->controller->bus_lock_mutex);
4309ef4d96ecSMark Brown 	ret = __spi_sync(spi, message);
43108caab75fSGeert Uytterhoeven 	mutex_unlock(&spi->controller->bus_lock_mutex);
4311ef4d96ecSMark Brown 
4312ef4d96ecSMark Brown 	return ret;
43138ae12a0dSDavid Brownell }
43148ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_sync);
43158ae12a0dSDavid Brownell 
4316cf32b71eSErnst Schwab /**
4317cf32b71eSErnst Schwab  * spi_sync_locked - version of spi_sync with exclusive bus usage
4318cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
4319cf32b71eSErnst Schwab  * @message: describes the data transfers
4320cf32b71eSErnst Schwab  * Context: can sleep
4321cf32b71eSErnst Schwab  *
4322cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4323cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.  Low-overhead controller
4324cf32b71eSErnst Schwab  * drivers may DMA directly into and out of the message buffers.
4325cf32b71eSErnst Schwab  *
4326cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
432725985edcSLucas De Marchi  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4328cf32b71eSErnst Schwab  * be released by a spi_bus_unlock call when the exclusive access is over.
4329cf32b71eSErnst Schwab  *
433097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4331cf32b71eSErnst Schwab  */
spi_sync_locked(struct spi_device * spi,struct spi_message * message)4332cf32b71eSErnst Schwab int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4333cf32b71eSErnst Schwab {
4334ef4d96ecSMark Brown 	return __spi_sync(spi, message);
4335cf32b71eSErnst Schwab }
4336cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_sync_locked);
4337cf32b71eSErnst Schwab 
4338cf32b71eSErnst Schwab /**
4339cf32b71eSErnst Schwab  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
43408caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that should be locked for exclusive bus access
4341cf32b71eSErnst Schwab  * Context: can sleep
4342cf32b71eSErnst Schwab  *
4343cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4344cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4345cf32b71eSErnst Schwab  *
4346cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
4347cf32b71eSErnst Schwab  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4348cf32b71eSErnst Schwab  * exclusive access is over. Data transfer must be done by spi_sync_locked
4349cf32b71eSErnst Schwab  * and spi_async_locked calls when the SPI bus lock is held.
4350cf32b71eSErnst Schwab  *
435197d56dc6SJavier Martinez Canillas  * Return: always zero.
4352cf32b71eSErnst Schwab  */
spi_bus_lock(struct spi_controller * ctlr)43538caab75fSGeert Uytterhoeven int spi_bus_lock(struct spi_controller *ctlr)
4354cf32b71eSErnst Schwab {
4355cf32b71eSErnst Schwab 	unsigned long flags;
4356cf32b71eSErnst Schwab 
43578caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->bus_lock_mutex);
4358cf32b71eSErnst Schwab 
43598caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
43608caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 1;
43618caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4362cf32b71eSErnst Schwab 
436395c8222fSDavid Jander 	/* Mutex remains locked until spi_bus_unlock() is called */
4364cf32b71eSErnst Schwab 
4365cf32b71eSErnst Schwab 	return 0;
4366cf32b71eSErnst Schwab }
4367cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_lock);
4368cf32b71eSErnst Schwab 
4369cf32b71eSErnst Schwab /**
4370cf32b71eSErnst Schwab  * spi_bus_unlock - release the lock for exclusive SPI bus usage
43718caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that was locked for exclusive bus access
4372cf32b71eSErnst Schwab  * Context: can sleep
4373cf32b71eSErnst Schwab  *
4374cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4375cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4376cf32b71eSErnst Schwab  *
4377cf32b71eSErnst Schwab  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4378cf32b71eSErnst Schwab  * call.
4379cf32b71eSErnst Schwab  *
438097d56dc6SJavier Martinez Canillas  * Return: always zero.
4381cf32b71eSErnst Schwab  */
spi_bus_unlock(struct spi_controller * ctlr)43828caab75fSGeert Uytterhoeven int spi_bus_unlock(struct spi_controller *ctlr)
4383cf32b71eSErnst Schwab {
43848caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
4385cf32b71eSErnst Schwab 
43868caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->bus_lock_mutex);
4387cf32b71eSErnst Schwab 
4388cf32b71eSErnst Schwab 	return 0;
4389cf32b71eSErnst Schwab }
4390cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_unlock);
4391cf32b71eSErnst Schwab 
439295c8222fSDavid Jander /* Portable code must never pass more than 32 bytes */
4393a9948b61SDavid Brownell #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
43948ae12a0dSDavid Brownell 
43958ae12a0dSDavid Brownell static u8	*buf;
43968ae12a0dSDavid Brownell 
43978ae12a0dSDavid Brownell /**
43988ae12a0dSDavid Brownell  * spi_write_then_read - SPI synchronous write followed by read
43998ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
4400702ca026SAndy Shevchenko  * @txbuf: data to be written (need not be DMA-safe)
44018ae12a0dSDavid Brownell  * @n_tx: size of txbuf, in bytes
4402702ca026SAndy Shevchenko  * @rxbuf: buffer into which data will be read (need not be DMA-safe)
440327570497SJiri Pirko  * @n_rx: size of rxbuf, in bytes
440433e34dc6SDavid Brownell  * Context: can sleep
44058ae12a0dSDavid Brownell  *
44068ae12a0dSDavid Brownell  * This performs a half duplex MicroWire style transaction with the
44078ae12a0dSDavid Brownell  * device, sending txbuf and then reading rxbuf.  The return value
44088ae12a0dSDavid Brownell  * is zero for success, else a negative errno status code.
4409b885244eSDavid Brownell  * This call may only be used from a context that may sleep.
44108ae12a0dSDavid Brownell  *
4411c373643bSMark Brown  * Parameters to this routine are always copied using a small buffer.
441233e34dc6SDavid Brownell  * Performance-sensitive or bulk transfer code should instead use
4413702ca026SAndy Shevchenko  * spi_{async,sync}() calls with DMA-safe buffers.
441497d56dc6SJavier Martinez Canillas  *
441597d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
44168ae12a0dSDavid Brownell  */
spi_write_then_read(struct spi_device * spi,const void * txbuf,unsigned n_tx,void * rxbuf,unsigned n_rx)44178ae12a0dSDavid Brownell int spi_write_then_read(struct spi_device *spi,
44180c4a1590SMark Brown 		const void *txbuf, unsigned n_tx,
44190c4a1590SMark Brown 		void *rxbuf, unsigned n_rx)
44208ae12a0dSDavid Brownell {
4421068f4070SDavid Brownell 	static DEFINE_MUTEX(lock);
44228ae12a0dSDavid Brownell 
44238ae12a0dSDavid Brownell 	int			status;
44248ae12a0dSDavid Brownell 	struct spi_message	message;
4425bdff549eSDavid Brownell 	struct spi_transfer	x[2];
44268ae12a0dSDavid Brownell 	u8			*local_buf;
44278ae12a0dSDavid Brownell 
4428350de7ceSAndy Shevchenko 	/*
4429350de7ceSAndy Shevchenko 	 * Use preallocated DMA-safe buffer if we can. We can't avoid
4430b3a223eeSMark Brown 	 * copying here, (as a pure convenience thing), but we can
4431b3a223eeSMark Brown 	 * keep heap costs out of the hot path unless someone else is
4432b3a223eeSMark Brown 	 * using the pre-allocated buffer or the transfer is too large.
44338ae12a0dSDavid Brownell 	 */
4434b3a223eeSMark Brown 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
44352cd94c8aSMark Brown 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
44362cd94c8aSMark Brown 				    GFP_KERNEL | GFP_DMA);
4437b3a223eeSMark Brown 		if (!local_buf)
4438b3a223eeSMark Brown 			return -ENOMEM;
4439b3a223eeSMark Brown 	} else {
4440b3a223eeSMark Brown 		local_buf = buf;
4441b3a223eeSMark Brown 	}
44428ae12a0dSDavid Brownell 
44438275c642SVitaly Wool 	spi_message_init(&message);
44445fe5f05eSJingoo Han 	memset(x, 0, sizeof(x));
4445bdff549eSDavid Brownell 	if (n_tx) {
4446bdff549eSDavid Brownell 		x[0].len = n_tx;
4447bdff549eSDavid Brownell 		spi_message_add_tail(&x[0], &message);
4448bdff549eSDavid Brownell 	}
4449bdff549eSDavid Brownell 	if (n_rx) {
4450bdff549eSDavid Brownell 		x[1].len = n_rx;
4451bdff549eSDavid Brownell 		spi_message_add_tail(&x[1], &message);
4452bdff549eSDavid Brownell 	}
44538275c642SVitaly Wool 
44548ae12a0dSDavid Brownell 	memcpy(local_buf, txbuf, n_tx);
4455bdff549eSDavid Brownell 	x[0].tx_buf = local_buf;
4456bdff549eSDavid Brownell 	x[1].rx_buf = local_buf + n_tx;
44578ae12a0dSDavid Brownell 
4458702ca026SAndy Shevchenko 	/* Do the I/O */
44598ae12a0dSDavid Brownell 	status = spi_sync(spi, &message);
44609b938b74SMarc Pignat 	if (status == 0)
4461bdff549eSDavid Brownell 		memcpy(rxbuf, x[1].rx_buf, n_rx);
44628ae12a0dSDavid Brownell 
4463bdff549eSDavid Brownell 	if (x[0].tx_buf == buf)
4464068f4070SDavid Brownell 		mutex_unlock(&lock);
44658ae12a0dSDavid Brownell 	else
44668ae12a0dSDavid Brownell 		kfree(local_buf);
44678ae12a0dSDavid Brownell 
44688ae12a0dSDavid Brownell 	return status;
44698ae12a0dSDavid Brownell }
44708ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_write_then_read);
44718ae12a0dSDavid Brownell 
44728ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
44738ae12a0dSDavid Brownell 
4474da21fde0SUwe Kleine-König #if IS_ENABLED(CONFIG_OF_DYNAMIC)
447595c8222fSDavid Jander /* Must call put_device() when done with returned spi_device device */
of_find_spi_device_by_node(struct device_node * node)4476da21fde0SUwe Kleine-König static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4477ce79d54aSPantelis Antoniou {
4478cfba5de9SSuzuki K Poulose 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4479cfba5de9SSuzuki K Poulose 
4480ce79d54aSPantelis Antoniou 	return dev ? to_spi_device(dev) : NULL;
4481ce79d54aSPantelis Antoniou }
4482ce79d54aSPantelis Antoniou 
448395c8222fSDavid Jander /* The spi controllers are not using spi_bus, so we find it with another way */
of_find_spi_controller_by_node(struct device_node * node)44848caab75fSGeert Uytterhoeven static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4485ce79d54aSPantelis Antoniou {
4486ce79d54aSPantelis Antoniou 	struct device *dev;
4487ce79d54aSPantelis Antoniou 
4488cfba5de9SSuzuki K Poulose 	dev = class_find_device_by_of_node(&spi_master_class, node);
44896c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4490cfba5de9SSuzuki K Poulose 		dev = class_find_device_by_of_node(&spi_slave_class, node);
4491ce79d54aSPantelis Antoniou 	if (!dev)
4492ce79d54aSPantelis Antoniou 		return NULL;
4493ce79d54aSPantelis Antoniou 
449495c8222fSDavid Jander 	/* Reference got in class_find_device */
44958caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
4496ce79d54aSPantelis Antoniou }
4497ce79d54aSPantelis Antoniou 
of_spi_notify(struct notifier_block * nb,unsigned long action,void * arg)4498ce79d54aSPantelis Antoniou static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4499ce79d54aSPantelis Antoniou 			 void *arg)
4500ce79d54aSPantelis Antoniou {
4501ce79d54aSPantelis Antoniou 	struct of_reconfig_data *rd = arg;
45028caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
4503ce79d54aSPantelis Antoniou 	struct spi_device *spi;
4504ce79d54aSPantelis Antoniou 
4505ce79d54aSPantelis Antoniou 	switch (of_reconfig_get_state_change(action, arg)) {
4506ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_ADD:
45078caab75fSGeert Uytterhoeven 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
45088caab75fSGeert Uytterhoeven 		if (ctlr == NULL)
450995c8222fSDavid Jander 			return NOTIFY_OK;	/* Not for us */
4510ce79d54aSPantelis Antoniou 
4511bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
45128caab75fSGeert Uytterhoeven 			put_device(&ctlr->dev);
4513bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4514bd6c1644SGeert Uytterhoeven 		}
4515bd6c1644SGeert Uytterhoeven 
45161a50d940SGeert Uytterhoeven 		/*
45171a50d940SGeert Uytterhoeven 		 * Clear the flag before adding the device so that fw_devlink
45181a50d940SGeert Uytterhoeven 		 * doesn't skip adding consumers to this device.
45191a50d940SGeert Uytterhoeven 		 */
45201a50d940SGeert Uytterhoeven 		rd->dn->fwnode.flags &= ~FWNODE_FLAG_NOT_DEVICE;
45218caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, rd->dn);
45228caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
4523ce79d54aSPantelis Antoniou 
4524ce79d54aSPantelis Antoniou 		if (IS_ERR(spi)) {
452525c56c88SRob Herring 			pr_err("%s: failed to create for '%pOF'\n",
452625c56c88SRob Herring 					__func__, rd->dn);
4527e0af98a7SRalf Ramsauer 			of_node_clear_flag(rd->dn, OF_POPULATED);
4528ce79d54aSPantelis Antoniou 			return notifier_from_errno(PTR_ERR(spi));
4529ce79d54aSPantelis Antoniou 		}
4530ce79d54aSPantelis Antoniou 		break;
4531ce79d54aSPantelis Antoniou 
4532ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_REMOVE:
453395c8222fSDavid Jander 		/* Already depopulated? */
4534bd6c1644SGeert Uytterhoeven 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4535bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4536bd6c1644SGeert Uytterhoeven 
453795c8222fSDavid Jander 		/* Find our device by node */
4538ce79d54aSPantelis Antoniou 		spi = of_find_spi_device_by_node(rd->dn);
4539ce79d54aSPantelis Antoniou 		if (spi == NULL)
454095c8222fSDavid Jander 			return NOTIFY_OK;	/* No? not meant for us */
4541ce79d54aSPantelis Antoniou 
454295c8222fSDavid Jander 		/* Unregister takes one ref away */
4543ce79d54aSPantelis Antoniou 		spi_unregister_device(spi);
4544ce79d54aSPantelis Antoniou 
454595c8222fSDavid Jander 		/* And put the reference of the find */
4546ce79d54aSPantelis Antoniou 		put_device(&spi->dev);
4547ce79d54aSPantelis Antoniou 		break;
4548ce79d54aSPantelis Antoniou 	}
4549ce79d54aSPantelis Antoniou 
4550ce79d54aSPantelis Antoniou 	return NOTIFY_OK;
4551ce79d54aSPantelis Antoniou }
4552ce79d54aSPantelis Antoniou 
4553ce79d54aSPantelis Antoniou static struct notifier_block spi_of_notifier = {
4554ce79d54aSPantelis Antoniou 	.notifier_call = of_spi_notify,
4555ce79d54aSPantelis Antoniou };
4556ce79d54aSPantelis Antoniou #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4557ce79d54aSPantelis Antoniou extern struct notifier_block spi_of_notifier;
4558ce79d54aSPantelis Antoniou #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4559ce79d54aSPantelis Antoniou 
45607f24467fSOctavian Purdila #if IS_ENABLED(CONFIG_ACPI)
spi_acpi_controller_match(struct device * dev,const void * data)45618caab75fSGeert Uytterhoeven static int spi_acpi_controller_match(struct device *dev, const void *data)
45627f24467fSOctavian Purdila {
45637f24467fSOctavian Purdila 	return ACPI_COMPANION(dev->parent) == data;
45647f24467fSOctavian Purdila }
45657f24467fSOctavian Purdila 
acpi_spi_find_controller_by_adev(struct acpi_device * adev)45668caab75fSGeert Uytterhoeven static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
45677f24467fSOctavian Purdila {
45687f24467fSOctavian Purdila 	struct device *dev;
45697f24467fSOctavian Purdila 
45707f24467fSOctavian Purdila 	dev = class_find_device(&spi_master_class, NULL, adev,
45718caab75fSGeert Uytterhoeven 				spi_acpi_controller_match);
45726c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
45736c364062SGeert Uytterhoeven 		dev = class_find_device(&spi_slave_class, NULL, adev,
45748caab75fSGeert Uytterhoeven 					spi_acpi_controller_match);
45757f24467fSOctavian Purdila 	if (!dev)
45767f24467fSOctavian Purdila 		return NULL;
45777f24467fSOctavian Purdila 
45788caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
45797f24467fSOctavian Purdila }
45807f24467fSOctavian Purdila 
acpi_spi_find_device_by_adev(struct acpi_device * adev)45817f24467fSOctavian Purdila static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
45827f24467fSOctavian Purdila {
45837f24467fSOctavian Purdila 	struct device *dev;
45847f24467fSOctavian Purdila 
458500500147SSuzuki K Poulose 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
45865b16668eSWolfram Sang 	return to_spi_device(dev);
45877f24467fSOctavian Purdila }
45887f24467fSOctavian Purdila 
acpi_spi_notify(struct notifier_block * nb,unsigned long value,void * arg)45897f24467fSOctavian Purdila static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
45907f24467fSOctavian Purdila 			   void *arg)
45917f24467fSOctavian Purdila {
45927f24467fSOctavian Purdila 	struct acpi_device *adev = arg;
45938caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
45947f24467fSOctavian Purdila 	struct spi_device *spi;
45957f24467fSOctavian Purdila 
45967f24467fSOctavian Purdila 	switch (value) {
45977f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_ADD:
459862fcb99bSRafael J. Wysocki 		ctlr = acpi_spi_find_controller_by_adev(acpi_dev_parent(adev));
45998caab75fSGeert Uytterhoeven 		if (!ctlr)
46007f24467fSOctavian Purdila 			break;
46017f24467fSOctavian Purdila 
46028caab75fSGeert Uytterhoeven 		acpi_register_spi_device(ctlr, adev);
46038caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
46047f24467fSOctavian Purdila 		break;
46057f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_REMOVE:
46067f24467fSOctavian Purdila 		if (!acpi_device_enumerated(adev))
46077f24467fSOctavian Purdila 			break;
46087f24467fSOctavian Purdila 
46097f24467fSOctavian Purdila 		spi = acpi_spi_find_device_by_adev(adev);
46107f24467fSOctavian Purdila 		if (!spi)
46117f24467fSOctavian Purdila 			break;
46127f24467fSOctavian Purdila 
46137f24467fSOctavian Purdila 		spi_unregister_device(spi);
46147f24467fSOctavian Purdila 		put_device(&spi->dev);
46157f24467fSOctavian Purdila 		break;
46167f24467fSOctavian Purdila 	}
46177f24467fSOctavian Purdila 
46187f24467fSOctavian Purdila 	return NOTIFY_OK;
46197f24467fSOctavian Purdila }
46207f24467fSOctavian Purdila 
46217f24467fSOctavian Purdila static struct notifier_block spi_acpi_notifier = {
46227f24467fSOctavian Purdila 	.notifier_call = acpi_spi_notify,
46237f24467fSOctavian Purdila };
46247f24467fSOctavian Purdila #else
46257f24467fSOctavian Purdila extern struct notifier_block spi_acpi_notifier;
46267f24467fSOctavian Purdila #endif
46277f24467fSOctavian Purdila 
spi_init(void)46288ae12a0dSDavid Brownell static int __init spi_init(void)
46298ae12a0dSDavid Brownell {
4630b885244eSDavid Brownell 	int	status;
46318ae12a0dSDavid Brownell 
4632e94b1766SChristoph Lameter 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4633b885244eSDavid Brownell 	if (!buf) {
4634b885244eSDavid Brownell 		status = -ENOMEM;
4635b885244eSDavid Brownell 		goto err0;
46368ae12a0dSDavid Brownell 	}
4637b885244eSDavid Brownell 
4638b885244eSDavid Brownell 	status = bus_register(&spi_bus_type);
4639b885244eSDavid Brownell 	if (status < 0)
4640b885244eSDavid Brownell 		goto err1;
4641b885244eSDavid Brownell 
4642b885244eSDavid Brownell 	status = class_register(&spi_master_class);
4643b885244eSDavid Brownell 	if (status < 0)
4644b885244eSDavid Brownell 		goto err2;
4645ce79d54aSPantelis Antoniou 
46466c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
46476c364062SGeert Uytterhoeven 		status = class_register(&spi_slave_class);
46486c364062SGeert Uytterhoeven 		if (status < 0)
46496c364062SGeert Uytterhoeven 			goto err3;
46506c364062SGeert Uytterhoeven 	}
46516c364062SGeert Uytterhoeven 
46525267720eSFabio Estevam 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4653ce79d54aSPantelis Antoniou 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
46547f24467fSOctavian Purdila 	if (IS_ENABLED(CONFIG_ACPI))
46557f24467fSOctavian Purdila 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4656ce79d54aSPantelis Antoniou 
4657b885244eSDavid Brownell 	return 0;
4658b885244eSDavid Brownell 
46596c364062SGeert Uytterhoeven err3:
46606c364062SGeert Uytterhoeven 	class_unregister(&spi_master_class);
4661b885244eSDavid Brownell err2:
4662b885244eSDavid Brownell 	bus_unregister(&spi_bus_type);
4663b885244eSDavid Brownell err1:
4664b885244eSDavid Brownell 	kfree(buf);
4665b885244eSDavid Brownell 	buf = NULL;
4666b885244eSDavid Brownell err0:
4667b885244eSDavid Brownell 	return status;
4668b885244eSDavid Brownell }
4669b885244eSDavid Brownell 
4670350de7ceSAndy Shevchenko /*
4671350de7ceSAndy Shevchenko  * A board_info is normally registered in arch_initcall(),
4672350de7ceSAndy Shevchenko  * but even essential drivers wait till later.
4673b885244eSDavid Brownell  *
4674350de7ceSAndy Shevchenko  * REVISIT only boardinfo really needs static linking. The rest (device and
4675350de7ceSAndy Shevchenko  * driver registration) _could_ be dynamically linked (modular) ... Costs
4676b885244eSDavid Brownell  * include needing to have boardinfo data structures be much more public.
46778ae12a0dSDavid Brownell  */
4678673c0c00SDavid Brownell postcore_initcall(spi_init);
4679