xref: /linux/drivers/spi/spi.c (revision 9086d0f23b7c292f162a828967975e29e97c0680)
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 
478ae12a0dSDavid Brownell static void spidev_release(struct device *dev)
488ae12a0dSDavid Brownell {
490ffa0285SHans-Peter Nilsson 	struct spi_device	*spi = to_spi_device(dev);
508ae12a0dSDavid Brownell 
518caab75fSGeert Uytterhoeven 	spi_controller_put(spi->controller);
525039563eSTrent Piepho 	kfree(spi->driver_override);
536598b91bSDavid Jander 	free_percpu(spi->pcpu_statistics);
5407a389feSRoman Tereshonkov 	kfree(spi);
558ae12a0dSDavid Brownell }
568ae12a0dSDavid Brownell 
578ae12a0dSDavid Brownell static ssize_t
588ae12a0dSDavid Brownell modalias_show(struct device *dev, struct device_attribute *a, char *buf)
598ae12a0dSDavid Brownell {
608ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
618c4ff6d0SZhang Rui 	int len;
628c4ff6d0SZhang Rui 
638c4ff6d0SZhang Rui 	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
648c4ff6d0SZhang Rui 	if (len != -ENODEV)
658c4ff6d0SZhang Rui 		return len;
668ae12a0dSDavid Brownell 
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 
715039563eSTrent Piepho static ssize_t driver_override_store(struct device *dev,
725039563eSTrent Piepho 				     struct device_attribute *a,
735039563eSTrent Piepho 				     const char *buf, size_t count)
745039563eSTrent Piepho {
755039563eSTrent Piepho 	struct spi_device *spi = to_spi_device(dev);
7619368f0fSKrzysztof Kozlowski 	int ret;
775039563eSTrent Piepho 
7819368f0fSKrzysztof Kozlowski 	ret = driver_set_override(dev, &spi->driver_override, buf, count);
7919368f0fSKrzysztof Kozlowski 	if (ret)
8019368f0fSKrzysztof Kozlowski 		return ret;
815039563eSTrent Piepho 
825039563eSTrent Piepho 	return count;
835039563eSTrent Piepho }
845039563eSTrent Piepho 
855039563eSTrent Piepho static ssize_t driver_override_show(struct device *dev,
865039563eSTrent Piepho 				    struct device_attribute *a, char *buf)
875039563eSTrent Piepho {
885039563eSTrent Piepho 	const struct spi_device *spi = to_spi_device(dev);
895039563eSTrent Piepho 	ssize_t len;
905039563eSTrent Piepho 
915039563eSTrent Piepho 	device_lock(dev);
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 
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 
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 
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  */
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 
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 
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 
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 
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 
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 
429676e7c25SUlf Hansson 	ret = dev_pm_domain_attach(dev, true);
43071f277a7SUlf Hansson 	if (ret)
43171f277a7SUlf Hansson 		return ret;
43271f277a7SUlf Hansson 
433440408dbSUwe Kleine-König 	if (sdrv->probe) {
43444af7927SJon Hunter 		ret = sdrv->probe(spi);
43533cf00e5SMika Westerberg 		if (ret)
436676e7c25SUlf Hansson 			dev_pm_domain_detach(dev, true);
437440408dbSUwe Kleine-König 	}
43833cf00e5SMika Westerberg 
43933cf00e5SMika Westerberg 	return ret;
440b885244eSDavid Brownell }
441b885244eSDavid Brownell 
442fc7a6209SUwe Kleine-König static void spi_remove(struct device *dev)
443b885244eSDavid Brownell {
444b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
445b885244eSDavid Brownell 
446a0386bbaSUwe Kleine-König 	if (sdrv->remove)
447a0386bbaSUwe Kleine-König 		sdrv->remove(to_spi_device(dev));
4487795d475SUwe Kleine-König 
449676e7c25SUlf Hansson 	dev_pm_domain_detach(dev, true);
450b885244eSDavid Brownell }
451b885244eSDavid Brownell 
4529db34ee6SUwe Kleine-König static void spi_shutdown(struct device *dev)
453b885244eSDavid Brownell {
454a6f483b2SMarek Szyprowski 	if (dev->driver) {
455b885244eSDavid Brownell 		const struct spi_driver	*sdrv = to_spi_driver(dev->driver);
456b885244eSDavid Brownell 
4579db34ee6SUwe Kleine-König 		if (sdrv->shutdown)
458b885244eSDavid Brownell 			sdrv->shutdown(to_spi_device(dev));
459b885244eSDavid Brownell 	}
460a6f483b2SMarek Szyprowski }
461b885244eSDavid Brownell 
4626df534ccSGreg Kroah-Hartman const struct bus_type spi_bus_type = {
4639db34ee6SUwe Kleine-König 	.name		= "spi",
4649db34ee6SUwe Kleine-König 	.dev_groups	= spi_dev_groups,
4659db34ee6SUwe Kleine-König 	.match		= spi_match_device,
4669db34ee6SUwe Kleine-König 	.uevent		= spi_uevent,
4679db34ee6SUwe Kleine-König 	.probe		= spi_probe,
4689db34ee6SUwe Kleine-König 	.remove		= spi_remove,
4699db34ee6SUwe Kleine-König 	.shutdown	= spi_shutdown,
4709db34ee6SUwe Kleine-König };
4719db34ee6SUwe Kleine-König EXPORT_SYMBOL_GPL(spi_bus_type);
4729db34ee6SUwe Kleine-König 
47333e34dc6SDavid Brownell /**
474ca5d2485SAndrew F. Davis  * __spi_register_driver - register a SPI driver
47588c9321dSThierry Reding  * @owner: owner module of the driver to register
47633e34dc6SDavid Brownell  * @sdrv: the driver to register
47733e34dc6SDavid Brownell  * Context: can sleep
47897d56dc6SJavier Martinez Canillas  *
47997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
48033e34dc6SDavid Brownell  */
481ca5d2485SAndrew F. Davis int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
482b885244eSDavid Brownell {
483ca5d2485SAndrew F. Davis 	sdrv->driver.owner = owner;
484b885244eSDavid Brownell 	sdrv->driver.bus = &spi_bus_type;
4855fa6863bSMark Brown 
4865fa6863bSMark Brown 	/*
4875fa6863bSMark Brown 	 * For Really Good Reasons we use spi: modaliases not of:
4885fa6863bSMark Brown 	 * modaliases for DT so module autoloading won't work if we
4895fa6863bSMark Brown 	 * don't have a spi_device_id as well as a compatible string.
4905fa6863bSMark Brown 	 */
4915fa6863bSMark Brown 	if (sdrv->driver.of_match_table) {
4925fa6863bSMark Brown 		const struct of_device_id *of_id;
4935fa6863bSMark Brown 
4945fa6863bSMark Brown 		for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
4955fa6863bSMark Brown 		     of_id++) {
4965fa6863bSMark Brown 			const char *of_name;
4975fa6863bSMark Brown 
4985fa6863bSMark Brown 			/* Strip off any vendor prefix */
4995fa6863bSMark Brown 			of_name = strnchr(of_id->compatible,
5005fa6863bSMark Brown 					  sizeof(of_id->compatible), ',');
5015fa6863bSMark Brown 			if (of_name)
5025fa6863bSMark Brown 				of_name++;
5035fa6863bSMark Brown 			else
5045fa6863bSMark Brown 				of_name = of_id->compatible;
5055fa6863bSMark Brown 
5065fa6863bSMark Brown 			if (sdrv->id_table) {
5075fa6863bSMark Brown 				const struct spi_device_id *spi_id;
5085fa6863bSMark Brown 
5093f076575SAndy Shevchenko 				spi_id = spi_match_id(sdrv->id_table, of_name);
510b79332efSAndy Shevchenko 				if (spi_id)
5115fa6863bSMark Brown 					continue;
5125fa6863bSMark Brown 			} else {
5135fa6863bSMark Brown 				if (strcmp(sdrv->driver.name, of_name) == 0)
5145fa6863bSMark Brown 					continue;
5155fa6863bSMark Brown 			}
5165fa6863bSMark Brown 
5175fa6863bSMark Brown 			pr_warn("SPI driver %s has no spi_device_id for %s\n",
5185fa6863bSMark Brown 				sdrv->driver.name, of_id->compatible);
5195fa6863bSMark Brown 		}
5205fa6863bSMark Brown 	}
5215fa6863bSMark Brown 
522b885244eSDavid Brownell 	return driver_register(&sdrv->driver);
523b885244eSDavid Brownell }
524ca5d2485SAndrew F. Davis EXPORT_SYMBOL_GPL(__spi_register_driver);
525b885244eSDavid Brownell 
5268ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
5278ae12a0dSDavid Brownell 
528350de7ceSAndy Shevchenko /*
529350de7ceSAndy Shevchenko  * SPI devices should normally not be created by SPI device drivers; that
5308caab75fSGeert Uytterhoeven  * would make them board-specific.  Similarly with SPI controller drivers.
5318ae12a0dSDavid Brownell  * Device registration normally goes into like arch/.../mach.../board-YYY.c
5328ae12a0dSDavid Brownell  * with other readonly (flashable) information about mainboard devices.
5338ae12a0dSDavid Brownell  */
5348ae12a0dSDavid Brownell 
5358ae12a0dSDavid Brownell struct boardinfo {
5368ae12a0dSDavid Brownell 	struct list_head	list;
5372b9603a0SFeng Tang 	struct spi_board_info	board_info;
5388ae12a0dSDavid Brownell };
5398ae12a0dSDavid Brownell 
5408ae12a0dSDavid Brownell static LIST_HEAD(board_list);
5418caab75fSGeert Uytterhoeven static LIST_HEAD(spi_controller_list);
5422b9603a0SFeng Tang 
5432b9603a0SFeng Tang /*
544be73e323SAndy Shevchenko  * Used to protect add/del operation for board_info list and
545350de7ceSAndy Shevchenko  * spi_controller list, and their matching process also used
546350de7ceSAndy Shevchenko  * to protect object of type struct idr.
5472b9603a0SFeng Tang  */
54894040828SMatthias Kaehlcke static DEFINE_MUTEX(board_lock);
5498ae12a0dSDavid Brownell 
550dc87c98eSGrant Likely /**
551dc87c98eSGrant Likely  * spi_alloc_device - Allocate a new SPI device
5528caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
553dc87c98eSGrant Likely  * Context: can sleep
554dc87c98eSGrant Likely  *
555dc87c98eSGrant Likely  * Allows a driver to allocate and initialize a spi_device without
556dc87c98eSGrant Likely  * registering it immediately.  This allows a driver to directly
557dc87c98eSGrant Likely  * fill the spi_device with device parameters before calling
558dc87c98eSGrant Likely  * spi_add_device() on it.
559dc87c98eSGrant Likely  *
560dc87c98eSGrant Likely  * Caller is responsible to call spi_add_device() on the returned
5618caab75fSGeert Uytterhoeven  * spi_device structure to add it to the SPI controller.  If the caller
562dc87c98eSGrant Likely  * needs to discard the spi_device without adding it, then it should
563dc87c98eSGrant Likely  * call spi_dev_put() on it.
564dc87c98eSGrant Likely  *
56597d56dc6SJavier Martinez Canillas  * Return: a pointer to the new device, or NULL.
566dc87c98eSGrant Likely  */
567e3dc1399SStefan Binding struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
568dc87c98eSGrant Likely {
569dc87c98eSGrant Likely 	struct spi_device	*spi;
570dc87c98eSGrant Likely 
5718caab75fSGeert Uytterhoeven 	if (!spi_controller_get(ctlr))
572dc87c98eSGrant Likely 		return NULL;
573dc87c98eSGrant Likely 
5745fe5f05eSJingoo Han 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
575dc87c98eSGrant Likely 	if (!spi) {
5768caab75fSGeert Uytterhoeven 		spi_controller_put(ctlr);
577dc87c98eSGrant Likely 		return NULL;
578dc87c98eSGrant Likely 	}
579dc87c98eSGrant Likely 
5806598b91bSDavid Jander 	spi->pcpu_statistics = spi_alloc_pcpu_stats(NULL);
5816598b91bSDavid Jander 	if (!spi->pcpu_statistics) {
5826598b91bSDavid Jander 		kfree(spi);
5836598b91bSDavid Jander 		spi_controller_put(ctlr);
5846598b91bSDavid Jander 		return NULL;
5856598b91bSDavid Jander 	}
5866598b91bSDavid Jander 
587620d269fSUwe Kleine-König 	spi->controller = ctlr;
5888caab75fSGeert Uytterhoeven 	spi->dev.parent = &ctlr->dev;
589dc87c98eSGrant Likely 	spi->dev.bus = &spi_bus_type;
590dc87c98eSGrant Likely 	spi->dev.release = spidev_release;
591ea235786SJohn Garry 	spi->mode = ctlr->buswidth_override_bits;
592eca2ebc7SMartin Sperl 
593dc87c98eSGrant Likely 	device_initialize(&spi->dev);
594dc87c98eSGrant Likely 	return spi;
595dc87c98eSGrant Likely }
596e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_alloc_device);
597dc87c98eSGrant Likely 
598e13ac47bSJarkko Nikula static void spi_dev_set_name(struct spi_device *spi)
599e13ac47bSJarkko Nikula {
600e13ac47bSJarkko Nikula 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
601e13ac47bSJarkko Nikula 
602e13ac47bSJarkko Nikula 	if (adev) {
603e13ac47bSJarkko Nikula 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
604e13ac47bSJarkko Nikula 		return;
605e13ac47bSJarkko Nikula 	}
606e13ac47bSJarkko Nikula 
6078caab75fSGeert Uytterhoeven 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
608303feb3cSAmit Kumar Mahapatra 		     spi_get_chipselect(spi, 0));
609e13ac47bSJarkko Nikula }
610e13ac47bSJarkko Nikula 
611*9086d0f2SAndy Shevchenko static inline int spi_dev_check_cs(struct device *dev,
612*9086d0f2SAndy Shevchenko 				   struct spi_device *spi, u8 idx,
613*9086d0f2SAndy Shevchenko 				   struct spi_device *new_spi, u8 new_idx)
614*9086d0f2SAndy Shevchenko {
615*9086d0f2SAndy Shevchenko 	u8 cs, cs_new;
616*9086d0f2SAndy Shevchenko 	u8 idx_new;
617*9086d0f2SAndy Shevchenko 
618*9086d0f2SAndy Shevchenko 	cs = spi_get_chipselect(spi, idx);
619*9086d0f2SAndy Shevchenko 	for (idx_new = new_idx; idx_new < SPI_CS_CNT_MAX; idx_new++) {
620*9086d0f2SAndy Shevchenko 		cs_new = spi_get_chipselect(new_spi, idx_new);
621*9086d0f2SAndy Shevchenko 		if (cs != 0xFF && cs_new != 0xFF && cs == cs_new) {
622*9086d0f2SAndy Shevchenko 			dev_err(dev, "chipselect %u already in use\n", cs_new);
623*9086d0f2SAndy Shevchenko 			return -EBUSY;
624*9086d0f2SAndy Shevchenko 		}
625*9086d0f2SAndy Shevchenko 	}
626*9086d0f2SAndy Shevchenko 	return 0;
627*9086d0f2SAndy Shevchenko }
628*9086d0f2SAndy Shevchenko 
629b6fb8d3aSMika Westerberg static int spi_dev_check(struct device *dev, void *data)
630b6fb8d3aSMika Westerberg {
631b6fb8d3aSMika Westerberg 	struct spi_device *spi = to_spi_device(dev);
632b6fb8d3aSMika Westerberg 	struct spi_device *new_spi = data;
633*9086d0f2SAndy Shevchenko 	int status, idx;
634b6fb8d3aSMika Westerberg 
6354d8ff6b0SAmit Kumar Mahapatra 	if (spi->controller == new_spi->controller) {
6364d8ff6b0SAmit Kumar Mahapatra 		for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
637*9086d0f2SAndy Shevchenko 			status = spi_dev_check_cs(dev, spi, idx, new_spi, 0);
638*9086d0f2SAndy Shevchenko 			if (status)
639*9086d0f2SAndy Shevchenko 				return status;
6404d8ff6b0SAmit Kumar Mahapatra 		}
6414d8ff6b0SAmit Kumar Mahapatra 	}
642b6fb8d3aSMika Westerberg 	return 0;
643b6fb8d3aSMika Westerberg }
644b6fb8d3aSMika Westerberg 
645c7299feaSSaravana Kannan static void spi_cleanup(struct spi_device *spi)
646c7299feaSSaravana Kannan {
647c7299feaSSaravana Kannan 	if (spi->controller->cleanup)
648c7299feaSSaravana Kannan 		spi->controller->cleanup(spi);
649c7299feaSSaravana Kannan }
650c7299feaSSaravana Kannan 
6510c79378cSSebastian Reichel static int __spi_add_device(struct spi_device *spi)
6520c79378cSSebastian Reichel {
6530c79378cSSebastian Reichel 	struct spi_controller *ctlr = spi->controller;
6540c79378cSSebastian Reichel 	struct device *dev = ctlr->dev.parent;
655*9086d0f2SAndy Shevchenko 	int status, idx;
656*9086d0f2SAndy Shevchenko 	u8 cs;
6570c79378cSSebastian Reichel 
6584d8ff6b0SAmit Kumar Mahapatra 	for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
65936124deaSAndy Shevchenko 		/* Chipselects are numbered 0..max; validate. */
6604d8ff6b0SAmit Kumar Mahapatra 		cs = spi_get_chipselect(spi, idx);
6614d8ff6b0SAmit Kumar Mahapatra 		if (cs != 0xFF && cs >= ctlr->num_chipselect) {
6624d8ff6b0SAmit Kumar Mahapatra 			dev_err(dev, "cs%d >= max %d\n", spi_get_chipselect(spi, idx),
66336124deaSAndy Shevchenko 				ctlr->num_chipselect);
66436124deaSAndy Shevchenko 			return -EINVAL;
66536124deaSAndy Shevchenko 		}
6664d8ff6b0SAmit Kumar Mahapatra 	}
6674d8ff6b0SAmit Kumar Mahapatra 
6684d8ff6b0SAmit Kumar Mahapatra 	/*
6694d8ff6b0SAmit Kumar Mahapatra 	 * Make sure that multiple logical CS doesn't map to the same physical CS.
6704d8ff6b0SAmit Kumar Mahapatra 	 * For example, spi->chip_select[0] != spi->chip_select[1] and so on.
6714d8ff6b0SAmit Kumar Mahapatra 	 */
6724d8ff6b0SAmit Kumar Mahapatra 	for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
673*9086d0f2SAndy Shevchenko 		status = spi_dev_check_cs(dev, spi, idx, spi, idx + 1);
674*9086d0f2SAndy Shevchenko 		if (status)
675*9086d0f2SAndy Shevchenko 			return status;
6764d8ff6b0SAmit Kumar Mahapatra 	}
67736124deaSAndy Shevchenko 
67836124deaSAndy Shevchenko 	/* Set the bus ID string */
67936124deaSAndy Shevchenko 	spi_dev_set_name(spi);
68036124deaSAndy Shevchenko 
6816bfb15f3SUwe Kleine-König 	/*
6826bfb15f3SUwe Kleine-König 	 * We need to make sure there's no other device with this
6836bfb15f3SUwe Kleine-König 	 * chipselect **BEFORE** we call setup(), else we'll trash
6846bfb15f3SUwe Kleine-König 	 * its configuration.
6856bfb15f3SUwe Kleine-König 	 */
6860c79378cSSebastian Reichel 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
6874d8ff6b0SAmit Kumar Mahapatra 	if (status)
6880c79378cSSebastian Reichel 		return status;
6890c79378cSSebastian Reichel 
6900c79378cSSebastian Reichel 	/* Controller may unregister concurrently */
6910c79378cSSebastian Reichel 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
6920c79378cSSebastian Reichel 	    !device_is_registered(&ctlr->dev)) {
6930c79378cSSebastian Reichel 		return -ENODEV;
6940c79378cSSebastian Reichel 	}
6950c79378cSSebastian Reichel 
6964d8ff6b0SAmit Kumar Mahapatra 	if (ctlr->cs_gpiods) {
6974d8ff6b0SAmit Kumar Mahapatra 		u8 cs;
6984d8ff6b0SAmit Kumar Mahapatra 
6994d8ff6b0SAmit Kumar Mahapatra 		for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
7004d8ff6b0SAmit Kumar Mahapatra 			cs = spi_get_chipselect(spi, idx);
7014d8ff6b0SAmit Kumar Mahapatra 			if (cs != 0xFF)
7024d8ff6b0SAmit Kumar Mahapatra 				spi_set_csgpiod(spi, idx, ctlr->cs_gpiods[cs]);
7034d8ff6b0SAmit Kumar Mahapatra 		}
7044d8ff6b0SAmit Kumar Mahapatra 	}
7050c79378cSSebastian Reichel 
706350de7ceSAndy Shevchenko 	/*
707350de7ceSAndy Shevchenko 	 * Drivers may modify this initial i/o setup, but will
7080c79378cSSebastian Reichel 	 * normally rely on the device being setup.  Devices
7090c79378cSSebastian Reichel 	 * using SPI_CS_HIGH can't coexist well otherwise...
7100c79378cSSebastian Reichel 	 */
7110c79378cSSebastian Reichel 	status = spi_setup(spi);
7120c79378cSSebastian Reichel 	if (status < 0) {
7130c79378cSSebastian Reichel 		dev_err(dev, "can't setup %s, status %d\n",
7140c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
7150c79378cSSebastian Reichel 		return status;
7160c79378cSSebastian Reichel 	}
7170c79378cSSebastian Reichel 
7180c79378cSSebastian Reichel 	/* Device may be bound to an active driver when this returns */
7190c79378cSSebastian Reichel 	status = device_add(&spi->dev);
7200c79378cSSebastian Reichel 	if (status < 0) {
7210c79378cSSebastian Reichel 		dev_err(dev, "can't add %s, status %d\n",
7220c79378cSSebastian Reichel 				dev_name(&spi->dev), status);
7230c79378cSSebastian Reichel 		spi_cleanup(spi);
7240c79378cSSebastian Reichel 	} else {
7250c79378cSSebastian Reichel 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
7260c79378cSSebastian Reichel 	}
7270c79378cSSebastian Reichel 
7280c79378cSSebastian Reichel 	return status;
7290c79378cSSebastian Reichel }
7300c79378cSSebastian Reichel 
731dc87c98eSGrant Likely /**
732dc87c98eSGrant Likely  * spi_add_device - Add spi_device allocated with spi_alloc_device
733dc87c98eSGrant Likely  * @spi: spi_device to register
734dc87c98eSGrant Likely  *
735dc87c98eSGrant Likely  * Companion function to spi_alloc_device.  Devices allocated with
736702ca026SAndy Shevchenko  * spi_alloc_device can be added onto the SPI bus with this function.
737dc87c98eSGrant Likely  *
73897d56dc6SJavier Martinez Canillas  * Return: 0 on success; negative errno on failure
739dc87c98eSGrant Likely  */
740e3dc1399SStefan Binding int spi_add_device(struct spi_device *spi)
741dc87c98eSGrant Likely {
7428caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
743dc87c98eSGrant Likely 	int status;
744dc87c98eSGrant Likely 
7454d8ff6b0SAmit Kumar Mahapatra 	/* Set the bus ID string */
7464d8ff6b0SAmit Kumar Mahapatra 	spi_dev_set_name(spi);
7474d8ff6b0SAmit Kumar Mahapatra 
7486098475dSMark Brown 	mutex_lock(&ctlr->add_lock);
7490c79378cSSebastian Reichel 	status = __spi_add_device(spi);
7506098475dSMark Brown 	mutex_unlock(&ctlr->add_lock);
751e48880e0SDavid Brownell 	return status;
752dc87c98eSGrant Likely }
753e3dc1399SStefan Binding EXPORT_SYMBOL_GPL(spi_add_device);
7548ae12a0dSDavid Brownell 
7555ee91605SAndy Shevchenko static void spi_set_all_cs_unused(struct spi_device *spi)
7565ee91605SAndy Shevchenko {
7575ee91605SAndy Shevchenko 	u8 idx;
7585ee91605SAndy Shevchenko 
7595ee91605SAndy Shevchenko 	/*
7605ee91605SAndy Shevchenko 	 * Zero(0) is a valid physical CS value and can be located at any
7615ee91605SAndy Shevchenko 	 * logical CS in the spi->chip_select[]. If all the physical CS
7625ee91605SAndy Shevchenko 	 * are initialized to 0 then It would be difficult to differentiate
7635ee91605SAndy Shevchenko 	 * between a valid physical CS 0 & an unused logical CS whose physical
7645ee91605SAndy Shevchenko 	 * CS can be 0. As a solution to this issue initialize all the CS to 0xFF.
7655ee91605SAndy Shevchenko 	 * Now all the unused logical CS will have 0xFF physical CS value & can be
7665ee91605SAndy Shevchenko 	 * ignore while performing physical CS validity checks.
7675ee91605SAndy Shevchenko 	 */
7685ee91605SAndy Shevchenko 	for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
7695ee91605SAndy Shevchenko 		spi_set_chipselect(spi, idx, 0xFF);
7705ee91605SAndy Shevchenko }
7715ee91605SAndy Shevchenko 
77233e34dc6SDavid Brownell /**
77333e34dc6SDavid Brownell  * spi_new_device - instantiate one new SPI device
7748caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
77533e34dc6SDavid Brownell  * @chip: Describes the SPI device
77633e34dc6SDavid Brownell  * Context: can sleep
77733e34dc6SDavid Brownell  *
77833e34dc6SDavid Brownell  * On typical mainboards, this is purely internal; and it's not needed
7798ae12a0dSDavid Brownell  * after board init creates the hard-wired devices.  Some development
7808ae12a0dSDavid Brownell  * platforms may not be able to use spi_register_board_info though, and
7818ae12a0dSDavid Brownell  * this is exported so that for example a USB or parport based adapter
7828ae12a0dSDavid Brownell  * driver could add devices (which it would learn about out-of-band).
783082c8cb4SDavid Brownell  *
78497d56dc6SJavier Martinez Canillas  * Return: the new device, or NULL.
7858ae12a0dSDavid Brownell  */
7868caab75fSGeert Uytterhoeven struct spi_device *spi_new_device(struct spi_controller *ctlr,
787e9d5a461SAdrian Bunk 				  struct spi_board_info *chip)
7888ae12a0dSDavid Brownell {
7898ae12a0dSDavid Brownell 	struct spi_device	*proxy;
7908ae12a0dSDavid Brownell 	int			status;
7918ae12a0dSDavid Brownell 
792350de7ceSAndy Shevchenko 	/*
793350de7ceSAndy Shevchenko 	 * NOTE:  caller did any chip->bus_num checks necessary.
794082c8cb4SDavid Brownell 	 *
795082c8cb4SDavid Brownell 	 * Also, unless we change the return value convention to use
796082c8cb4SDavid Brownell 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
797082c8cb4SDavid Brownell 	 * suggests syslogged diagnostics are best here (ugh).
798082c8cb4SDavid Brownell 	 */
799082c8cb4SDavid Brownell 
8008caab75fSGeert Uytterhoeven 	proxy = spi_alloc_device(ctlr);
801dc87c98eSGrant Likely 	if (!proxy)
8028ae12a0dSDavid Brownell 		return NULL;
8038ae12a0dSDavid Brownell 
804102eb975SGrant Likely 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
805102eb975SGrant Likely 
8065ee91605SAndy Shevchenko 	/* Use provided chip-select for proxy device */
8075ee91605SAndy Shevchenko 	spi_set_all_cs_unused(proxy);
808303feb3cSAmit Kumar Mahapatra 	spi_set_chipselect(proxy, 0, chip->chip_select);
8095ee91605SAndy Shevchenko 
8108ae12a0dSDavid Brownell 	proxy->max_speed_hz = chip->max_speed_hz;
811980a01c9SDavid Brownell 	proxy->mode = chip->mode;
8128ae12a0dSDavid Brownell 	proxy->irq = chip->irq;
81351e99de5SWolfram Sang 	strscpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
8148ae12a0dSDavid Brownell 	proxy->dev.platform_data = (void *) chip->platform_data;
8158ae12a0dSDavid Brownell 	proxy->controller_data = chip->controller_data;
8168ae12a0dSDavid Brownell 	proxy->controller_state = NULL;
8174d8ff6b0SAmit Kumar Mahapatra 	/*
8184d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[i] gives the corresponding physical CS for logical CS i
8194d8ff6b0SAmit Kumar Mahapatra 	 * logical CS number is represented by setting the ith bit in spi->cs_index_mask
8204d8ff6b0SAmit Kumar Mahapatra 	 * So, for example, if spi->cs_index_mask = 0x01 then logical CS number is 0 and
8214d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[0] will give the physical CS.
8224d8ff6b0SAmit Kumar Mahapatra 	 * By default spi->chip_select[0] will hold the physical CS number so, set
8234d8ff6b0SAmit Kumar Mahapatra 	 * spi->cs_index_mask as 0x01.
8244d8ff6b0SAmit Kumar Mahapatra 	 */
8254d8ff6b0SAmit Kumar Mahapatra 	proxy->cs_index_mask = 0x01;
8268ae12a0dSDavid Brownell 
82747afc77bSHeikki Krogerus 	if (chip->swnode) {
82847afc77bSHeikki Krogerus 		status = device_add_software_node(&proxy->dev, chip->swnode);
829826cf175SDmitry Torokhov 		if (status) {
8309d902c2aSColin Ian King 			dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
831826cf175SDmitry Torokhov 				chip->modalias, status);
832826cf175SDmitry Torokhov 			goto err_dev_put;
833826cf175SDmitry Torokhov 		}
8348ae12a0dSDavid Brownell 	}
835dc87c98eSGrant Likely 
836826cf175SDmitry Torokhov 	status = spi_add_device(proxy);
837826cf175SDmitry Torokhov 	if (status < 0)
838df41a5daSHeikki Krogerus 		goto err_dev_put;
839826cf175SDmitry Torokhov 
840dc87c98eSGrant Likely 	return proxy;
841826cf175SDmitry Torokhov 
842826cf175SDmitry Torokhov err_dev_put:
843df41a5daSHeikki Krogerus 	device_remove_software_node(&proxy->dev);
844826cf175SDmitry Torokhov 	spi_dev_put(proxy);
845826cf175SDmitry Torokhov 	return NULL;
846dc87c98eSGrant Likely }
8478ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_new_device);
8488ae12a0dSDavid Brownell 
8493b1884c2SGeert Uytterhoeven /**
8503b1884c2SGeert Uytterhoeven  * spi_unregister_device - unregister a single SPI device
8513b1884c2SGeert Uytterhoeven  * @spi: spi_device to unregister
8523b1884c2SGeert Uytterhoeven  *
8533b1884c2SGeert Uytterhoeven  * Start making the passed SPI device vanish. Normally this would be handled
8548caab75fSGeert Uytterhoeven  * by spi_unregister_controller().
8553b1884c2SGeert Uytterhoeven  */
8563b1884c2SGeert Uytterhoeven void spi_unregister_device(struct spi_device *spi)
8573b1884c2SGeert Uytterhoeven {
858bd6c1644SGeert Uytterhoeven 	if (!spi)
859bd6c1644SGeert Uytterhoeven 		return;
860bd6c1644SGeert Uytterhoeven 
8618324147fSJohan Hovold 	if (spi->dev.of_node) {
862bd6c1644SGeert Uytterhoeven 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
8638324147fSJohan Hovold 		of_node_put(spi->dev.of_node);
8648324147fSJohan Hovold 	}
8657f24467fSOctavian Purdila 	if (ACPI_COMPANION(&spi->dev))
8667f24467fSOctavian Purdila 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
86747afc77bSHeikki Krogerus 	device_remove_software_node(&spi->dev);
86827e7db56SSaravana Kannan 	device_del(&spi->dev);
86927e7db56SSaravana Kannan 	spi_cleanup(spi);
87027e7db56SSaravana Kannan 	put_device(&spi->dev);
8713b1884c2SGeert Uytterhoeven }
8723b1884c2SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_device);
8733b1884c2SGeert Uytterhoeven 
8748caab75fSGeert Uytterhoeven static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
8752b9603a0SFeng Tang 					      struct spi_board_info *bi)
8762b9603a0SFeng Tang {
8772b9603a0SFeng Tang 	struct spi_device *dev;
8782b9603a0SFeng Tang 
8798caab75fSGeert Uytterhoeven 	if (ctlr->bus_num != bi->bus_num)
8802b9603a0SFeng Tang 		return;
8812b9603a0SFeng Tang 
8828caab75fSGeert Uytterhoeven 	dev = spi_new_device(ctlr, bi);
8832b9603a0SFeng Tang 	if (!dev)
8848caab75fSGeert Uytterhoeven 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
8852b9603a0SFeng Tang 			bi->modalias);
8862b9603a0SFeng Tang }
8872b9603a0SFeng Tang 
88833e34dc6SDavid Brownell /**
88933e34dc6SDavid Brownell  * spi_register_board_info - register SPI devices for a given board
89033e34dc6SDavid Brownell  * @info: array of chip descriptors
89133e34dc6SDavid Brownell  * @n: how many descriptors are provided
89233e34dc6SDavid Brownell  * Context: can sleep
89333e34dc6SDavid Brownell  *
8948ae12a0dSDavid Brownell  * Board-specific early init code calls this (probably during arch_initcall)
8958ae12a0dSDavid Brownell  * with segments of the SPI device table.  Any device nodes are created later,
8968ae12a0dSDavid Brownell  * after the relevant parent SPI controller (bus_num) is defined.  We keep
8978ae12a0dSDavid Brownell  * this table of devices forever, so that reloading a controller driver will
8988ae12a0dSDavid Brownell  * not make Linux forget about these hard-wired devices.
8998ae12a0dSDavid Brownell  *
9008ae12a0dSDavid Brownell  * Other code can also call this, e.g. a particular add-on board might provide
9018ae12a0dSDavid Brownell  * SPI devices through its expansion connector, so code initializing that board
9028ae12a0dSDavid Brownell  * would naturally declare its SPI devices.
9038ae12a0dSDavid Brownell  *
9048ae12a0dSDavid Brownell  * The board info passed can safely be __initdata ... but be careful of
9058ae12a0dSDavid Brownell  * any embedded pointers (platform_data, etc), they're copied as-is.
90697d56dc6SJavier Martinez Canillas  *
90797d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
9088ae12a0dSDavid Brownell  */
909fd4a319bSGrant Likely int spi_register_board_info(struct spi_board_info const *info, unsigned n)
9108ae12a0dSDavid Brownell {
9118ae12a0dSDavid Brownell 	struct boardinfo *bi;
9122b9603a0SFeng Tang 	int i;
9138ae12a0dSDavid Brownell 
914c7908a37SXiubo Li 	if (!n)
915f974cf57SDmitry Torokhov 		return 0;
916c7908a37SXiubo Li 
917f9bdb7fdSMarkus Elfring 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
9188ae12a0dSDavid Brownell 	if (!bi)
9198ae12a0dSDavid Brownell 		return -ENOMEM;
9208ae12a0dSDavid Brownell 
9212b9603a0SFeng Tang 	for (i = 0; i < n; i++, bi++, info++) {
9228caab75fSGeert Uytterhoeven 		struct spi_controller *ctlr;
9232b9603a0SFeng Tang 
9242b9603a0SFeng Tang 		memcpy(&bi->board_info, info, sizeof(*info));
925826cf175SDmitry Torokhov 
92694040828SMatthias Kaehlcke 		mutex_lock(&board_lock);
9278ae12a0dSDavid Brownell 		list_add_tail(&bi->list, &board_list);
9288caab75fSGeert Uytterhoeven 		list_for_each_entry(ctlr, &spi_controller_list, list)
9298caab75fSGeert Uytterhoeven 			spi_match_controller_to_boardinfo(ctlr,
9308caab75fSGeert Uytterhoeven 							  &bi->board_info);
93194040828SMatthias Kaehlcke 		mutex_unlock(&board_lock);
9322b9603a0SFeng Tang 	}
9332b9603a0SFeng Tang 
9348ae12a0dSDavid Brownell 	return 0;
9358ae12a0dSDavid Brownell }
9368ae12a0dSDavid Brownell 
9378ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
9388ae12a0dSDavid Brownell 
939fb51601bSUwe Kleine-König /* Core methods for SPI resource management */
940fb51601bSUwe Kleine-König 
941fb51601bSUwe Kleine-König /**
942fb51601bSUwe Kleine-König  * spi_res_alloc - allocate a spi resource that is life-cycle managed
943fb51601bSUwe Kleine-König  *                 during the processing of a spi_message while using
944fb51601bSUwe Kleine-König  *                 spi_transfer_one
945702ca026SAndy Shevchenko  * @spi:     the SPI device for which we allocate memory
946fb51601bSUwe Kleine-König  * @release: the release code to execute for this resource
947fb51601bSUwe Kleine-König  * @size:    size to alloc and return
948fb51601bSUwe Kleine-König  * @gfp:     GFP allocation flags
949fb51601bSUwe Kleine-König  *
950fb51601bSUwe Kleine-König  * Return: the pointer to the allocated data
951fb51601bSUwe Kleine-König  *
952fb51601bSUwe Kleine-König  * This may get enhanced in the future to allocate from a memory pool
953fb51601bSUwe Kleine-König  * of the @spi_device or @spi_controller to avoid repeated allocations.
954fb51601bSUwe Kleine-König  */
955da21fde0SUwe Kleine-König static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
956fb51601bSUwe Kleine-König 			   size_t size, gfp_t gfp)
957fb51601bSUwe Kleine-König {
958fb51601bSUwe Kleine-König 	struct spi_res *sres;
959fb51601bSUwe Kleine-König 
960fb51601bSUwe Kleine-König 	sres = kzalloc(sizeof(*sres) + size, gfp);
961fb51601bSUwe Kleine-König 	if (!sres)
962fb51601bSUwe Kleine-König 		return NULL;
963fb51601bSUwe Kleine-König 
964fb51601bSUwe Kleine-König 	INIT_LIST_HEAD(&sres->entry);
965fb51601bSUwe Kleine-König 	sres->release = release;
966fb51601bSUwe Kleine-König 
967fb51601bSUwe Kleine-König 	return sres->data;
968fb51601bSUwe Kleine-König }
969fb51601bSUwe Kleine-König 
970fb51601bSUwe Kleine-König /**
971702ca026SAndy Shevchenko  * spi_res_free - free an SPI resource
972fb51601bSUwe Kleine-König  * @res: pointer to the custom data of a resource
973fb51601bSUwe Kleine-König  */
974da21fde0SUwe Kleine-König static void spi_res_free(void *res)
975fb51601bSUwe Kleine-König {
976fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
977fb51601bSUwe Kleine-König 
978fb51601bSUwe Kleine-König 	if (!res)
979fb51601bSUwe Kleine-König 		return;
980fb51601bSUwe Kleine-König 
981fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
982fb51601bSUwe Kleine-König 	kfree(sres);
983fb51601bSUwe Kleine-König }
984fb51601bSUwe Kleine-König 
985fb51601bSUwe Kleine-König /**
986fb51601bSUwe Kleine-König  * spi_res_add - add a spi_res to the spi_message
987702ca026SAndy Shevchenko  * @message: the SPI message
988fb51601bSUwe Kleine-König  * @res:     the spi_resource
989fb51601bSUwe Kleine-König  */
990da21fde0SUwe Kleine-König static void spi_res_add(struct spi_message *message, void *res)
991fb51601bSUwe Kleine-König {
992fb51601bSUwe Kleine-König 	struct spi_res *sres = container_of(res, struct spi_res, data);
993fb51601bSUwe Kleine-König 
994fb51601bSUwe Kleine-König 	WARN_ON(!list_empty(&sres->entry));
995fb51601bSUwe Kleine-König 	list_add_tail(&sres->entry, &message->resources);
996fb51601bSUwe Kleine-König }
997fb51601bSUwe Kleine-König 
998fb51601bSUwe Kleine-König /**
999702ca026SAndy Shevchenko  * spi_res_release - release all SPI resources for this message
1000fb51601bSUwe Kleine-König  * @ctlr:  the @spi_controller
1001fb51601bSUwe Kleine-König  * @message: the @spi_message
1002fb51601bSUwe Kleine-König  */
1003da21fde0SUwe Kleine-König static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
1004fb51601bSUwe Kleine-König {
1005fb51601bSUwe Kleine-König 	struct spi_res *res, *tmp;
1006fb51601bSUwe Kleine-König 
1007fb51601bSUwe Kleine-König 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
1008fb51601bSUwe Kleine-König 		if (res->release)
1009fb51601bSUwe Kleine-König 			res->release(ctlr, message, res->data);
1010fb51601bSUwe Kleine-König 
1011fb51601bSUwe Kleine-König 		list_del(&res->entry);
1012fb51601bSUwe Kleine-König 
1013fb51601bSUwe Kleine-König 		kfree(res);
1014fb51601bSUwe Kleine-König 	}
1015fb51601bSUwe Kleine-König }
1016fb51601bSUwe Kleine-König 
1017fb51601bSUwe Kleine-König /*-------------------------------------------------------------------------*/
10184d8ff6b0SAmit Kumar Mahapatra static inline bool spi_is_last_cs(struct spi_device *spi)
10194d8ff6b0SAmit Kumar Mahapatra {
10204d8ff6b0SAmit Kumar Mahapatra 	u8 idx;
10214d8ff6b0SAmit Kumar Mahapatra 	bool last = false;
10224d8ff6b0SAmit Kumar Mahapatra 
10234d8ff6b0SAmit Kumar Mahapatra 	for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
10244d8ff6b0SAmit Kumar Mahapatra 		if ((spi->cs_index_mask >> idx) & 0x01) {
10254d8ff6b0SAmit Kumar Mahapatra 			if (spi->controller->last_cs[idx] == spi_get_chipselect(spi, idx))
10264d8ff6b0SAmit Kumar Mahapatra 				last = true;
10274d8ff6b0SAmit Kumar Mahapatra 		}
10284d8ff6b0SAmit Kumar Mahapatra 	}
10294d8ff6b0SAmit Kumar Mahapatra 	return last;
10304d8ff6b0SAmit Kumar Mahapatra }
10314d8ff6b0SAmit Kumar Mahapatra 
1032fb51601bSUwe Kleine-König 
1033d347b4aaSDavid Bauer static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
1034b158935fSMark Brown {
103586527bcbSAndy Shevchenko 	bool activate = enable;
10364d8ff6b0SAmit Kumar Mahapatra 	u8 idx;
103725093bdeSAlexandru Ardelean 
1038d40f0b6fSDouglas Anderson 	/*
1039d40f0b6fSDouglas Anderson 	 * Avoid calling into the driver (or doing delays) if the chip select
1040d40f0b6fSDouglas Anderson 	 * isn't actually changing from the last time this was called.
1041d40f0b6fSDouglas Anderson 	 */
10424d8ff6b0SAmit Kumar Mahapatra 	if (!force && ((enable && spi->controller->last_cs_index_mask == spi->cs_index_mask &&
10434d8ff6b0SAmit Kumar Mahapatra 			spi_is_last_cs(spi)) ||
10444d8ff6b0SAmit Kumar Mahapatra 		       (!enable && spi->controller->last_cs_index_mask == spi->cs_index_mask &&
10454d8ff6b0SAmit Kumar Mahapatra 			!spi_is_last_cs(spi))) &&
1046d40f0b6fSDouglas Anderson 	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
1047d40f0b6fSDouglas Anderson 		return;
1048d40f0b6fSDouglas Anderson 
10495cb4e1f3SAndy Shevchenko 	trace_spi_set_cs(spi, activate);
10505cb4e1f3SAndy Shevchenko 
10514d8ff6b0SAmit Kumar Mahapatra 	spi->controller->last_cs_index_mask = spi->cs_index_mask;
10524d8ff6b0SAmit Kumar Mahapatra 	for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
10534d8ff6b0SAmit Kumar Mahapatra 		spi->controller->last_cs[idx] = enable ? spi_get_chipselect(spi, 0) : -1;
1054d40f0b6fSDouglas Anderson 	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
1055d40f0b6fSDouglas Anderson 
1056b158935fSMark Brown 	if (spi->mode & SPI_CS_HIGH)
1057b158935fSMark Brown 		enable = !enable;
1058b158935fSMark Brown 
10594d8ff6b0SAmit Kumar Mahapatra 	if (spi_is_csgpiod(spi)) {
10604d8ff6b0SAmit Kumar Mahapatra 		if (!spi->controller->set_cs_timing && !activate)
10614d8ff6b0SAmit Kumar Mahapatra 			spi_delay_exec(&spi->cs_hold, NULL);
10624d8ff6b0SAmit Kumar Mahapatra 
1063f48dc6b9SLinus Walleij 		if (!(spi->mode & SPI_NO_CS)) {
10646b695469SAndy Shevchenko 			/*
10656b695469SAndy Shevchenko 			 * Historically ACPI has no means of the GPIO polarity and
10666b695469SAndy Shevchenko 			 * thus the SPISerialBus() resource defines it on the per-chip
10676b695469SAndy Shevchenko 			 * basis. In order to avoid a chain of negations, the GPIO
10686b695469SAndy Shevchenko 			 * polarity is considered being Active High. Even for the cases
10696b695469SAndy Shevchenko 			 * when _DSD() is involved (in the updated versions of ACPI)
10706b695469SAndy Shevchenko 			 * the GPIO CS polarity must be defined Active High to avoid
10716b695469SAndy Shevchenko 			 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
10726b695469SAndy Shevchenko 			 * into account.
10736b695469SAndy Shevchenko 			 */
10744d8ff6b0SAmit Kumar Mahapatra 			for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
10754d8ff6b0SAmit Kumar Mahapatra 				if (((spi->cs_index_mask >> idx) & 0x01) &&
10764d8ff6b0SAmit Kumar Mahapatra 				    spi_get_csgpiod(spi, idx)) {
10776b695469SAndy Shevchenko 					if (has_acpi_companion(&spi->dev))
10784d8ff6b0SAmit Kumar Mahapatra 						gpiod_set_value_cansleep(spi_get_csgpiod(spi, idx),
10794d8ff6b0SAmit Kumar Mahapatra 									 !enable);
1080f3186dd8SLinus Walleij 					else
10816b695469SAndy Shevchenko 						/* Polarity handled by GPIO library */
10824d8ff6b0SAmit Kumar Mahapatra 						gpiod_set_value_cansleep(spi_get_csgpiod(spi, idx),
10834d8ff6b0SAmit Kumar Mahapatra 									 activate);
10844d8ff6b0SAmit Kumar Mahapatra 
10854d8ff6b0SAmit Kumar Mahapatra 					if (activate)
10864d8ff6b0SAmit Kumar Mahapatra 						spi_delay_exec(&spi->cs_setup, NULL);
10874d8ff6b0SAmit Kumar Mahapatra 					else
10884d8ff6b0SAmit Kumar Mahapatra 						spi_delay_exec(&spi->cs_inactive, NULL);
10894d8ff6b0SAmit Kumar Mahapatra 				}
10904d8ff6b0SAmit Kumar Mahapatra 			}
10916b695469SAndy Shevchenko 		}
10928eee6b9dSThor Thayer 		/* Some SPI masters need both GPIO CS & slave_select */
109382238d2cSAndy Shevchenko 		if ((spi->controller->flags & SPI_CONTROLLER_GPIO_SS) &&
10948caab75fSGeert Uytterhoeven 		    spi->controller->set_cs)
10958caab75fSGeert Uytterhoeven 			spi->controller->set_cs(spi, !enable);
109625093bdeSAlexandru Ardelean 
10974d8ff6b0SAmit Kumar Mahapatra 		if (!spi->controller->set_cs_timing) {
109895c07247SHector Martin 			if (activate)
109995c07247SHector Martin 				spi_delay_exec(&spi->cs_setup, NULL);
110095c07247SHector Martin 			else
11018c33ebfeSMason Zhang 				spi_delay_exec(&spi->cs_inactive, NULL);
110225093bdeSAlexandru Ardelean 		}
11034d8ff6b0SAmit Kumar Mahapatra 	} else if (spi->controller->set_cs) {
11044d8ff6b0SAmit Kumar Mahapatra 		spi->controller->set_cs(spi, !enable);
11054d8ff6b0SAmit Kumar Mahapatra 	}
1106b158935fSMark Brown }
1107b158935fSMark Brown 
11082de440f5SGeert Uytterhoeven #ifdef CONFIG_HAS_DMA
11090c17ba73SVincent Whitchurch static int spi_map_buf_attrs(struct spi_controller *ctlr, struct device *dev,
11106ad45a27SMark Brown 			     struct sg_table *sgt, void *buf, size_t len,
11110c17ba73SVincent Whitchurch 			     enum dma_data_direction dir, unsigned long attrs)
11126ad45a27SMark Brown {
11136ad45a27SMark Brown 	const bool vmalloced_buf = is_vmalloc_addr(buf);
1114df88e91bSAndy Shevchenko 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
1115b1b8153cSVignesh R #ifdef CONFIG_HIGHMEM
1116b1b8153cSVignesh R 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
1117b1b8153cSVignesh R 				(unsigned long)buf < (PKMAP_BASE +
1118b1b8153cSVignesh R 					(LAST_PKMAP * PAGE_SIZE)));
1119b1b8153cSVignesh R #else
1120b1b8153cSVignesh R 	const bool kmap_buf = false;
1121b1b8153cSVignesh R #endif
112265598c13SAndrew Gabbasov 	int desc_len;
112365598c13SAndrew Gabbasov 	int sgs;
11246ad45a27SMark Brown 	struct page *vm_page;
11258dd4a016SJuan Gutierrez 	struct scatterlist *sg;
11266ad45a27SMark Brown 	void *sg_buf;
11276ad45a27SMark Brown 	size_t min;
11286ad45a27SMark Brown 	int i, ret;
11296ad45a27SMark Brown 
1130b1b8153cSVignesh R 	if (vmalloced_buf || kmap_buf) {
1131ebc4cb43SBiju Das 		desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
113265598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
11330569a88fSVignesh R 	} else if (virt_addr_valid(buf)) {
1134ebc4cb43SBiju Das 		desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
113565598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len, desc_len);
11360569a88fSVignesh R 	} else {
11370569a88fSVignesh R 		return -EINVAL;
113865598c13SAndrew Gabbasov 	}
113965598c13SAndrew Gabbasov 
11406ad45a27SMark Brown 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
11416ad45a27SMark Brown 	if (ret != 0)
11426ad45a27SMark Brown 		return ret;
11436ad45a27SMark Brown 
11448dd4a016SJuan Gutierrez 	sg = &sgt->sgl[0];
11456ad45a27SMark Brown 	for (i = 0; i < sgs; i++) {
11466ad45a27SMark Brown 
1147b1b8153cSVignesh R 		if (vmalloced_buf || kmap_buf) {
1148ce99319aSMaxime Chevallier 			/*
1149ce99319aSMaxime Chevallier 			 * Next scatterlist entry size is the minimum between
1150ce99319aSMaxime Chevallier 			 * the desc_len and the remaining buffer length that
1151ce99319aSMaxime Chevallier 			 * fits in a page.
1152ce99319aSMaxime Chevallier 			 */
1153ce99319aSMaxime Chevallier 			min = min_t(size_t, desc_len,
1154ce99319aSMaxime Chevallier 				    min_t(size_t, len,
1155ce99319aSMaxime Chevallier 					  PAGE_SIZE - offset_in_page(buf)));
1156b1b8153cSVignesh R 			if (vmalloced_buf)
11576ad45a27SMark Brown 				vm_page = vmalloc_to_page(buf);
1158b1b8153cSVignesh R 			else
1159b1b8153cSVignesh R 				vm_page = kmap_to_page(buf);
11606ad45a27SMark Brown 			if (!vm_page) {
11616ad45a27SMark Brown 				sg_free_table(sgt);
11626ad45a27SMark Brown 				return -ENOMEM;
11636ad45a27SMark Brown 			}
11648dd4a016SJuan Gutierrez 			sg_set_page(sg, vm_page,
1165c1aefbddSCharles Keepax 				    min, offset_in_page(buf));
11666ad45a27SMark Brown 		} else {
116765598c13SAndrew Gabbasov 			min = min_t(size_t, len, desc_len);
11686ad45a27SMark Brown 			sg_buf = buf;
11698dd4a016SJuan Gutierrez 			sg_set_buf(sg, sg_buf, min);
11706ad45a27SMark Brown 		}
11716ad45a27SMark Brown 
11726ad45a27SMark Brown 		buf += min;
11736ad45a27SMark Brown 		len -= min;
11748dd4a016SJuan Gutierrez 		sg = sg_next(sg);
11756ad45a27SMark Brown 	}
11766ad45a27SMark Brown 
11770c17ba73SVincent Whitchurch 	ret = dma_map_sgtable(dev, sgt, dir, attrs);
11786ad45a27SMark Brown 	if (ret < 0) {
11796ad45a27SMark Brown 		sg_free_table(sgt);
11806ad45a27SMark Brown 		return ret;
11816ad45a27SMark Brown 	}
11826ad45a27SMark Brown 
11836ad45a27SMark Brown 	return 0;
11846ad45a27SMark Brown }
11856ad45a27SMark Brown 
11860c17ba73SVincent Whitchurch int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
11870c17ba73SVincent Whitchurch 		struct sg_table *sgt, void *buf, size_t len,
11880c17ba73SVincent Whitchurch 		enum dma_data_direction dir)
11890c17ba73SVincent Whitchurch {
11900c17ba73SVincent Whitchurch 	return spi_map_buf_attrs(ctlr, dev, sgt, buf, len, dir, 0);
11910c17ba73SVincent Whitchurch }
11920c17ba73SVincent Whitchurch 
11930c17ba73SVincent Whitchurch static void spi_unmap_buf_attrs(struct spi_controller *ctlr,
11940c17ba73SVincent Whitchurch 				struct device *dev, struct sg_table *sgt,
11950c17ba73SVincent Whitchurch 				enum dma_data_direction dir,
11960c17ba73SVincent Whitchurch 				unsigned long attrs)
11970c17ba73SVincent Whitchurch {
11980c17ba73SVincent Whitchurch 	if (sgt->orig_nents) {
11990c17ba73SVincent Whitchurch 		dma_unmap_sgtable(dev, sgt, dir, attrs);
12000c17ba73SVincent Whitchurch 		sg_free_table(sgt);
12018e9204cdSMarek Szyprowski 		sgt->orig_nents = 0;
12028e9204cdSMarek Szyprowski 		sgt->nents = 0;
12030c17ba73SVincent Whitchurch 	}
12040c17ba73SVincent Whitchurch }
12050c17ba73SVincent Whitchurch 
120646336966SBoris Brezillon void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
12076ad45a27SMark Brown 		   struct sg_table *sgt, enum dma_data_direction dir)
12086ad45a27SMark Brown {
12090c17ba73SVincent Whitchurch 	spi_unmap_buf_attrs(ctlr, dev, sgt, dir, 0);
12106ad45a27SMark Brown }
12116ad45a27SMark Brown 
12128caab75fSGeert Uytterhoeven static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
121399adef31SMark Brown {
121499adef31SMark Brown 	struct device *tx_dev, *rx_dev;
121599adef31SMark Brown 	struct spi_transfer *xfer;
12166ad45a27SMark Brown 	int ret;
12173a2eba9bSMark Brown 
12188caab75fSGeert Uytterhoeven 	if (!ctlr->can_dma)
121999adef31SMark Brown 		return 0;
122099adef31SMark Brown 
12218caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
12228caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
1223b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1224b470e10eSVinod Koul 		tx_dev = ctlr->dma_map_dev;
1225c37f45b5SLeilk Liu 	else
12268caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
1227c37f45b5SLeilk Liu 
12288caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
12298caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
1230b470e10eSVinod Koul 	else if (ctlr->dma_map_dev)
1231b470e10eSVinod Koul 		rx_dev = ctlr->dma_map_dev;
1232c37f45b5SLeilk Liu 	else
12338caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
123499adef31SMark Brown 
123599adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
12360c17ba73SVincent Whitchurch 		/* The sync is done before each transfer. */
12370c17ba73SVincent Whitchurch 		unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
12380c17ba73SVincent Whitchurch 
12398caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
124099adef31SMark Brown 			continue;
124199adef31SMark Brown 
124299adef31SMark Brown 		if (xfer->tx_buf != NULL) {
12430c17ba73SVincent Whitchurch 			ret = spi_map_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
12440c17ba73SVincent Whitchurch 						(void *)xfer->tx_buf,
12450c17ba73SVincent Whitchurch 						xfer->len, DMA_TO_DEVICE,
12460c17ba73SVincent Whitchurch 						attrs);
12476ad45a27SMark Brown 			if (ret != 0)
12486ad45a27SMark Brown 				return ret;
124999adef31SMark Brown 		}
125099adef31SMark Brown 
125199adef31SMark Brown 		if (xfer->rx_buf != NULL) {
12520c17ba73SVincent Whitchurch 			ret = spi_map_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
125399adef31SMark Brown 						xfer->rx_buf, xfer->len,
12540c17ba73SVincent Whitchurch 						DMA_FROM_DEVICE, attrs);
12556ad45a27SMark Brown 			if (ret != 0) {
12560c17ba73SVincent Whitchurch 				spi_unmap_buf_attrs(ctlr, tx_dev,
12570c17ba73SVincent Whitchurch 						&xfer->tx_sg, DMA_TO_DEVICE,
12580c17ba73SVincent Whitchurch 						attrs);
12590c17ba73SVincent Whitchurch 
12606ad45a27SMark Brown 				return ret;
126199adef31SMark Brown 			}
126299adef31SMark Brown 		}
126399adef31SMark Brown 	}
126499adef31SMark Brown 
1265f25723dcSVincent Whitchurch 	ctlr->cur_rx_dma_dev = rx_dev;
1266f25723dcSVincent Whitchurch 	ctlr->cur_tx_dma_dev = tx_dev;
12678caab75fSGeert Uytterhoeven 	ctlr->cur_msg_mapped = true;
126899adef31SMark Brown 
126999adef31SMark Brown 	return 0;
127099adef31SMark Brown }
127199adef31SMark Brown 
12728caab75fSGeert Uytterhoeven static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
127399adef31SMark Brown {
1274f25723dcSVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
1275f25723dcSVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
127699adef31SMark Brown 	struct spi_transfer *xfer;
127799adef31SMark Brown 
12788caab75fSGeert Uytterhoeven 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
127999adef31SMark Brown 		return 0;
128099adef31SMark Brown 
128199adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
12820c17ba73SVincent Whitchurch 		/* The sync has already been done after each transfer. */
12830c17ba73SVincent Whitchurch 		unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
12840c17ba73SVincent Whitchurch 
12858caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
128699adef31SMark Brown 			continue;
128799adef31SMark Brown 
12880c17ba73SVincent Whitchurch 		spi_unmap_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
12890c17ba73SVincent Whitchurch 				    DMA_FROM_DEVICE, attrs);
12900c17ba73SVincent Whitchurch 		spi_unmap_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
12910c17ba73SVincent Whitchurch 				    DMA_TO_DEVICE, attrs);
129299adef31SMark Brown 	}
129399adef31SMark Brown 
1294809b1b04SRobin Gong 	ctlr->cur_msg_mapped = false;
1295809b1b04SRobin Gong 
129699adef31SMark Brown 	return 0;
129799adef31SMark Brown }
12980c17ba73SVincent Whitchurch 
12990c17ba73SVincent Whitchurch static void spi_dma_sync_for_device(struct spi_controller *ctlr,
13000c17ba73SVincent Whitchurch 				    struct spi_transfer *xfer)
13010c17ba73SVincent Whitchurch {
13020c17ba73SVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
13030c17ba73SVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
13040c17ba73SVincent Whitchurch 
13050c17ba73SVincent Whitchurch 	if (!ctlr->cur_msg_mapped)
13060c17ba73SVincent Whitchurch 		return;
13070c17ba73SVincent Whitchurch 
13080c17ba73SVincent Whitchurch 	if (xfer->tx_sg.orig_nents)
13090c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_device(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
13100c17ba73SVincent Whitchurch 	if (xfer->rx_sg.orig_nents)
13110c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
13120c17ba73SVincent Whitchurch }
13130c17ba73SVincent Whitchurch 
13140c17ba73SVincent Whitchurch static void spi_dma_sync_for_cpu(struct spi_controller *ctlr,
13150c17ba73SVincent Whitchurch 				 struct spi_transfer *xfer)
13160c17ba73SVincent Whitchurch {
13170c17ba73SVincent Whitchurch 	struct device *rx_dev = ctlr->cur_rx_dma_dev;
13180c17ba73SVincent Whitchurch 	struct device *tx_dev = ctlr->cur_tx_dma_dev;
13190c17ba73SVincent Whitchurch 
13200c17ba73SVincent Whitchurch 	if (!ctlr->cur_msg_mapped)
13210c17ba73SVincent Whitchurch 		return;
13220c17ba73SVincent Whitchurch 
13230c17ba73SVincent Whitchurch 	if (xfer->rx_sg.orig_nents)
13240c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
13250c17ba73SVincent Whitchurch 	if (xfer->tx_sg.orig_nents)
13260c17ba73SVincent Whitchurch 		dma_sync_sgtable_for_cpu(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
13270c17ba73SVincent Whitchurch }
13282de440f5SGeert Uytterhoeven #else /* !CONFIG_HAS_DMA */
13298caab75fSGeert Uytterhoeven static inline int __spi_map_msg(struct spi_controller *ctlr,
13302de440f5SGeert Uytterhoeven 				struct spi_message *msg)
13312de440f5SGeert Uytterhoeven {
13322de440f5SGeert Uytterhoeven 	return 0;
13332de440f5SGeert Uytterhoeven }
13342de440f5SGeert Uytterhoeven 
13358caab75fSGeert Uytterhoeven static inline int __spi_unmap_msg(struct spi_controller *ctlr,
13362de440f5SGeert Uytterhoeven 				  struct spi_message *msg)
13372de440f5SGeert Uytterhoeven {
13382de440f5SGeert Uytterhoeven 	return 0;
13392de440f5SGeert Uytterhoeven }
13400c17ba73SVincent Whitchurch 
13410c17ba73SVincent Whitchurch static void spi_dma_sync_for_device(struct spi_controller *ctrl,
13420c17ba73SVincent Whitchurch 				    struct spi_transfer *xfer)
13430c17ba73SVincent Whitchurch {
13440c17ba73SVincent Whitchurch }
13450c17ba73SVincent Whitchurch 
13460c17ba73SVincent Whitchurch static void spi_dma_sync_for_cpu(struct spi_controller *ctrl,
13470c17ba73SVincent Whitchurch 				 struct spi_transfer *xfer)
13480c17ba73SVincent Whitchurch {
13490c17ba73SVincent Whitchurch }
13502de440f5SGeert Uytterhoeven #endif /* !CONFIG_HAS_DMA */
13512de440f5SGeert Uytterhoeven 
13528caab75fSGeert Uytterhoeven static inline int spi_unmap_msg(struct spi_controller *ctlr,
13534b786458SMartin Sperl 				struct spi_message *msg)
13544b786458SMartin Sperl {
13554b786458SMartin Sperl 	struct spi_transfer *xfer;
13564b786458SMartin Sperl 
13574b786458SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
13584b786458SMartin Sperl 		/*
13594b786458SMartin Sperl 		 * Restore the original value of tx_buf or rx_buf if they are
13604b786458SMartin Sperl 		 * NULL.
13614b786458SMartin Sperl 		 */
13628caab75fSGeert Uytterhoeven 		if (xfer->tx_buf == ctlr->dummy_tx)
13634b786458SMartin Sperl 			xfer->tx_buf = NULL;
13648caab75fSGeert Uytterhoeven 		if (xfer->rx_buf == ctlr->dummy_rx)
13654b786458SMartin Sperl 			xfer->rx_buf = NULL;
13664b786458SMartin Sperl 	}
13674b786458SMartin Sperl 
13688caab75fSGeert Uytterhoeven 	return __spi_unmap_msg(ctlr, msg);
13694b786458SMartin Sperl }
13704b786458SMartin Sperl 
13718caab75fSGeert Uytterhoeven static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
13722de440f5SGeert Uytterhoeven {
13732de440f5SGeert Uytterhoeven 	struct spi_transfer *xfer;
13742de440f5SGeert Uytterhoeven 	void *tmp;
13752de440f5SGeert Uytterhoeven 	unsigned int max_tx, max_rx;
13762de440f5SGeert Uytterhoeven 
1377aee67fe8Sdillon min 	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1378aee67fe8Sdillon min 		&& !(msg->spi->mode & SPI_3WIRE)) {
13792de440f5SGeert Uytterhoeven 		max_tx = 0;
13802de440f5SGeert Uytterhoeven 		max_rx = 0;
13812de440f5SGeert Uytterhoeven 
13822de440f5SGeert Uytterhoeven 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
13838caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
13842de440f5SGeert Uytterhoeven 			    !xfer->tx_buf)
13852de440f5SGeert Uytterhoeven 				max_tx = max(xfer->len, max_tx);
13868caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
13872de440f5SGeert Uytterhoeven 			    !xfer->rx_buf)
13882de440f5SGeert Uytterhoeven 				max_rx = max(xfer->len, max_rx);
13892de440f5SGeert Uytterhoeven 		}
13902de440f5SGeert Uytterhoeven 
13912de440f5SGeert Uytterhoeven 		if (max_tx) {
13928caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_tx, max_tx,
1393b00bab9dSAndy Shevchenko 				       GFP_KERNEL | GFP_DMA | __GFP_ZERO);
13942de440f5SGeert Uytterhoeven 			if (!tmp)
13952de440f5SGeert Uytterhoeven 				return -ENOMEM;
13968caab75fSGeert Uytterhoeven 			ctlr->dummy_tx = tmp;
13972de440f5SGeert Uytterhoeven 		}
13982de440f5SGeert Uytterhoeven 
13992de440f5SGeert Uytterhoeven 		if (max_rx) {
14008caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_rx, max_rx,
14012de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
14022de440f5SGeert Uytterhoeven 			if (!tmp)
14032de440f5SGeert Uytterhoeven 				return -ENOMEM;
14048caab75fSGeert Uytterhoeven 			ctlr->dummy_rx = tmp;
14052de440f5SGeert Uytterhoeven 		}
14062de440f5SGeert Uytterhoeven 
14072de440f5SGeert Uytterhoeven 		if (max_tx || max_rx) {
14082de440f5SGeert Uytterhoeven 			list_for_each_entry(xfer, &msg->transfers,
14092de440f5SGeert Uytterhoeven 					    transfer_list) {
14105442dcaaSChris Lesiak 				if (!xfer->len)
14115442dcaaSChris Lesiak 					continue;
14122de440f5SGeert Uytterhoeven 				if (!xfer->tx_buf)
14138caab75fSGeert Uytterhoeven 					xfer->tx_buf = ctlr->dummy_tx;
14142de440f5SGeert Uytterhoeven 				if (!xfer->rx_buf)
14158caab75fSGeert Uytterhoeven 					xfer->rx_buf = ctlr->dummy_rx;
14162de440f5SGeert Uytterhoeven 			}
14172de440f5SGeert Uytterhoeven 		}
14182de440f5SGeert Uytterhoeven 	}
14192de440f5SGeert Uytterhoeven 
14208caab75fSGeert Uytterhoeven 	return __spi_map_msg(ctlr, msg);
14212de440f5SGeert Uytterhoeven }
142299adef31SMark Brown 
1423810923f3SLubomir Rintel static int spi_transfer_wait(struct spi_controller *ctlr,
1424810923f3SLubomir Rintel 			     struct spi_message *msg,
1425810923f3SLubomir Rintel 			     struct spi_transfer *xfer)
1426810923f3SLubomir Rintel {
1427d501cc4cSDavid Jander 	struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1428d501cc4cSDavid Jander 	struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
14296170d077SXu Yilun 	u32 speed_hz = xfer->speed_hz;
143049686df5SColin Ian King 	unsigned long long ms;
1431810923f3SLubomir Rintel 
1432810923f3SLubomir Rintel 	if (spi_controller_is_slave(ctlr)) {
1433810923f3SLubomir Rintel 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1434810923f3SLubomir Rintel 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1435810923f3SLubomir Rintel 			return -EINTR;
1436810923f3SLubomir Rintel 		}
1437810923f3SLubomir Rintel 	} else {
14386170d077SXu Yilun 		if (!speed_hz)
14396170d077SXu Yilun 			speed_hz = 100000;
14406170d077SXu Yilun 
144186b8bff7SAndy Shevchenko 		/*
144286b8bff7SAndy Shevchenko 		 * For each byte we wait for 8 cycles of the SPI clock.
144386b8bff7SAndy Shevchenko 		 * Since speed is defined in Hz and we want milliseconds,
144486b8bff7SAndy Shevchenko 		 * use respective multiplier, but before the division,
144586b8bff7SAndy Shevchenko 		 * otherwise we may get 0 for short transfers.
144686b8bff7SAndy Shevchenko 		 */
144786b8bff7SAndy Shevchenko 		ms = 8LL * MSEC_PER_SEC * xfer->len;
14486170d077SXu Yilun 		do_div(ms, speed_hz);
1449810923f3SLubomir Rintel 
145086b8bff7SAndy Shevchenko 		/*
145186b8bff7SAndy Shevchenko 		 * Increase it twice and add 200 ms tolerance, use
145286b8bff7SAndy Shevchenko 		 * predefined maximum in case of overflow.
145386b8bff7SAndy Shevchenko 		 */
145486b8bff7SAndy Shevchenko 		ms += ms + 200;
1455810923f3SLubomir Rintel 		if (ms > UINT_MAX)
1456810923f3SLubomir Rintel 			ms = UINT_MAX;
1457810923f3SLubomir Rintel 
1458810923f3SLubomir Rintel 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1459810923f3SLubomir Rintel 						 msecs_to_jiffies(ms));
1460810923f3SLubomir Rintel 
1461810923f3SLubomir Rintel 		if (ms == 0) {
1462810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1463810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1464810923f3SLubomir Rintel 			dev_err(&msg->spi->dev,
1465810923f3SLubomir Rintel 				"SPI transfer timed out\n");
1466810923f3SLubomir Rintel 			return -ETIMEDOUT;
1467810923f3SLubomir Rintel 		}
146839cefd85SNam Cao 
146939cefd85SNam Cao 		if (xfer->error & SPI_TRANS_FAIL_IO)
147039cefd85SNam Cao 			return -EIO;
1471810923f3SLubomir Rintel 	}
1472810923f3SLubomir Rintel 
1473810923f3SLubomir Rintel 	return 0;
1474810923f3SLubomir Rintel }
1475810923f3SLubomir Rintel 
14760ff2de8bSMartin Sperl static void _spi_transfer_delay_ns(u32 ns)
14770ff2de8bSMartin Sperl {
14780ff2de8bSMartin Sperl 	if (!ns)
14790ff2de8bSMartin Sperl 		return;
148086b8bff7SAndy Shevchenko 	if (ns <= NSEC_PER_USEC) {
14810ff2de8bSMartin Sperl 		ndelay(ns);
14820ff2de8bSMartin Sperl 	} else {
148386b8bff7SAndy Shevchenko 		u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
14840ff2de8bSMartin Sperl 
14850ff2de8bSMartin Sperl 		if (us <= 10)
14860ff2de8bSMartin Sperl 			udelay(us);
14870ff2de8bSMartin Sperl 		else
14880ff2de8bSMartin Sperl 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
14890ff2de8bSMartin Sperl 	}
14900ff2de8bSMartin Sperl }
14910ff2de8bSMartin Sperl 
14923984d39bSAlexandru Ardelean int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
14930ff2de8bSMartin Sperl {
1494b2c98153SAlexandru Ardelean 	u32 delay = _delay->value;
1495b2c98153SAlexandru Ardelean 	u32 unit = _delay->unit;
1496d5864e5bSMartin Sperl 	u32 hz;
14970ff2de8bSMartin Sperl 
1498b2c98153SAlexandru Ardelean 	if (!delay)
1499b2c98153SAlexandru Ardelean 		return 0;
15000ff2de8bSMartin Sperl 
15010ff2de8bSMartin Sperl 	switch (unit) {
15020ff2de8bSMartin Sperl 	case SPI_DELAY_UNIT_USECS:
150386b8bff7SAndy Shevchenko 		delay *= NSEC_PER_USEC;
15040ff2de8bSMartin Sperl 		break;
150586b8bff7SAndy Shevchenko 	case SPI_DELAY_UNIT_NSECS:
150686b8bff7SAndy Shevchenko 		/* Nothing to do here */
15070ff2de8bSMartin Sperl 		break;
1508d5864e5bSMartin Sperl 	case SPI_DELAY_UNIT_SCK:
150995c8222fSDavid Jander 		/* Clock cycles need to be obtained from spi_transfer */
1510b2c98153SAlexandru Ardelean 		if (!xfer)
1511b2c98153SAlexandru Ardelean 			return -EINVAL;
151286b8bff7SAndy Shevchenko 		/*
151386b8bff7SAndy Shevchenko 		 * If there is unknown effective speed, approximate it
1514702ca026SAndy Shevchenko 		 * by underestimating with half of the requested Hz.
1515d5864e5bSMartin Sperl 		 */
1516d5864e5bSMartin Sperl 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1517b2c98153SAlexandru Ardelean 		if (!hz)
1518b2c98153SAlexandru Ardelean 			return -EINVAL;
151986b8bff7SAndy Shevchenko 
152086b8bff7SAndy Shevchenko 		/* Convert delay to nanoseconds */
152186b8bff7SAndy Shevchenko 		delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
1522d5864e5bSMartin Sperl 		break;
15230ff2de8bSMartin Sperl 	default:
1524b2c98153SAlexandru Ardelean 		return -EINVAL;
1525b2c98153SAlexandru Ardelean 	}
1526b2c98153SAlexandru Ardelean 
1527b2c98153SAlexandru Ardelean 	return delay;
1528b2c98153SAlexandru Ardelean }
15293984d39bSAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1530b2c98153SAlexandru Ardelean 
1531b2c98153SAlexandru Ardelean int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1532b2c98153SAlexandru Ardelean {
1533b2c98153SAlexandru Ardelean 	int delay;
1534b2c98153SAlexandru Ardelean 
15358fede89fSMark Brown 	might_sleep();
15368fede89fSMark Brown 
1537b2c98153SAlexandru Ardelean 	if (!_delay)
1538b2c98153SAlexandru Ardelean 		return -EINVAL;
1539b2c98153SAlexandru Ardelean 
15403984d39bSAlexandru Ardelean 	delay = spi_delay_to_ns(_delay, xfer);
1541b2c98153SAlexandru Ardelean 	if (delay < 0)
1542b2c98153SAlexandru Ardelean 		return delay;
1543b2c98153SAlexandru Ardelean 
1544b2c98153SAlexandru Ardelean 	_spi_transfer_delay_ns(delay);
1545b2c98153SAlexandru Ardelean 
1546b2c98153SAlexandru Ardelean 	return 0;
1547b2c98153SAlexandru Ardelean }
1548b2c98153SAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_exec);
1549b2c98153SAlexandru Ardelean 
15500ff2de8bSMartin Sperl static void _spi_transfer_cs_change_delay(struct spi_message *msg,
15510ff2de8bSMartin Sperl 					  struct spi_transfer *xfer)
15520ff2de8bSMartin Sperl {
155386b8bff7SAndy Shevchenko 	u32 default_delay_ns = 10 * NSEC_PER_USEC;
1554329f0dacSAlexandru Ardelean 	u32 delay = xfer->cs_change_delay.value;
1555329f0dacSAlexandru Ardelean 	u32 unit = xfer->cs_change_delay.unit;
1556329f0dacSAlexandru Ardelean 	int ret;
15570ff2de8bSMartin Sperl 
155895c8222fSDavid Jander 	/* Return early on "fast" mode - for everything but USECS */
15596b3f236aSAlexandru Ardelean 	if (!delay) {
15606b3f236aSAlexandru Ardelean 		if (unit == SPI_DELAY_UNIT_USECS)
156186b8bff7SAndy Shevchenko 			_spi_transfer_delay_ns(default_delay_ns);
15620ff2de8bSMartin Sperl 		return;
15636b3f236aSAlexandru Ardelean 	}
15640ff2de8bSMartin Sperl 
1565329f0dacSAlexandru Ardelean 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1566329f0dacSAlexandru Ardelean 	if (ret) {
15670ff2de8bSMartin Sperl 		dev_err_once(&msg->spi->dev,
156886b8bff7SAndy Shevchenko 			     "Use of unsupported delay unit %i, using default of %luus\n",
156986b8bff7SAndy Shevchenko 			     unit, default_delay_ns / NSEC_PER_USEC);
157086b8bff7SAndy Shevchenko 		_spi_transfer_delay_ns(default_delay_ns);
15710ff2de8bSMartin Sperl 	}
15720ff2de8bSMartin Sperl }
15730ff2de8bSMartin Sperl 
15746e80133aSWilliam Zhang void spi_transfer_cs_change_delay_exec(struct spi_message *msg,
15756e80133aSWilliam Zhang 						  struct spi_transfer *xfer)
15766e80133aSWilliam Zhang {
15776e80133aSWilliam Zhang 	_spi_transfer_cs_change_delay(msg, xfer);
15786e80133aSWilliam Zhang }
15796e80133aSWilliam Zhang EXPORT_SYMBOL_GPL(spi_transfer_cs_change_delay_exec);
15806e80133aSWilliam Zhang 
1581b158935fSMark Brown /*
1582b158935fSMark Brown  * spi_transfer_one_message - Default implementation of transfer_one_message()
1583b158935fSMark Brown  *
1584b158935fSMark Brown  * This is a standard implementation of transfer_one_message() for
15858ba811a7SMoritz Fischer  * drivers which implement a transfer_one() operation.  It provides
1586b158935fSMark Brown  * standard handling of delays and chip select management.
1587b158935fSMark Brown  */
15888caab75fSGeert Uytterhoeven static int spi_transfer_one_message(struct spi_controller *ctlr,
1589b158935fSMark Brown 				    struct spi_message *msg)
1590b158935fSMark Brown {
1591b158935fSMark Brown 	struct spi_transfer *xfer;
1592b158935fSMark Brown 	bool keep_cs = false;
1593b158935fSMark Brown 	int ret = 0;
1594d501cc4cSDavid Jander 	struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
1595d501cc4cSDavid Jander 	struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
1596b158935fSMark Brown 
15975e0531f6SChristophe Leroy 	xfer = list_first_entry(&msg->transfers, struct spi_transfer, transfer_list);
15985e0531f6SChristophe Leroy 	spi_set_cs(msg->spi, !xfer->cs_off, false);
1599b158935fSMark Brown 
1600eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1601eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1602eca2ebc7SMartin Sperl 
1603b158935fSMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1604b158935fSMark Brown 		trace_spi_transfer_start(msg, xfer);
1605b158935fSMark Brown 
16068caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
16078caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1608eca2ebc7SMartin Sperl 
1609b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1610b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1611b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1612b42faeeeSVladimir Oltean 		}
1613b42faeeeSVladimir Oltean 
1614b3063203SNicolas Saenz Julienne 		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
16158caab75fSGeert Uytterhoeven 			reinit_completion(&ctlr->xfer_completion);
1616b158935fSMark Brown 
1617809b1b04SRobin Gong fallback_pio:
16180c17ba73SVincent Whitchurch 			spi_dma_sync_for_device(ctlr, xfer);
16198caab75fSGeert Uytterhoeven 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1620b158935fSMark Brown 			if (ret < 0) {
16210c17ba73SVincent Whitchurch 				spi_dma_sync_for_cpu(ctlr, xfer);
16220c17ba73SVincent Whitchurch 
1623809b1b04SRobin Gong 				if (ctlr->cur_msg_mapped &&
1624809b1b04SRobin Gong 				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1625809b1b04SRobin Gong 					__spi_unmap_msg(ctlr, msg);
1626809b1b04SRobin Gong 					ctlr->fallback = true;
1627809b1b04SRobin Gong 					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1628809b1b04SRobin Gong 					goto fallback_pio;
1629809b1b04SRobin Gong 				}
1630809b1b04SRobin Gong 
1631eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1632eca2ebc7SMartin Sperl 							       errors);
1633eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1634eca2ebc7SMartin Sperl 							       errors);
1635b158935fSMark Brown 				dev_err(&msg->spi->dev,
1636b158935fSMark Brown 					"SPI transfer failed: %d\n", ret);
1637b158935fSMark Brown 				goto out;
1638b158935fSMark Brown 			}
1639b158935fSMark Brown 
1640d57e7960SMark Brown 			if (ret > 0) {
1641810923f3SLubomir Rintel 				ret = spi_transfer_wait(ctlr, msg, xfer);
1642810923f3SLubomir Rintel 				if (ret < 0)
1643810923f3SLubomir Rintel 					msg->status = ret;
1644d57e7960SMark Brown 			}
16450c17ba73SVincent Whitchurch 
16460c17ba73SVincent Whitchurch 			spi_dma_sync_for_cpu(ctlr, xfer);
164738ec10f6SMark Brown 		} else {
164838ec10f6SMark Brown 			if (xfer->len)
164938ec10f6SMark Brown 				dev_err(&msg->spi->dev,
165038ec10f6SMark Brown 					"Bufferless transfer has length %u\n",
165138ec10f6SMark Brown 					xfer->len);
165238ec10f6SMark Brown 		}
1653b158935fSMark Brown 
1654b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1655b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1656b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1657b42faeeeSVladimir Oltean 		}
1658b42faeeeSVladimir Oltean 
1659b158935fSMark Brown 		trace_spi_transfer_stop(msg, xfer);
1660b158935fSMark Brown 
1661b158935fSMark Brown 		if (msg->status != -EINPROGRESS)
1662b158935fSMark Brown 			goto out;
1663b158935fSMark Brown 
1664bebcfd27SAlexandru Ardelean 		spi_transfer_delay_exec(xfer);
1665b158935fSMark Brown 
1666b158935fSMark Brown 		if (xfer->cs_change) {
1667b158935fSMark Brown 			if (list_is_last(&xfer->transfer_list,
1668b158935fSMark Brown 					 &msg->transfers)) {
1669b158935fSMark Brown 				keep_cs = true;
1670b158935fSMark Brown 			} else {
16715e0531f6SChristophe Leroy 				if (!xfer->cs_off)
1672d347b4aaSDavid Bauer 					spi_set_cs(msg->spi, false, false);
16730ff2de8bSMartin Sperl 				_spi_transfer_cs_change_delay(msg, xfer);
16745e0531f6SChristophe Leroy 				if (!list_next_entry(xfer, transfer_list)->cs_off)
1675d347b4aaSDavid Bauer 					spi_set_cs(msg->spi, true, false);
1676b158935fSMark Brown 			}
16775e0531f6SChristophe Leroy 		} else if (!list_is_last(&xfer->transfer_list, &msg->transfers) &&
16785e0531f6SChristophe Leroy 			   xfer->cs_off != list_next_entry(xfer, transfer_list)->cs_off) {
16795e0531f6SChristophe Leroy 			spi_set_cs(msg->spi, xfer->cs_off, false);
1680b158935fSMark Brown 		}
1681b158935fSMark Brown 
1682b158935fSMark Brown 		msg->actual_length += xfer->len;
1683b158935fSMark Brown 	}
1684b158935fSMark Brown 
1685b158935fSMark Brown out:
1686b158935fSMark Brown 	if (ret != 0 || !keep_cs)
1687d347b4aaSDavid Bauer 		spi_set_cs(msg->spi, false, false);
1688b158935fSMark Brown 
1689b158935fSMark Brown 	if (msg->status == -EINPROGRESS)
1690b158935fSMark Brown 		msg->status = ret;
1691b158935fSMark Brown 
16928caab75fSGeert Uytterhoeven 	if (msg->status && ctlr->handle_err)
16938caab75fSGeert Uytterhoeven 		ctlr->handle_err(ctlr, msg);
1694b716c4ffSAndy Shevchenko 
16950ed56252SMark Brown 	spi_finalize_current_message(ctlr);
16960ed56252SMark Brown 
1697b158935fSMark Brown 	return ret;
1698b158935fSMark Brown }
1699b158935fSMark Brown 
1700b158935fSMark Brown /**
1701b158935fSMark Brown  * spi_finalize_current_transfer - report completion of a transfer
17028caab75fSGeert Uytterhoeven  * @ctlr: the controller reporting completion
1703b158935fSMark Brown  *
1704b158935fSMark Brown  * Called by SPI drivers using the core transfer_one_message()
1705b158935fSMark Brown  * implementation to notify it that the current interrupt driven
17069e8f4882SGeert Uytterhoeven  * transfer has finished and the next one may be scheduled.
1707b158935fSMark Brown  */
17088caab75fSGeert Uytterhoeven void spi_finalize_current_transfer(struct spi_controller *ctlr)
1709b158935fSMark Brown {
17108caab75fSGeert Uytterhoeven 	complete(&ctlr->xfer_completion);
1711b158935fSMark Brown }
1712b158935fSMark Brown EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1713b158935fSMark Brown 
1714e1268597SMark Brown static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1715e1268597SMark Brown {
1716e1268597SMark Brown 	if (ctlr->auto_runtime_pm) {
1717e1268597SMark Brown 		pm_runtime_mark_last_busy(ctlr->dev.parent);
1718e1268597SMark Brown 		pm_runtime_put_autosuspend(ctlr->dev.parent);
1719e1268597SMark Brown 	}
1720e1268597SMark Brown }
1721e1268597SMark Brown 
1722ae7d2346SDavid Jander static int __spi_pump_transfer_message(struct spi_controller *ctlr,
1723ae7d2346SDavid Jander 		struct spi_message *msg, bool was_busy)
1724ae7d2346SDavid Jander {
1725ae7d2346SDavid Jander 	struct spi_transfer *xfer;
1726ae7d2346SDavid Jander 	int ret;
1727ae7d2346SDavid Jander 
1728ae7d2346SDavid Jander 	if (!was_busy && ctlr->auto_runtime_pm) {
1729ae7d2346SDavid Jander 		ret = pm_runtime_get_sync(ctlr->dev.parent);
1730ae7d2346SDavid Jander 		if (ret < 0) {
1731ae7d2346SDavid Jander 			pm_runtime_put_noidle(ctlr->dev.parent);
1732ae7d2346SDavid Jander 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
1733ae7d2346SDavid Jander 				ret);
17348c2ae772SDavid Lechner 
17358c2ae772SDavid Lechner 			msg->status = ret;
17368c2ae772SDavid Lechner 			spi_finalize_current_message(ctlr);
17378c2ae772SDavid Lechner 
1738ae7d2346SDavid Jander 			return ret;
1739ae7d2346SDavid Jander 		}
1740ae7d2346SDavid Jander 	}
1741ae7d2346SDavid Jander 
1742ae7d2346SDavid Jander 	if (!was_busy)
1743ae7d2346SDavid Jander 		trace_spi_controller_busy(ctlr);
1744ae7d2346SDavid Jander 
1745ae7d2346SDavid Jander 	if (!was_busy && ctlr->prepare_transfer_hardware) {
1746ae7d2346SDavid Jander 		ret = ctlr->prepare_transfer_hardware(ctlr);
1747ae7d2346SDavid Jander 		if (ret) {
1748ae7d2346SDavid Jander 			dev_err(&ctlr->dev,
1749ae7d2346SDavid Jander 				"failed to prepare transfer hardware: %d\n",
1750ae7d2346SDavid Jander 				ret);
1751ae7d2346SDavid Jander 
1752ae7d2346SDavid Jander 			if (ctlr->auto_runtime_pm)
1753ae7d2346SDavid Jander 				pm_runtime_put(ctlr->dev.parent);
1754ae7d2346SDavid Jander 
1755ae7d2346SDavid Jander 			msg->status = ret;
1756ae7d2346SDavid Jander 			spi_finalize_current_message(ctlr);
1757ae7d2346SDavid Jander 
1758ae7d2346SDavid Jander 			return ret;
1759ae7d2346SDavid Jander 		}
1760ae7d2346SDavid Jander 	}
1761ae7d2346SDavid Jander 
1762ae7d2346SDavid Jander 	trace_spi_message_start(msg);
1763ae7d2346SDavid Jander 
1764ae7d2346SDavid Jander 	if (ctlr->prepare_message) {
1765ae7d2346SDavid Jander 		ret = ctlr->prepare_message(ctlr, msg);
1766ae7d2346SDavid Jander 		if (ret) {
1767ae7d2346SDavid Jander 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1768ae7d2346SDavid Jander 				ret);
1769ae7d2346SDavid Jander 			msg->status = ret;
1770ae7d2346SDavid Jander 			spi_finalize_current_message(ctlr);
1771ae7d2346SDavid Jander 			return ret;
1772ae7d2346SDavid Jander 		}
1773ae7d2346SDavid Jander 		msg->prepared = true;
1774ae7d2346SDavid Jander 	}
1775ae7d2346SDavid Jander 
1776ae7d2346SDavid Jander 	ret = spi_map_msg(ctlr, msg);
1777ae7d2346SDavid Jander 	if (ret) {
1778ae7d2346SDavid Jander 		msg->status = ret;
1779ae7d2346SDavid Jander 		spi_finalize_current_message(ctlr);
1780ae7d2346SDavid Jander 		return ret;
1781ae7d2346SDavid Jander 	}
1782ae7d2346SDavid Jander 
1783ae7d2346SDavid Jander 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1784ae7d2346SDavid Jander 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1785ae7d2346SDavid Jander 			xfer->ptp_sts_word_pre = 0;
1786ae7d2346SDavid Jander 			ptp_read_system_prets(xfer->ptp_sts);
1787ae7d2346SDavid Jander 		}
1788ae7d2346SDavid Jander 	}
1789ae7d2346SDavid Jander 
1790dc302905SDavid Jander 	/*
1791dc302905SDavid Jander 	 * Drivers implementation of transfer_one_message() must arrange for
1792dc302905SDavid Jander 	 * spi_finalize_current_message() to get called. Most drivers will do
1793dc302905SDavid Jander 	 * this in the calling context, but some don't. For those cases, a
1794dc302905SDavid Jander 	 * completion is used to guarantee that this function does not return
1795dc302905SDavid Jander 	 * until spi_finalize_current_message() is done accessing
1796dc302905SDavid Jander 	 * ctlr->cur_msg.
1797dc302905SDavid Jander 	 * Use of the following two flags enable to opportunistically skip the
1798dc302905SDavid Jander 	 * use of the completion since its use involves expensive spin locks.
1799dc302905SDavid Jander 	 * In case of a race with the context that calls
1800dc302905SDavid Jander 	 * spi_finalize_current_message() the completion will always be used,
1801dc302905SDavid Jander 	 * due to strict ordering of these flags using barriers.
1802dc302905SDavid Jander 	 */
1803dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_incomplete, true);
1804dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_need_completion, false);
180569fa9590SDavid Jander 	reinit_completion(&ctlr->cur_msg_completion);
180695c8222fSDavid Jander 	smp_wmb(); /* Make these available to spi_finalize_current_message() */
1807dc302905SDavid Jander 
1808ae7d2346SDavid Jander 	ret = ctlr->transfer_one_message(ctlr, msg);
1809ae7d2346SDavid Jander 	if (ret) {
1810ae7d2346SDavid Jander 		dev_err(&ctlr->dev,
1811ae7d2346SDavid Jander 			"failed to transfer one message from queue\n");
1812ae7d2346SDavid Jander 		return ret;
181331d4c1bdSDavid Jander 	}
181431d4c1bdSDavid Jander 
1815dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_need_completion, true);
181631d4c1bdSDavid Jander 	smp_mb(); /* See spi_finalize_current_message()... */
1817dc302905SDavid Jander 	if (READ_ONCE(ctlr->cur_msg_incomplete))
181869fa9590SDavid Jander 		wait_for_completion(&ctlr->cur_msg_completion);
1819ae7d2346SDavid Jander 
1820ae7d2346SDavid Jander 	return 0;
1821ae7d2346SDavid Jander }
1822ae7d2346SDavid Jander 
1823ffbbdd21SLinus Walleij /**
1824702ca026SAndy Shevchenko  * __spi_pump_messages - function which processes SPI message queue
18258caab75fSGeert Uytterhoeven  * @ctlr: controller to process queue for
1826fc9e0f71SMark Brown  * @in_kthread: true if we are in the context of the message pump thread
1827ffbbdd21SLinus Walleij  *
1828702ca026SAndy Shevchenko  * This function checks if there is any SPI message in the queue that
1829ffbbdd21SLinus Walleij  * needs processing and if so call out to the driver to initialize hardware
1830ffbbdd21SLinus Walleij  * and transfer each message.
1831ffbbdd21SLinus Walleij  *
18320461a414SMark Brown  * Note that it is called both from the kthread itself and also from
18330461a414SMark Brown  * inside spi_sync(); the queue extraction handling at the top of the
18340461a414SMark Brown  * function should deal with this safely.
1835ffbbdd21SLinus Walleij  */
18368caab75fSGeert Uytterhoeven static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1837ffbbdd21SLinus Walleij {
1838d1c44c93SVladimir Oltean 	struct spi_message *msg;
1839ffbbdd21SLinus Walleij 	bool was_busy = false;
1840d1c44c93SVladimir Oltean 	unsigned long flags;
1841ffbbdd21SLinus Walleij 	int ret;
1842ffbbdd21SLinus Walleij 
1843702ca026SAndy Shevchenko 	/* Take the I/O mutex */
1844c1038165SDavid Jander 	mutex_lock(&ctlr->io_mutex);
1845c1038165SDavid Jander 
1846983aee5dSMark Brown 	/* Lock queue */
18478caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1848983aee5dSMark Brown 
1849983aee5dSMark Brown 	/* Make sure we are not already running a message */
18508711a2abSDavid Jander 	if (ctlr->cur_msg)
1851c1038165SDavid Jander 		goto out_unlock;
1852983aee5dSMark Brown 
1853983aee5dSMark Brown 	/* Check if the queue is idle */
18548caab75fSGeert Uytterhoeven 	if (list_empty(&ctlr->queue) || !ctlr->running) {
18558711a2abSDavid Jander 		if (!ctlr->busy)
1856c1038165SDavid Jander 			goto out_unlock;
1857fc9e0f71SMark Brown 
1858e1268597SMark Brown 		/* Defer any non-atomic teardown to the thread */
1859f0125f1aSMark Brown 		if (!in_kthread) {
1860e1268597SMark Brown 			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1861e1268597SMark Brown 			    !ctlr->unprepare_transfer_hardware) {
1862e1268597SMark Brown 				spi_idle_runtime_pm(ctlr);
1863e1268597SMark Brown 				ctlr->busy = false;
1864ae7d2346SDavid Jander 				ctlr->queue_empty = true;
1865e1268597SMark Brown 				trace_spi_controller_idle(ctlr);
1866e1268597SMark Brown 			} else {
186760a883d1SMarek Szyprowski 				kthread_queue_work(ctlr->kworker,
1868f0125f1aSMark Brown 						   &ctlr->pump_messages);
1869e1268597SMark Brown 			}
1870c1038165SDavid Jander 			goto out_unlock;
1871f0125f1aSMark Brown 		}
1872f0125f1aSMark Brown 
1873f0125f1aSMark Brown 		ctlr->busy = false;
1874f0125f1aSMark Brown 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1875f0125f1aSMark Brown 
1876f0125f1aSMark Brown 		kfree(ctlr->dummy_rx);
1877f0125f1aSMark Brown 		ctlr->dummy_rx = NULL;
1878f0125f1aSMark Brown 		kfree(ctlr->dummy_tx);
1879f0125f1aSMark Brown 		ctlr->dummy_tx = NULL;
1880f0125f1aSMark Brown 		if (ctlr->unprepare_transfer_hardware &&
1881f0125f1aSMark Brown 		    ctlr->unprepare_transfer_hardware(ctlr))
1882f0125f1aSMark Brown 			dev_err(&ctlr->dev,
1883f0125f1aSMark Brown 				"failed to unprepare transfer hardware\n");
1884e1268597SMark Brown 		spi_idle_runtime_pm(ctlr);
1885f0125f1aSMark Brown 		trace_spi_controller_idle(ctlr);
1886f0125f1aSMark Brown 
1887f0125f1aSMark Brown 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1888ae7d2346SDavid Jander 		ctlr->queue_empty = true;
1889c1038165SDavid Jander 		goto out_unlock;
1890ffbbdd21SLinus Walleij 	}
1891ffbbdd21SLinus Walleij 
1892ffbbdd21SLinus Walleij 	/* Extract head of queue */
1893d1c44c93SVladimir Oltean 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1894d1c44c93SVladimir Oltean 	ctlr->cur_msg = msg;
1895ffbbdd21SLinus Walleij 
1896d1c44c93SVladimir Oltean 	list_del_init(&msg->queue);
18978caab75fSGeert Uytterhoeven 	if (ctlr->busy)
1898ffbbdd21SLinus Walleij 		was_busy = true;
1899ffbbdd21SLinus Walleij 	else
19008caab75fSGeert Uytterhoeven 		ctlr->busy = true;
19018caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1902ffbbdd21SLinus Walleij 
1903ae7d2346SDavid Jander 	ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
190469fa9590SDavid Jander 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1905c191543eSDavid Jander 
190669fa9590SDavid Jander 	ctlr->cur_msg = NULL;
190769fa9590SDavid Jander 	ctlr->fallback = false;
190869fa9590SDavid Jander 
19098caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->io_mutex);
191062826970SMark Brown 
191162826970SMark Brown 	/* Prod the scheduler in case transfer_one() was busy waiting */
191249023d2eSJon Hunter 	if (!ret)
191362826970SMark Brown 		cond_resched();
1914c1038165SDavid Jander 	return;
1915c1038165SDavid Jander 
1916c1038165SDavid Jander out_unlock:
19178711a2abSDavid Jander 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1918c1038165SDavid Jander 	mutex_unlock(&ctlr->io_mutex);
1919ffbbdd21SLinus Walleij }
1920ffbbdd21SLinus Walleij 
1921fc9e0f71SMark Brown /**
1922fc9e0f71SMark Brown  * spi_pump_messages - kthread work function which processes spi message queue
19238caab75fSGeert Uytterhoeven  * @work: pointer to kthread work struct contained in the controller struct
1924fc9e0f71SMark Brown  */
1925fc9e0f71SMark Brown static void spi_pump_messages(struct kthread_work *work)
1926fc9e0f71SMark Brown {
19278caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr =
19288caab75fSGeert Uytterhoeven 		container_of(work, struct spi_controller, pump_messages);
1929fc9e0f71SMark Brown 
19308caab75fSGeert Uytterhoeven 	__spi_pump_messages(ctlr, true);
1931fc9e0f71SMark Brown }
1932fc9e0f71SMark Brown 
1933924b5867SDouglas Anderson /**
1934350de7ceSAndy Shevchenko  * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
1935b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1936b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1937862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1938b42faeeeSVladimir Oltean  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1939b42faeeeSVladimir Oltean  *	      transfer, for less jitter in time measurement. Only compatible
1940b42faeeeSVladimir Oltean  *	      with PIO drivers. If true, must follow up with
1941b42faeeeSVladimir Oltean  *	      spi_take_timestamp_post or otherwise system will crash.
1942b42faeeeSVladimir Oltean  *	      WARNING: for fully predictable results, the CPU frequency must
1943b42faeeeSVladimir Oltean  *	      also be under control (governor).
1944350de7ceSAndy Shevchenko  *
1945350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the beginning of the TX timestamp
1946350de7ceSAndy Shevchenko  * for the requested byte from the SPI transfer. The frequency with which this
1947350de7ceSAndy Shevchenko  * function must be called (once per word, once for the whole transfer, once
1948350de7ceSAndy Shevchenko  * per batch of words etc) is arbitrary as long as the @tx buffer offset is
1949350de7ceSAndy Shevchenko  * greater than or equal to the requested byte at the time of the call. The
1950350de7ceSAndy Shevchenko  * timestamp is only taken once, at the first such call. It is assumed that
1951350de7ceSAndy Shevchenko  * the driver advances its @tx buffer pointer monotonically.
1952b42faeeeSVladimir Oltean  */
1953b42faeeeSVladimir Oltean void spi_take_timestamp_pre(struct spi_controller *ctlr,
1954b42faeeeSVladimir Oltean 			    struct spi_transfer *xfer,
1955862dd2a9SVladimir Oltean 			    size_t progress, bool irqs_off)
1956b42faeeeSVladimir Oltean {
1957b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1958b42faeeeSVladimir Oltean 		return;
1959b42faeeeSVladimir Oltean 
19606a726824SVladimir Oltean 	if (xfer->timestamped)
1961b42faeeeSVladimir Oltean 		return;
1962b42faeeeSVladimir Oltean 
19636a726824SVladimir Oltean 	if (progress > xfer->ptp_sts_word_pre)
1964b42faeeeSVladimir Oltean 		return;
1965b42faeeeSVladimir Oltean 
1966b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1967862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_pre = progress;
1968b42faeeeSVladimir Oltean 
1969b42faeeeSVladimir Oltean 	if (irqs_off) {
1970b42faeeeSVladimir Oltean 		local_irq_save(ctlr->irq_flags);
1971b42faeeeSVladimir Oltean 		preempt_disable();
1972b42faeeeSVladimir Oltean 	}
1973b42faeeeSVladimir Oltean 
1974b42faeeeSVladimir Oltean 	ptp_read_system_prets(xfer->ptp_sts);
1975b42faeeeSVladimir Oltean }
1976b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1977b42faeeeSVladimir Oltean 
1978b42faeeeSVladimir Oltean /**
1979350de7ceSAndy Shevchenko  * spi_take_timestamp_post - helper to collect the end of the TX timestamp
1980b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1981b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1982862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1983b42faeeeSVladimir Oltean  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1984350de7ceSAndy Shevchenko  *
1985350de7ceSAndy Shevchenko  * This is a helper for drivers to collect the end of the TX timestamp for
1986350de7ceSAndy Shevchenko  * the requested byte from the SPI transfer. Can be called with an arbitrary
1987350de7ceSAndy Shevchenko  * frequency: only the first call where @tx exceeds or is equal to the
1988350de7ceSAndy Shevchenko  * requested word will be timestamped.
1989b42faeeeSVladimir Oltean  */
1990b42faeeeSVladimir Oltean void spi_take_timestamp_post(struct spi_controller *ctlr,
1991b42faeeeSVladimir Oltean 			     struct spi_transfer *xfer,
1992862dd2a9SVladimir Oltean 			     size_t progress, bool irqs_off)
1993b42faeeeSVladimir Oltean {
1994b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1995b42faeeeSVladimir Oltean 		return;
1996b42faeeeSVladimir Oltean 
19976a726824SVladimir Oltean 	if (xfer->timestamped)
1998b42faeeeSVladimir Oltean 		return;
1999b42faeeeSVladimir Oltean 
2000862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_post)
2001b42faeeeSVladimir Oltean 		return;
2002b42faeeeSVladimir Oltean 
2003b42faeeeSVladimir Oltean 	ptp_read_system_postts(xfer->ptp_sts);
2004b42faeeeSVladimir Oltean 
2005b42faeeeSVladimir Oltean 	if (irqs_off) {
2006b42faeeeSVladimir Oltean 		local_irq_restore(ctlr->irq_flags);
2007b42faeeeSVladimir Oltean 		preempt_enable();
2008b42faeeeSVladimir Oltean 	}
2009b42faeeeSVladimir Oltean 
2010b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
2011862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_post = progress;
2012b42faeeeSVladimir Oltean 
20139d77522bSChristophe JAILLET 	xfer->timestamped = 1;
2014b42faeeeSVladimir Oltean }
2015b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
2016b42faeeeSVladimir Oltean 
2017b42faeeeSVladimir Oltean /**
2018924b5867SDouglas Anderson  * spi_set_thread_rt - set the controller to pump at realtime priority
2019924b5867SDouglas Anderson  * @ctlr: controller to boost priority of
2020924b5867SDouglas Anderson  *
2021924b5867SDouglas Anderson  * This can be called because the controller requested realtime priority
2022924b5867SDouglas Anderson  * (by setting the ->rt value before calling spi_register_controller()) or
2023924b5867SDouglas Anderson  * because a device on the bus said that its transfers needed realtime
2024924b5867SDouglas Anderson  * priority.
2025924b5867SDouglas Anderson  *
2026924b5867SDouglas Anderson  * NOTE: at the moment if any device on a bus says it needs realtime then
2027924b5867SDouglas Anderson  * the thread will be at realtime priority for all transfers on that
2028924b5867SDouglas Anderson  * controller.  If this eventually becomes a problem we may see if we can
2029924b5867SDouglas Anderson  * find a way to boost the priority only temporarily during relevant
2030924b5867SDouglas Anderson  * transfers.
2031924b5867SDouglas Anderson  */
2032924b5867SDouglas Anderson static void spi_set_thread_rt(struct spi_controller *ctlr)
2033ffbbdd21SLinus Walleij {
2034924b5867SDouglas Anderson 	dev_info(&ctlr->dev,
2035924b5867SDouglas Anderson 		"will run message pump with realtime priority\n");
20366d2b84a4SLinus Torvalds 	sched_set_fifo(ctlr->kworker->task);
2037924b5867SDouglas Anderson }
2038924b5867SDouglas Anderson 
2039924b5867SDouglas Anderson static int spi_init_queue(struct spi_controller *ctlr)
2040924b5867SDouglas Anderson {
20418caab75fSGeert Uytterhoeven 	ctlr->running = false;
20428caab75fSGeert Uytterhoeven 	ctlr->busy = false;
2043ae7d2346SDavid Jander 	ctlr->queue_empty = true;
2044ffbbdd21SLinus Walleij 
204560a883d1SMarek Szyprowski 	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
204660a883d1SMarek Szyprowski 	if (IS_ERR(ctlr->kworker)) {
204760a883d1SMarek Szyprowski 		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
204860a883d1SMarek Szyprowski 		return PTR_ERR(ctlr->kworker);
2049ffbbdd21SLinus Walleij 	}
205060a883d1SMarek Szyprowski 
20518caab75fSGeert Uytterhoeven 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
2052f0125f1aSMark Brown 
2053ffbbdd21SLinus Walleij 	/*
20548caab75fSGeert Uytterhoeven 	 * Controller config will indicate if this controller should run the
2055ffbbdd21SLinus Walleij 	 * message pump with high (realtime) priority to reduce the transfer
2056ffbbdd21SLinus Walleij 	 * latency on the bus by minimising the delay between a transfer
2057ffbbdd21SLinus Walleij 	 * request and the scheduling of the message pump thread. Without this
2058ffbbdd21SLinus Walleij 	 * setting the message pump thread will remain at default priority.
2059ffbbdd21SLinus Walleij 	 */
2060924b5867SDouglas Anderson 	if (ctlr->rt)
2061924b5867SDouglas Anderson 		spi_set_thread_rt(ctlr);
2062ffbbdd21SLinus Walleij 
2063ffbbdd21SLinus Walleij 	return 0;
2064ffbbdd21SLinus Walleij }
2065ffbbdd21SLinus Walleij 
2066ffbbdd21SLinus Walleij /**
2067ffbbdd21SLinus Walleij  * spi_get_next_queued_message() - called by driver to check for queued
2068ffbbdd21SLinus Walleij  * messages
20698caab75fSGeert Uytterhoeven  * @ctlr: the controller to check for queued messages
2070ffbbdd21SLinus Walleij  *
2071ffbbdd21SLinus Walleij  * If there are more messages in the queue, the next message is returned from
2072ffbbdd21SLinus Walleij  * this call.
207397d56dc6SJavier Martinez Canillas  *
207497d56dc6SJavier Martinez Canillas  * Return: the next message in the queue, else NULL if the queue is empty.
2075ffbbdd21SLinus Walleij  */
20768caab75fSGeert Uytterhoeven struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
2077ffbbdd21SLinus Walleij {
2078ffbbdd21SLinus Walleij 	struct spi_message *next;
2079ffbbdd21SLinus Walleij 	unsigned long flags;
2080ffbbdd21SLinus Walleij 
208195c8222fSDavid Jander 	/* Get a pointer to the next message, if any */
20828caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
20838caab75fSGeert Uytterhoeven 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
20841cfd97f9SAxel Lin 					queue);
20858caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2086ffbbdd21SLinus Walleij 
2087ffbbdd21SLinus Walleij 	return next;
2088ffbbdd21SLinus Walleij }
2089ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
2090ffbbdd21SLinus Walleij 
20917b1d87afSDavid Lechner /*
20927b1d87afSDavid Lechner  * __spi_unoptimize_message - shared implementation of spi_unoptimize_message()
20937b1d87afSDavid Lechner  *                            and spi_maybe_unoptimize_message()
20947b1d87afSDavid Lechner  * @msg: the message to unoptimize
20957b1d87afSDavid Lechner  *
20967b1d87afSDavid Lechner  * Peripheral drivers should use spi_unoptimize_message() and callers inside
20977b1d87afSDavid Lechner  * core should use spi_maybe_unoptimize_message() rather than calling this
20987b1d87afSDavid Lechner  * function directly.
20997b1d87afSDavid Lechner  *
21007b1d87afSDavid Lechner  * It is not valid to call this on a message that is not currently optimized.
21017b1d87afSDavid Lechner  */
21027b1d87afSDavid Lechner static void __spi_unoptimize_message(struct spi_message *msg)
21037b1d87afSDavid Lechner {
21047b1d87afSDavid Lechner 	struct spi_controller *ctlr = msg->spi->controller;
21057b1d87afSDavid Lechner 
21067b1d87afSDavid Lechner 	if (ctlr->unoptimize_message)
21077b1d87afSDavid Lechner 		ctlr->unoptimize_message(msg);
21087b1d87afSDavid Lechner 
2109fab53feaSDavid Lechner 	spi_res_release(ctlr, msg);
2110fab53feaSDavid Lechner 
21117b1d87afSDavid Lechner 	msg->optimized = false;
21127b1d87afSDavid Lechner 	msg->opt_state = NULL;
21137b1d87afSDavid Lechner }
21147b1d87afSDavid Lechner 
21157b1d87afSDavid Lechner /*
21167b1d87afSDavid Lechner  * spi_maybe_unoptimize_message - unoptimize msg not managed by a peripheral
21177b1d87afSDavid Lechner  * @msg: the message to unoptimize
21187b1d87afSDavid Lechner  *
21197b1d87afSDavid Lechner  * This function is used to unoptimize a message if and only if it was
21207b1d87afSDavid Lechner  * optimized by the core (via spi_maybe_optimize_message()).
21217b1d87afSDavid Lechner  */
21227b1d87afSDavid Lechner static void spi_maybe_unoptimize_message(struct spi_message *msg)
21237b1d87afSDavid Lechner {
21247b1d87afSDavid Lechner 	if (!msg->pre_optimized && msg->optimized)
21257b1d87afSDavid Lechner 		__spi_unoptimize_message(msg);
21267b1d87afSDavid Lechner }
21277b1d87afSDavid Lechner 
2128ffbbdd21SLinus Walleij /**
2129ffbbdd21SLinus Walleij  * spi_finalize_current_message() - the current message is complete
21308caab75fSGeert Uytterhoeven  * @ctlr: the controller to return the message to
2131ffbbdd21SLinus Walleij  *
2132ffbbdd21SLinus Walleij  * Called by the driver to notify the core that the message in the front of the
2133ffbbdd21SLinus Walleij  * queue is complete and can be removed from the queue.
2134ffbbdd21SLinus Walleij  */
21358caab75fSGeert Uytterhoeven void spi_finalize_current_message(struct spi_controller *ctlr)
2136ffbbdd21SLinus Walleij {
2137b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
2138ffbbdd21SLinus Walleij 	struct spi_message *mesg;
21392841a5fcSMark Brown 	int ret;
2140ffbbdd21SLinus Walleij 
21418caab75fSGeert Uytterhoeven 	mesg = ctlr->cur_msg;
2142ffbbdd21SLinus Walleij 
2143b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
2144b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
2145b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
2146b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
2147b42faeeeSVladimir Oltean 		}
2148b42faeeeSVladimir Oltean 	}
2149b42faeeeSVladimir Oltean 
21506a726824SVladimir Oltean 	if (unlikely(ctlr->ptp_sts_supported))
21516a726824SVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
21526a726824SVladimir Oltean 			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
2153f971a207SVladimir Oltean 
21548caab75fSGeert Uytterhoeven 	spi_unmap_msg(ctlr, mesg);
215599adef31SMark Brown 
21561714582aSDavid Jander 	if (mesg->prepared && ctlr->unprepare_message) {
21578caab75fSGeert Uytterhoeven 		ret = ctlr->unprepare_message(ctlr, mesg);
21582841a5fcSMark Brown 		if (ret) {
21598caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
21608caab75fSGeert Uytterhoeven 				ret);
21612841a5fcSMark Brown 		}
21622841a5fcSMark Brown 	}
2163391949b6SUwe Kleine-König 
21641714582aSDavid Jander 	mesg->prepared = false;
21651714582aSDavid Jander 
21667b1d87afSDavid Lechner 	spi_maybe_unoptimize_message(mesg);
21677b1d87afSDavid Lechner 
2168dc302905SDavid Jander 	WRITE_ONCE(ctlr->cur_msg_incomplete, false);
2169dc302905SDavid Jander 	smp_mb(); /* See __spi_pump_transfer_message()... */
2170dc302905SDavid Jander 	if (READ_ONCE(ctlr->cur_msg_need_completion))
217169fa9590SDavid Jander 		complete(&ctlr->cur_msg_completion);
21728e76ef88SMartin Sperl 
21738e76ef88SMartin Sperl 	trace_spi_message_done(mesg);
21742841a5fcSMark Brown 
2175ffbbdd21SLinus Walleij 	mesg->state = NULL;
2176ffbbdd21SLinus Walleij 	if (mesg->complete)
2177ffbbdd21SLinus Walleij 		mesg->complete(mesg->context);
2178ffbbdd21SLinus Walleij }
2179ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_finalize_current_message);
2180ffbbdd21SLinus Walleij 
21818caab75fSGeert Uytterhoeven static int spi_start_queue(struct spi_controller *ctlr)
2182ffbbdd21SLinus Walleij {
2183ffbbdd21SLinus Walleij 	unsigned long flags;
2184ffbbdd21SLinus Walleij 
21858caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2186ffbbdd21SLinus Walleij 
21878caab75fSGeert Uytterhoeven 	if (ctlr->running || ctlr->busy) {
21888caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2189ffbbdd21SLinus Walleij 		return -EBUSY;
2190ffbbdd21SLinus Walleij 	}
2191ffbbdd21SLinus Walleij 
21928caab75fSGeert Uytterhoeven 	ctlr->running = true;
21938caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
21948caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2195ffbbdd21SLinus Walleij 
219660a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2197ffbbdd21SLinus Walleij 
2198ffbbdd21SLinus Walleij 	return 0;
2199ffbbdd21SLinus Walleij }
2200ffbbdd21SLinus Walleij 
22018caab75fSGeert Uytterhoeven static int spi_stop_queue(struct spi_controller *ctlr)
2202ffbbdd21SLinus Walleij {
2203ffbbdd21SLinus Walleij 	unsigned long flags;
2204ffbbdd21SLinus Walleij 	unsigned limit = 500;
2205ffbbdd21SLinus Walleij 	int ret = 0;
2206ffbbdd21SLinus Walleij 
22078caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2208ffbbdd21SLinus Walleij 
2209ffbbdd21SLinus Walleij 	/*
2210ffbbdd21SLinus Walleij 	 * This is a bit lame, but is optimized for the common execution path.
22118caab75fSGeert Uytterhoeven 	 * A wait_queue on the ctlr->busy could be used, but then the common
2212ffbbdd21SLinus Walleij 	 * execution path (pump_messages) would be required to call wake_up or
2213ffbbdd21SLinus Walleij 	 * friends on every SPI message. Do this instead.
2214ffbbdd21SLinus Walleij 	 */
22158caab75fSGeert Uytterhoeven 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
22168caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2217f97b26b0SAxel Lin 		usleep_range(10000, 11000);
22188caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->queue_lock, flags);
2219ffbbdd21SLinus Walleij 	}
2220ffbbdd21SLinus Walleij 
22218caab75fSGeert Uytterhoeven 	if (!list_empty(&ctlr->queue) || ctlr->busy)
2222ffbbdd21SLinus Walleij 		ret = -EBUSY;
2223ffbbdd21SLinus Walleij 	else
22248caab75fSGeert Uytterhoeven 		ctlr->running = false;
2225ffbbdd21SLinus Walleij 
22268caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2227ffbbdd21SLinus Walleij 
2228ffbbdd21SLinus Walleij 	return ret;
2229ffbbdd21SLinus Walleij }
2230ffbbdd21SLinus Walleij 
22318caab75fSGeert Uytterhoeven static int spi_destroy_queue(struct spi_controller *ctlr)
2232ffbbdd21SLinus Walleij {
2233ffbbdd21SLinus Walleij 	int ret;
2234ffbbdd21SLinus Walleij 
22358caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
2236ffbbdd21SLinus Walleij 
2237ffbbdd21SLinus Walleij 	/*
22383989144fSPetr Mladek 	 * kthread_flush_worker will block until all work is done.
2239ffbbdd21SLinus Walleij 	 * If the reason that stop_queue timed out is that the work will never
2240ffbbdd21SLinus Walleij 	 * finish, then it does no good to call flush/stop thread, so
2241ffbbdd21SLinus Walleij 	 * return anyway.
2242ffbbdd21SLinus Walleij 	 */
2243ffbbdd21SLinus Walleij 	if (ret) {
22448caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem destroying queue\n");
2245ffbbdd21SLinus Walleij 		return ret;
2246ffbbdd21SLinus Walleij 	}
2247ffbbdd21SLinus Walleij 
224860a883d1SMarek Szyprowski 	kthread_destroy_worker(ctlr->kworker);
2249ffbbdd21SLinus Walleij 
2250ffbbdd21SLinus Walleij 	return 0;
2251ffbbdd21SLinus Walleij }
2252ffbbdd21SLinus Walleij 
22530461a414SMark Brown static int __spi_queued_transfer(struct spi_device *spi,
22540461a414SMark Brown 				 struct spi_message *msg,
22550461a414SMark Brown 				 bool need_pump)
2256ffbbdd21SLinus Walleij {
22578caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
2258ffbbdd21SLinus Walleij 	unsigned long flags;
2259ffbbdd21SLinus Walleij 
22608caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
2261ffbbdd21SLinus Walleij 
22628caab75fSGeert Uytterhoeven 	if (!ctlr->running) {
22638caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2264ffbbdd21SLinus Walleij 		return -ESHUTDOWN;
2265ffbbdd21SLinus Walleij 	}
2266ffbbdd21SLinus Walleij 	msg->actual_length = 0;
2267ffbbdd21SLinus Walleij 	msg->status = -EINPROGRESS;
2268ffbbdd21SLinus Walleij 
22698caab75fSGeert Uytterhoeven 	list_add_tail(&msg->queue, &ctlr->queue);
2270ae7d2346SDavid Jander 	ctlr->queue_empty = false;
2271f0125f1aSMark Brown 	if (!ctlr->busy && need_pump)
227260a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
2273ffbbdd21SLinus Walleij 
22748caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
2275ffbbdd21SLinus Walleij 	return 0;
2276ffbbdd21SLinus Walleij }
2277ffbbdd21SLinus Walleij 
22780461a414SMark Brown /**
22790461a414SMark Brown  * spi_queued_transfer - transfer function for queued transfers
2280702ca026SAndy Shevchenko  * @spi: SPI device which is requesting transfer
2281702ca026SAndy Shevchenko  * @msg: SPI message which is to handled is queued to driver queue
228297d56dc6SJavier Martinez Canillas  *
228397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
22840461a414SMark Brown  */
22850461a414SMark Brown static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
22860461a414SMark Brown {
22870461a414SMark Brown 	return __spi_queued_transfer(spi, msg, true);
22880461a414SMark Brown }
22890461a414SMark Brown 
22908caab75fSGeert Uytterhoeven static int spi_controller_initialize_queue(struct spi_controller *ctlr)
2291ffbbdd21SLinus Walleij {
2292ffbbdd21SLinus Walleij 	int ret;
2293ffbbdd21SLinus Walleij 
22948caab75fSGeert Uytterhoeven 	ctlr->transfer = spi_queued_transfer;
22958caab75fSGeert Uytterhoeven 	if (!ctlr->transfer_one_message)
22968caab75fSGeert Uytterhoeven 		ctlr->transfer_one_message = spi_transfer_one_message;
2297ffbbdd21SLinus Walleij 
2298ffbbdd21SLinus Walleij 	/* Initialize and start queue */
22998caab75fSGeert Uytterhoeven 	ret = spi_init_queue(ctlr);
2300ffbbdd21SLinus Walleij 	if (ret) {
23018caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem initializing queue\n");
2302ffbbdd21SLinus Walleij 		goto err_init_queue;
2303ffbbdd21SLinus Walleij 	}
23048caab75fSGeert Uytterhoeven 	ctlr->queued = true;
23058caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
2306ffbbdd21SLinus Walleij 	if (ret) {
23078caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem starting queue\n");
2308ffbbdd21SLinus Walleij 		goto err_start_queue;
2309ffbbdd21SLinus Walleij 	}
2310ffbbdd21SLinus Walleij 
2311ffbbdd21SLinus Walleij 	return 0;
2312ffbbdd21SLinus Walleij 
2313ffbbdd21SLinus Walleij err_start_queue:
23148caab75fSGeert Uytterhoeven 	spi_destroy_queue(ctlr);
2315c3676d5cSMark Brown err_init_queue:
2316ffbbdd21SLinus Walleij 	return ret;
2317ffbbdd21SLinus Walleij }
2318ffbbdd21SLinus Walleij 
2319988f259bSBoris Brezillon /**
2320988f259bSBoris Brezillon  * spi_flush_queue - Send all pending messages in the queue from the callers'
2321988f259bSBoris Brezillon  *		     context
2322988f259bSBoris Brezillon  * @ctlr: controller to process queue for
2323988f259bSBoris Brezillon  *
2324988f259bSBoris Brezillon  * This should be used when one wants to ensure all pending messages have been
2325988f259bSBoris Brezillon  * sent before doing something. Is used by the spi-mem code to make sure SPI
2326988f259bSBoris Brezillon  * memory operations do not preempt regular SPI transfers that have been queued
2327988f259bSBoris Brezillon  * before the spi-mem operation.
2328988f259bSBoris Brezillon  */
2329988f259bSBoris Brezillon void spi_flush_queue(struct spi_controller *ctlr)
2330988f259bSBoris Brezillon {
2331988f259bSBoris Brezillon 	if (ctlr->transfer == spi_queued_transfer)
2332988f259bSBoris Brezillon 		__spi_pump_messages(ctlr, false);
2333988f259bSBoris Brezillon }
2334988f259bSBoris Brezillon 
2335ffbbdd21SLinus Walleij /*-------------------------------------------------------------------------*/
2336ffbbdd21SLinus Walleij 
23377cb94361SAndreas Larsson #if defined(CONFIG_OF)
2338f276aacfSJanne Grunau static void of_spi_parse_dt_cs_delay(struct device_node *nc,
2339f276aacfSJanne Grunau 				     struct spi_delay *delay, const char *prop)
2340f276aacfSJanne Grunau {
2341f276aacfSJanne Grunau 	u32 value;
2342f276aacfSJanne Grunau 
2343f276aacfSJanne Grunau 	if (!of_property_read_u32(nc, prop, &value)) {
2344f276aacfSJanne Grunau 		if (value > U16_MAX) {
2345f276aacfSJanne Grunau 			delay->value = DIV_ROUND_UP(value, 1000);
2346f276aacfSJanne Grunau 			delay->unit = SPI_DELAY_UNIT_USECS;
2347f276aacfSJanne Grunau 		} else {
2348f276aacfSJanne Grunau 			delay->value = value;
2349f276aacfSJanne Grunau 			delay->unit = SPI_DELAY_UNIT_NSECS;
2350f276aacfSJanne Grunau 		}
2351f276aacfSJanne Grunau 	}
2352f276aacfSJanne Grunau }
2353f276aacfSJanne Grunau 
23548caab75fSGeert Uytterhoeven static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
2355c2e51ac3SGeert Uytterhoeven 			   struct device_node *nc)
2356d57a4282SGrant Likely {
23574d8ff6b0SAmit Kumar Mahapatra 	u32 value, cs[SPI_CS_CNT_MAX];
23584d8ff6b0SAmit Kumar Mahapatra 	int rc, idx;
2359d57a4282SGrant Likely 
2360d57a4282SGrant Likely 	/* Mode (clock phase/polarity/etc.) */
2361e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpha"))
2362d57a4282SGrant Likely 		spi->mode |= SPI_CPHA;
2363e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpol"))
2364d57a4282SGrant Likely 		spi->mode |= SPI_CPOL;
2365e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-3wire"))
2366c20151dfSLars-Peter Clausen 		spi->mode |= SPI_3WIRE;
2367e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-lsb-first"))
2368cd6339e6SZhao Qiang 		spi->mode |= SPI_LSB_FIRST;
23693e5ec1dbSGregory CLEMENT 	if (of_property_read_bool(nc, "spi-cs-high"))
2370f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
2371f3186dd8SLinus Walleij 
2372f477b7fbSwangyuhang 	/* Device DUAL/QUAD mode */
237389da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
237489da4293STrent Piepho 		switch (value) {
2375d962608cSDragos Bogdan 		case 0:
2376d962608cSDragos Bogdan 			spi->mode |= SPI_NO_TX;
2377d962608cSDragos Bogdan 			break;
237889da4293STrent Piepho 		case 1:
2379f477b7fbSwangyuhang 			break;
238089da4293STrent Piepho 		case 2:
2381f477b7fbSwangyuhang 			spi->mode |= SPI_TX_DUAL;
2382f477b7fbSwangyuhang 			break;
238389da4293STrent Piepho 		case 4:
2384f477b7fbSwangyuhang 			spi->mode |= SPI_TX_QUAD;
2385f477b7fbSwangyuhang 			break;
23866b03061fSYogesh Narayan Gaur 		case 8:
23876b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_TX_OCTAL;
23886b03061fSYogesh Narayan Gaur 			break;
2389f477b7fbSwangyuhang 		default:
23908caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2391a110f93dSwangyuhang 				"spi-tx-bus-width %d not supported\n",
239289da4293STrent Piepho 				value);
239380874d8cSGeert Uytterhoeven 			break;
2394f477b7fbSwangyuhang 		}
2395a822e99cSMark Brown 	}
2396f477b7fbSwangyuhang 
239789da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
239889da4293STrent Piepho 		switch (value) {
2399d962608cSDragos Bogdan 		case 0:
2400d962608cSDragos Bogdan 			spi->mode |= SPI_NO_RX;
2401d962608cSDragos Bogdan 			break;
240289da4293STrent Piepho 		case 1:
2403f477b7fbSwangyuhang 			break;
240489da4293STrent Piepho 		case 2:
2405f477b7fbSwangyuhang 			spi->mode |= SPI_RX_DUAL;
2406f477b7fbSwangyuhang 			break;
240789da4293STrent Piepho 		case 4:
2408f477b7fbSwangyuhang 			spi->mode |= SPI_RX_QUAD;
2409f477b7fbSwangyuhang 			break;
24106b03061fSYogesh Narayan Gaur 		case 8:
24116b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_RX_OCTAL;
24126b03061fSYogesh Narayan Gaur 			break;
2413f477b7fbSwangyuhang 		default:
24148caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
2415a110f93dSwangyuhang 				"spi-rx-bus-width %d not supported\n",
241689da4293STrent Piepho 				value);
241780874d8cSGeert Uytterhoeven 			break;
2418f477b7fbSwangyuhang 		}
2419a822e99cSMark Brown 	}
2420f477b7fbSwangyuhang 
24218caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr)) {
2422194276b0SRob Herring 		if (!of_node_name_eq(nc, "slave")) {
242325c56c88SRob Herring 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
242425c56c88SRob Herring 				nc);
24256c364062SGeert Uytterhoeven 			return -EINVAL;
24266c364062SGeert Uytterhoeven 		}
24276c364062SGeert Uytterhoeven 		return 0;
24286c364062SGeert Uytterhoeven 	}
24296c364062SGeert Uytterhoeven 
24304d8ff6b0SAmit Kumar Mahapatra 	if (ctlr->num_chipselect > SPI_CS_CNT_MAX) {
24314d8ff6b0SAmit Kumar Mahapatra 		dev_err(&ctlr->dev, "No. of CS is more than max. no. of supported CS\n");
24324d8ff6b0SAmit Kumar Mahapatra 		return -EINVAL;
24334d8ff6b0SAmit Kumar Mahapatra 	}
24344d8ff6b0SAmit Kumar Mahapatra 
24355ee91605SAndy Shevchenko 	spi_set_all_cs_unused(spi);
24364d8ff6b0SAmit Kumar Mahapatra 
24376c364062SGeert Uytterhoeven 	/* Device address */
24384d8ff6b0SAmit Kumar Mahapatra 	rc = of_property_read_variable_u32_array(nc, "reg", &cs[0], 1,
24394d8ff6b0SAmit Kumar Mahapatra 						 SPI_CS_CNT_MAX);
24404d8ff6b0SAmit Kumar Mahapatra 	if (rc < 0) {
244125c56c88SRob Herring 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
244225c56c88SRob Herring 			nc, rc);
24436c364062SGeert Uytterhoeven 		return rc;
24446c364062SGeert Uytterhoeven 	}
24454d8ff6b0SAmit Kumar Mahapatra 	if (rc > ctlr->num_chipselect) {
24464d8ff6b0SAmit Kumar Mahapatra 		dev_err(&ctlr->dev, "%pOF has number of CS > ctlr->num_chipselect (%d)\n",
24474d8ff6b0SAmit Kumar Mahapatra 			nc, rc);
24484d8ff6b0SAmit Kumar Mahapatra 		return rc;
24494d8ff6b0SAmit Kumar Mahapatra 	}
24504d8ff6b0SAmit Kumar Mahapatra 	if ((of_property_read_bool(nc, "parallel-memories")) &&
24514d8ff6b0SAmit Kumar Mahapatra 	    (!(ctlr->flags & SPI_CONTROLLER_MULTI_CS))) {
24524d8ff6b0SAmit Kumar Mahapatra 		dev_err(&ctlr->dev, "SPI controller doesn't support multi CS\n");
24534d8ff6b0SAmit Kumar Mahapatra 		return -EINVAL;
24544d8ff6b0SAmit Kumar Mahapatra 	}
24554d8ff6b0SAmit Kumar Mahapatra 	for (idx = 0; idx < rc; idx++)
24564d8ff6b0SAmit Kumar Mahapatra 		spi_set_chipselect(spi, idx, cs[idx]);
24574d8ff6b0SAmit Kumar Mahapatra 
24584d8ff6b0SAmit Kumar Mahapatra 	/*
24594d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[i] gives the corresponding physical CS for logical CS i
24604d8ff6b0SAmit Kumar Mahapatra 	 * logical CS number is represented by setting the ith bit in spi->cs_index_mask
24614d8ff6b0SAmit Kumar Mahapatra 	 * So, for example, if spi->cs_index_mask = 0x01 then logical CS number is 0 and
24624d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[0] will give the physical CS.
24634d8ff6b0SAmit Kumar Mahapatra 	 * By default spi->chip_select[0] will hold the physical CS number so, set
24644d8ff6b0SAmit Kumar Mahapatra 	 * spi->cs_index_mask as 0x01.
24654d8ff6b0SAmit Kumar Mahapatra 	 */
24664d8ff6b0SAmit Kumar Mahapatra 	spi->cs_index_mask = 0x01;
24676c364062SGeert Uytterhoeven 
2468d57a4282SGrant Likely 	/* Device speed */
2469671c3bf5SChuanhong Guo 	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
247089da4293STrent Piepho 		spi->max_speed_hz = value;
2471d57a4282SGrant Likely 
2472f276aacfSJanne Grunau 	/* Device CS delays */
2473f276aacfSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_setup, "spi-cs-setup-delay-ns");
24745827b31dSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_hold, "spi-cs-hold-delay-ns");
24755827b31dSJanne Grunau 	of_spi_parse_dt_cs_delay(nc, &spi->cs_inactive, "spi-cs-inactive-delay-ns");
247633a2fde5STudor Ambarus 
2477c2e51ac3SGeert Uytterhoeven 	return 0;
2478c2e51ac3SGeert Uytterhoeven }
2479c2e51ac3SGeert Uytterhoeven 
2480c2e51ac3SGeert Uytterhoeven static struct spi_device *
24818caab75fSGeert Uytterhoeven of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2482c2e51ac3SGeert Uytterhoeven {
2483c2e51ac3SGeert Uytterhoeven 	struct spi_device *spi;
2484c2e51ac3SGeert Uytterhoeven 	int rc;
2485c2e51ac3SGeert Uytterhoeven 
2486c2e51ac3SGeert Uytterhoeven 	/* Alloc an spi_device */
24878caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
2488c2e51ac3SGeert Uytterhoeven 	if (!spi) {
248925c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2490c2e51ac3SGeert Uytterhoeven 		rc = -ENOMEM;
2491c2e51ac3SGeert Uytterhoeven 		goto err_out;
2492c2e51ac3SGeert Uytterhoeven 	}
2493c2e51ac3SGeert Uytterhoeven 
2494c2e51ac3SGeert Uytterhoeven 	/* Select device driver */
2495673aa1edSMiquel Raynal 	rc = of_alias_from_compatible(nc, spi->modalias,
2496c2e51ac3SGeert Uytterhoeven 				      sizeof(spi->modalias));
2497c2e51ac3SGeert Uytterhoeven 	if (rc < 0) {
249825c56c88SRob Herring 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2499c2e51ac3SGeert Uytterhoeven 		goto err_out;
2500c2e51ac3SGeert Uytterhoeven 	}
2501c2e51ac3SGeert Uytterhoeven 
25028caab75fSGeert Uytterhoeven 	rc = of_spi_parse_dt(ctlr, spi, nc);
2503c2e51ac3SGeert Uytterhoeven 	if (rc)
2504c2e51ac3SGeert Uytterhoeven 		goto err_out;
2505c2e51ac3SGeert Uytterhoeven 
2506d57a4282SGrant Likely 	/* Store a pointer to the node in the device structure */
2507d57a4282SGrant Likely 	of_node_get(nc);
2508c7cc588bSAndy Shevchenko 
2509c7cc588bSAndy Shevchenko 	device_set_node(&spi->dev, of_fwnode_handle(nc));
2510d57a4282SGrant Likely 
2511d57a4282SGrant Likely 	/* Register the new device */
2512d57a4282SGrant Likely 	rc = spi_add_device(spi);
2513d57a4282SGrant Likely 	if (rc) {
251425c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
25158324147fSJohan Hovold 		goto err_of_node_put;
2516d57a4282SGrant Likely 	}
2517d57a4282SGrant Likely 
2518aff5e3f8SPantelis Antoniou 	return spi;
2519aff5e3f8SPantelis Antoniou 
25208324147fSJohan Hovold err_of_node_put:
25218324147fSJohan Hovold 	of_node_put(nc);
2522aff5e3f8SPantelis Antoniou err_out:
2523aff5e3f8SPantelis Antoniou 	spi_dev_put(spi);
2524aff5e3f8SPantelis Antoniou 	return ERR_PTR(rc);
2525aff5e3f8SPantelis Antoniou }
2526aff5e3f8SPantelis Antoniou 
2527aff5e3f8SPantelis Antoniou /**
2528aff5e3f8SPantelis Antoniou  * of_register_spi_devices() - Register child devices onto the SPI bus
25298caab75fSGeert Uytterhoeven  * @ctlr:	Pointer to spi_controller device
2530aff5e3f8SPantelis Antoniou  *
25316c364062SGeert Uytterhoeven  * Registers an spi_device for each child node of controller node which
25326c364062SGeert Uytterhoeven  * represents a valid SPI slave.
2533aff5e3f8SPantelis Antoniou  */
25348caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr)
2535aff5e3f8SPantelis Antoniou {
2536aff5e3f8SPantelis Antoniou 	struct spi_device *spi;
2537aff5e3f8SPantelis Antoniou 	struct device_node *nc;
2538aff5e3f8SPantelis Antoniou 
25398caab75fSGeert Uytterhoeven 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2540bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2541bd6c1644SGeert Uytterhoeven 			continue;
25428caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, nc);
2543e0af98a7SRalf Ramsauer 		if (IS_ERR(spi)) {
25448caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
254525c56c88SRob Herring 				 "Failed to create SPI device for %pOF\n", nc);
2546e0af98a7SRalf Ramsauer 			of_node_clear_flag(nc, OF_POPULATED);
2547e0af98a7SRalf Ramsauer 		}
2548d57a4282SGrant Likely 	}
2549d57a4282SGrant Likely }
2550d57a4282SGrant Likely #else
25518caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr) { }
2552d57a4282SGrant Likely #endif
2553d57a4282SGrant Likely 
25540c79378cSSebastian Reichel /**
25550c79378cSSebastian Reichel  * spi_new_ancillary_device() - Register ancillary SPI device
25560c79378cSSebastian Reichel  * @spi:         Pointer to the main SPI device registering the ancillary device
25570c79378cSSebastian Reichel  * @chip_select: Chip Select of the ancillary device
25580c79378cSSebastian Reichel  *
25590c79378cSSebastian Reichel  * Register an ancillary SPI device; for example some chips have a chip-select
25600c79378cSSebastian Reichel  * for normal device usage and another one for setup/firmware upload.
25610c79378cSSebastian Reichel  *
25620c79378cSSebastian Reichel  * This may only be called from main SPI device's probe routine.
25630c79378cSSebastian Reichel  *
25640c79378cSSebastian Reichel  * Return: 0 on success; negative errno on failure
25650c79378cSSebastian Reichel  */
25660c79378cSSebastian Reichel struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
25670c79378cSSebastian Reichel 					     u8 chip_select)
25680c79378cSSebastian Reichel {
25697b5c6a54SAndy Shevchenko 	struct spi_controller *ctlr = spi->controller;
25700c79378cSSebastian Reichel 	struct spi_device *ancillary;
25710c79378cSSebastian Reichel 	int rc = 0;
25720c79378cSSebastian Reichel 
25730c79378cSSebastian Reichel 	/* Alloc an spi_device */
25747b5c6a54SAndy Shevchenko 	ancillary = spi_alloc_device(ctlr);
25750c79378cSSebastian Reichel 	if (!ancillary) {
25760c79378cSSebastian Reichel 		rc = -ENOMEM;
25770c79378cSSebastian Reichel 		goto err_out;
25780c79378cSSebastian Reichel 	}
25790c79378cSSebastian Reichel 
258051e99de5SWolfram Sang 	strscpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
25810c79378cSSebastian Reichel 
25820c79378cSSebastian Reichel 	/* Use provided chip-select for ancillary device */
25835ee91605SAndy Shevchenko 	spi_set_all_cs_unused(ancillary);
2584303feb3cSAmit Kumar Mahapatra 	spi_set_chipselect(ancillary, 0, chip_select);
25850c79378cSSebastian Reichel 
25860c79378cSSebastian Reichel 	/* Take over SPI mode/speed from SPI main device */
25870c79378cSSebastian Reichel 	ancillary->max_speed_hz = spi->max_speed_hz;
2588b01d5506SColin Ian King 	ancillary->mode = spi->mode;
25894d8ff6b0SAmit Kumar Mahapatra 	/*
25904d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[i] gives the corresponding physical CS for logical CS i
25914d8ff6b0SAmit Kumar Mahapatra 	 * logical CS number is represented by setting the ith bit in spi->cs_index_mask
25924d8ff6b0SAmit Kumar Mahapatra 	 * So, for example, if spi->cs_index_mask = 0x01 then logical CS number is 0 and
25934d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[0] will give the physical CS.
25944d8ff6b0SAmit Kumar Mahapatra 	 * By default spi->chip_select[0] will hold the physical CS number so, set
25954d8ff6b0SAmit Kumar Mahapatra 	 * spi->cs_index_mask as 0x01.
25964d8ff6b0SAmit Kumar Mahapatra 	 */
25974d8ff6b0SAmit Kumar Mahapatra 	ancillary->cs_index_mask = 0x01;
25980c79378cSSebastian Reichel 
25997b5c6a54SAndy Shevchenko 	WARN_ON(!mutex_is_locked(&ctlr->add_lock));
26007b5c6a54SAndy Shevchenko 
26010c79378cSSebastian Reichel 	/* Register the new device */
26027b5c6a54SAndy Shevchenko 	rc = __spi_add_device(ancillary);
26030c79378cSSebastian Reichel 	if (rc) {
26040c79378cSSebastian Reichel 		dev_err(&spi->dev, "failed to register ancillary device\n");
26050c79378cSSebastian Reichel 		goto err_out;
26060c79378cSSebastian Reichel 	}
26070c79378cSSebastian Reichel 
26080c79378cSSebastian Reichel 	return ancillary;
26090c79378cSSebastian Reichel 
26100c79378cSSebastian Reichel err_out:
26110c79378cSSebastian Reichel 	spi_dev_put(ancillary);
26120c79378cSSebastian Reichel 	return ERR_PTR(rc);
26130c79378cSSebastian Reichel }
26140c79378cSSebastian Reichel EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
26150c79378cSSebastian Reichel 
261664bee4d2SMika Westerberg #ifdef CONFIG_ACPI
26174c3c5954SArd Biesheuvel struct acpi_spi_lookup {
26184c3c5954SArd Biesheuvel 	struct spi_controller 	*ctlr;
26194c3c5954SArd Biesheuvel 	u32			max_speed_hz;
26204c3c5954SArd Biesheuvel 	u32			mode;
26214c3c5954SArd Biesheuvel 	int			irq;
26224c3c5954SArd Biesheuvel 	u8			bits_per_word;
26234c3c5954SArd Biesheuvel 	u8			chip_select;
262487e59b36SStefan Binding 	int			n;
262587e59b36SStefan Binding 	int			index;
26264c3c5954SArd Biesheuvel };
26274c3c5954SArd Biesheuvel 
2628e612af7aSStefan Binding static int acpi_spi_count(struct acpi_resource *ares, void *data)
2629e612af7aSStefan Binding {
2630e612af7aSStefan Binding 	struct acpi_resource_spi_serialbus *sb;
2631e612af7aSStefan Binding 	int *count = data;
2632e612af7aSStefan Binding 
2633e612af7aSStefan Binding 	if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
2634e612af7aSStefan Binding 		return 1;
2635e612af7aSStefan Binding 
2636e612af7aSStefan Binding 	sb = &ares->data.spi_serial_bus;
2637e612af7aSStefan Binding 	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
2638e612af7aSStefan Binding 		return 1;
2639e612af7aSStefan Binding 
2640e612af7aSStefan Binding 	*count = *count + 1;
2641e612af7aSStefan Binding 
2642e612af7aSStefan Binding 	return 1;
2643e612af7aSStefan Binding }
2644e612af7aSStefan Binding 
2645e612af7aSStefan Binding /**
2646e612af7aSStefan Binding  * acpi_spi_count_resources - Count the number of SpiSerialBus resources
2647e612af7aSStefan Binding  * @adev:	ACPI device
2648e612af7aSStefan Binding  *
2649702ca026SAndy Shevchenko  * Return: the number of SpiSerialBus resources in the ACPI-device's
2650e612af7aSStefan Binding  * resource-list; or a negative error code.
2651e612af7aSStefan Binding  */
2652e612af7aSStefan Binding int acpi_spi_count_resources(struct acpi_device *adev)
2653e612af7aSStefan Binding {
2654e612af7aSStefan Binding 	LIST_HEAD(r);
2655e612af7aSStefan Binding 	int count = 0;
2656e612af7aSStefan Binding 	int ret;
2657e612af7aSStefan Binding 
2658e612af7aSStefan Binding 	ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
2659e612af7aSStefan Binding 	if (ret < 0)
2660e612af7aSStefan Binding 		return ret;
2661e612af7aSStefan Binding 
2662e612af7aSStefan Binding 	acpi_dev_free_resource_list(&r);
2663e612af7aSStefan Binding 
2664e612af7aSStefan Binding 	return count;
2665e612af7aSStefan Binding }
2666e612af7aSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
2667e612af7aSStefan Binding 
26684c3c5954SArd Biesheuvel static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
26694c3c5954SArd Biesheuvel 					    struct acpi_spi_lookup *lookup)
26708a2e487eSLukas Wunner {
26718a2e487eSLukas Wunner 	const union acpi_object *obj;
26728a2e487eSLukas Wunner 
26738a2e487eSLukas Wunner 	if (!x86_apple_machine)
26748a2e487eSLukas Wunner 		return;
26758a2e487eSLukas Wunner 
26768a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
26778a2e487eSLukas Wunner 	    && obj->buffer.length >= 4)
26784c3c5954SArd Biesheuvel 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
26798a2e487eSLukas Wunner 
26808a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
26818a2e487eSLukas Wunner 	    && obj->buffer.length == 8)
26824c3c5954SArd Biesheuvel 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
26838a2e487eSLukas Wunner 
26848a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
26858a2e487eSLukas Wunner 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
26864c3c5954SArd Biesheuvel 		lookup->mode |= SPI_LSB_FIRST;
26878a2e487eSLukas Wunner 
26888a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
26898a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
26904c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPOL;
26918a2e487eSLukas Wunner 
26928a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
26938a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
26944c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPHA;
26958a2e487eSLukas Wunner }
26968a2e487eSLukas Wunner 
269764bee4d2SMika Westerberg static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
269864bee4d2SMika Westerberg {
26994c3c5954SArd Biesheuvel 	struct acpi_spi_lookup *lookup = data;
27004c3c5954SArd Biesheuvel 	struct spi_controller *ctlr = lookup->ctlr;
270164bee4d2SMika Westerberg 
270264bee4d2SMika Westerberg 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
270364bee4d2SMika Westerberg 		struct acpi_resource_spi_serialbus *sb;
27044c3c5954SArd Biesheuvel 		acpi_handle parent_handle;
27054c3c5954SArd Biesheuvel 		acpi_status status;
270664bee4d2SMika Westerberg 
270764bee4d2SMika Westerberg 		sb = &ares->data.spi_serial_bus;
270864bee4d2SMika Westerberg 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
27094c3c5954SArd Biesheuvel 
271087e59b36SStefan Binding 			if (lookup->index != -1 && lookup->n++ != lookup->index)
271187e59b36SStefan Binding 				return 1;
271287e59b36SStefan Binding 
27134c3c5954SArd Biesheuvel 			status = acpi_get_handle(NULL,
27144c3c5954SArd Biesheuvel 						 sb->resource_source.string_ptr,
27154c3c5954SArd Biesheuvel 						 &parent_handle);
27164c3c5954SArd Biesheuvel 
271787e59b36SStefan Binding 			if (ACPI_FAILURE(status))
27184c3c5954SArd Biesheuvel 				return -ENODEV;
27194c3c5954SArd Biesheuvel 
272087e59b36SStefan Binding 			if (ctlr) {
272187e59b36SStefan Binding 				if (ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
272287e59b36SStefan Binding 					return -ENODEV;
272387e59b36SStefan Binding 			} else {
272487e59b36SStefan Binding 				struct acpi_device *adev;
272587e59b36SStefan Binding 
2726ac2a3feeSRafael J. Wysocki 				adev = acpi_fetch_acpi_dev(parent_handle);
2727ac2a3feeSRafael J. Wysocki 				if (!adev)
272887e59b36SStefan Binding 					return -ENODEV;
272987e59b36SStefan Binding 
273087e59b36SStefan Binding 				ctlr = acpi_spi_find_controller_by_adev(adev);
273187e59b36SStefan Binding 				if (!ctlr)
27329c22ec4aSAndy Shevchenko 					return -EPROBE_DEFER;
273387e59b36SStefan Binding 
273487e59b36SStefan Binding 				lookup->ctlr = ctlr;
273587e59b36SStefan Binding 			}
273687e59b36SStefan Binding 
2737a0a90718SMika Westerberg 			/*
2738a0a90718SMika Westerberg 			 * ACPI DeviceSelection numbering is handled by the
2739a0a90718SMika Westerberg 			 * host controller driver in Windows and can vary
2740a0a90718SMika Westerberg 			 * from driver to driver. In Linux we always expect
2741a0a90718SMika Westerberg 			 * 0 .. max - 1 so we need to ask the driver to
2742a0a90718SMika Westerberg 			 * translate between the two schemes.
2743a0a90718SMika Westerberg 			 */
27448caab75fSGeert Uytterhoeven 			if (ctlr->fw_translate_cs) {
27458caab75fSGeert Uytterhoeven 				int cs = ctlr->fw_translate_cs(ctlr,
2746a0a90718SMika Westerberg 						sb->device_selection);
2747a0a90718SMika Westerberg 				if (cs < 0)
2748a0a90718SMika Westerberg 					return cs;
27494c3c5954SArd Biesheuvel 				lookup->chip_select = cs;
2750a0a90718SMika Westerberg 			} else {
27514c3c5954SArd Biesheuvel 				lookup->chip_select = sb->device_selection;
2752a0a90718SMika Westerberg 			}
2753a0a90718SMika Westerberg 
27544c3c5954SArd Biesheuvel 			lookup->max_speed_hz = sb->connection_speed;
27550dadde34SAndy Shevchenko 			lookup->bits_per_word = sb->data_bit_length;
275664bee4d2SMika Westerberg 
275764bee4d2SMika Westerberg 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
27584c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPHA;
275964bee4d2SMika Westerberg 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
27604c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPOL;
276164bee4d2SMika Westerberg 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
27624c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CS_HIGH;
276364bee4d2SMika Westerberg 		}
27644c3c5954SArd Biesheuvel 	} else if (lookup->irq < 0) {
276564bee4d2SMika Westerberg 		struct resource r;
276664bee4d2SMika Westerberg 
276764bee4d2SMika Westerberg 		if (acpi_dev_resource_interrupt(ares, 0, &r))
27684c3c5954SArd Biesheuvel 			lookup->irq = r.start;
276964bee4d2SMika Westerberg 	}
277064bee4d2SMika Westerberg 
277164bee4d2SMika Westerberg 	/* Always tell the ACPI core to skip this resource */
277264bee4d2SMika Westerberg 	return 1;
277364bee4d2SMika Westerberg }
277464bee4d2SMika Westerberg 
2775000bee0eSStefan Binding /**
2776000bee0eSStefan Binding  * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
2777000bee0eSStefan Binding  * @ctlr: controller to which the spi device belongs
2778000bee0eSStefan Binding  * @adev: ACPI Device for the spi device
277987e59b36SStefan Binding  * @index: Index of the spi resource inside the ACPI Node
2780000bee0eSStefan Binding  *
2781702ca026SAndy Shevchenko  * This should be used to allocate a new SPI device from and ACPI Device node.
2782702ca026SAndy Shevchenko  * The caller is responsible for calling spi_add_device to register the SPI device.
2783000bee0eSStefan Binding  *
2784702ca026SAndy Shevchenko  * If ctlr is set to NULL, the Controller for the SPI device will be looked up
278587e59b36SStefan Binding  * using the resource.
278687e59b36SStefan Binding  * If index is set to -1, index is not used.
278787e59b36SStefan Binding  * Note: If index is -1, ctlr must be set.
278887e59b36SStefan Binding  *
2789000bee0eSStefan Binding  * Return: a pointer to the new device, or ERR_PTR on error.
2790000bee0eSStefan Binding  */
2791000bee0eSStefan Binding struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
279287e59b36SStefan Binding 					 struct acpi_device *adev,
279387e59b36SStefan Binding 					 int index)
279464bee4d2SMika Westerberg {
27954c3c5954SArd Biesheuvel 	acpi_handle parent_handle = NULL;
279664bee4d2SMika Westerberg 	struct list_head resource_list;
2797b28944c6SArd Biesheuvel 	struct acpi_spi_lookup lookup = {};
279864bee4d2SMika Westerberg 	struct spi_device *spi;
279964bee4d2SMika Westerberg 	int ret;
280064bee4d2SMika Westerberg 
280187e59b36SStefan Binding 	if (!ctlr && index == -1)
280287e59b36SStefan Binding 		return ERR_PTR(-EINVAL);
280387e59b36SStefan Binding 
28044c3c5954SArd Biesheuvel 	lookup.ctlr		= ctlr;
28054c3c5954SArd Biesheuvel 	lookup.irq		= -1;
280687e59b36SStefan Binding 	lookup.index		= index;
280787e59b36SStefan Binding 	lookup.n		= 0;
28084c3c5954SArd Biesheuvel 
28094c3c5954SArd Biesheuvel 	INIT_LIST_HEAD(&resource_list);
28104c3c5954SArd Biesheuvel 	ret = acpi_dev_get_resources(adev, &resource_list,
28114c3c5954SArd Biesheuvel 				     acpi_spi_add_resource, &lookup);
28124c3c5954SArd Biesheuvel 	acpi_dev_free_resource_list(&resource_list);
28134c3c5954SArd Biesheuvel 
28144c3c5954SArd Biesheuvel 	if (ret < 0)
281595c8222fSDavid Jander 		/* Found SPI in _CRS but it points to another controller */
2816b6747f4fSAndy Shevchenko 		return ERR_PTR(ret);
28174c3c5954SArd Biesheuvel 
28184c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz &&
281910e92724SBjorn Helgaas 	    ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
282087e59b36SStefan Binding 	    ACPI_HANDLE(lookup.ctlr->dev.parent) == parent_handle) {
28214c3c5954SArd Biesheuvel 		/* Apple does not use _CRS but nested devices for SPI slaves */
28224c3c5954SArd Biesheuvel 		acpi_spi_parse_apple_properties(adev, &lookup);
28234c3c5954SArd Biesheuvel 	}
28244c3c5954SArd Biesheuvel 
28254c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz)
2826000bee0eSStefan Binding 		return ERR_PTR(-ENODEV);
28274c3c5954SArd Biesheuvel 
282887e59b36SStefan Binding 	spi = spi_alloc_device(lookup.ctlr);
282964bee4d2SMika Westerberg 	if (!spi) {
283087e59b36SStefan Binding 		dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
283164bee4d2SMika Westerberg 			dev_name(&adev->dev));
2832000bee0eSStefan Binding 		return ERR_PTR(-ENOMEM);
283364bee4d2SMika Westerberg 	}
283464bee4d2SMika Westerberg 
28355ee91605SAndy Shevchenko 	spi_set_all_cs_unused(spi);
28365ee91605SAndy Shevchenko 	spi_set_chipselect(spi, 0, lookup.chip_select);
28374d8ff6b0SAmit Kumar Mahapatra 
28387b199811SRafael J. Wysocki 	ACPI_COMPANION_SET(&spi->dev, adev);
28394c3c5954SArd Biesheuvel 	spi->max_speed_hz	= lookup.max_speed_hz;
2840ea235786SJohn Garry 	spi->mode		|= lookup.mode;
28414c3c5954SArd Biesheuvel 	spi->irq		= lookup.irq;
28424c3c5954SArd Biesheuvel 	spi->bits_per_word	= lookup.bits_per_word;
28434d8ff6b0SAmit Kumar Mahapatra 	/*
28444d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[i] gives the corresponding physical CS for logical CS i
28454d8ff6b0SAmit Kumar Mahapatra 	 * logical CS number is represented by setting the ith bit in spi->cs_index_mask
28464d8ff6b0SAmit Kumar Mahapatra 	 * So, for example, if spi->cs_index_mask = 0x01 then logical CS number is 0 and
28474d8ff6b0SAmit Kumar Mahapatra 	 * spi->chip_select[0] will give the physical CS.
28484d8ff6b0SAmit Kumar Mahapatra 	 * By default spi->chip_select[0] will hold the physical CS number so, set
28494d8ff6b0SAmit Kumar Mahapatra 	 * spi->cs_index_mask as 0x01.
28504d8ff6b0SAmit Kumar Mahapatra 	 */
28514d8ff6b0SAmit Kumar Mahapatra 	spi->cs_index_mask	= 0x01;
285264bee4d2SMika Westerberg 
2853000bee0eSStefan Binding 	return spi;
2854000bee0eSStefan Binding }
2855000bee0eSStefan Binding EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
2856000bee0eSStefan Binding 
2857000bee0eSStefan Binding static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2858000bee0eSStefan Binding 					    struct acpi_device *adev)
2859000bee0eSStefan Binding {
2860000bee0eSStefan Binding 	struct spi_device *spi;
2861000bee0eSStefan Binding 
2862000bee0eSStefan Binding 	if (acpi_bus_get_status(adev) || !adev->status.present ||
2863000bee0eSStefan Binding 	    acpi_device_enumerated(adev))
2864000bee0eSStefan Binding 		return AE_OK;
2865000bee0eSStefan Binding 
286687e59b36SStefan Binding 	spi = acpi_spi_device_alloc(ctlr, adev, -1);
2867000bee0eSStefan Binding 	if (IS_ERR(spi)) {
2868000bee0eSStefan Binding 		if (PTR_ERR(spi) == -ENOMEM)
2869000bee0eSStefan Binding 			return AE_NO_MEMORY;
2870000bee0eSStefan Binding 		else
2871000bee0eSStefan Binding 			return AE_OK;
2872000bee0eSStefan Binding 	}
2873000bee0eSStefan Binding 
28740c6543f6SDan O'Donovan 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
28750c6543f6SDan O'Donovan 			  sizeof(spi->modalias));
28760c6543f6SDan O'Donovan 
287733ada67dSChristophe RICARD 	if (spi->irq < 0)
287833ada67dSChristophe RICARD 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
287933ada67dSChristophe RICARD 
28807f24467fSOctavian Purdila 	acpi_device_set_enumerated(adev);
28817f24467fSOctavian Purdila 
288233cf00e5SMika Westerberg 	adev->power.flags.ignore_parent = true;
288364bee4d2SMika Westerberg 	if (spi_add_device(spi)) {
288433cf00e5SMika Westerberg 		adev->power.flags.ignore_parent = false;
28858caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
288664bee4d2SMika Westerberg 			dev_name(&adev->dev));
288764bee4d2SMika Westerberg 		spi_dev_put(spi);
288864bee4d2SMika Westerberg 	}
288964bee4d2SMika Westerberg 
289064bee4d2SMika Westerberg 	return AE_OK;
289164bee4d2SMika Westerberg }
289264bee4d2SMika Westerberg 
28937f24467fSOctavian Purdila static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
28947f24467fSOctavian Purdila 				       void *data, void **return_value)
28957f24467fSOctavian Purdila {
28967030c428SRafael J. Wysocki 	struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
28978caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = data;
28987f24467fSOctavian Purdila 
28997030c428SRafael J. Wysocki 	if (!adev)
29007f24467fSOctavian Purdila 		return AE_OK;
29017f24467fSOctavian Purdila 
29028caab75fSGeert Uytterhoeven 	return acpi_register_spi_device(ctlr, adev);
29037f24467fSOctavian Purdila }
29047f24467fSOctavian Purdila 
29054c3c5954SArd Biesheuvel #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
29064c3c5954SArd Biesheuvel 
29078caab75fSGeert Uytterhoeven static void acpi_register_spi_devices(struct spi_controller *ctlr)
290864bee4d2SMika Westerberg {
290964bee4d2SMika Westerberg 	acpi_status status;
291064bee4d2SMika Westerberg 	acpi_handle handle;
291164bee4d2SMika Westerberg 
29128caab75fSGeert Uytterhoeven 	handle = ACPI_HANDLE(ctlr->dev.parent);
291364bee4d2SMika Westerberg 	if (!handle)
291464bee4d2SMika Westerberg 		return;
291564bee4d2SMika Westerberg 
29164c3c5954SArd Biesheuvel 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
29174c3c5954SArd Biesheuvel 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
29188caab75fSGeert Uytterhoeven 				     acpi_spi_add_device, NULL, ctlr, NULL);
291964bee4d2SMika Westerberg 	if (ACPI_FAILURE(status))
29208caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
292164bee4d2SMika Westerberg }
292264bee4d2SMika Westerberg #else
29238caab75fSGeert Uytterhoeven static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
292464bee4d2SMika Westerberg #endif /* CONFIG_ACPI */
292564bee4d2SMika Westerberg 
29268caab75fSGeert Uytterhoeven static void spi_controller_release(struct device *dev)
29278ae12a0dSDavid Brownell {
29288caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
29298ae12a0dSDavid Brownell 
29308caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
29318caab75fSGeert Uytterhoeven 	kfree(ctlr);
29328ae12a0dSDavid Brownell }
29338ae12a0dSDavid Brownell 
29348ae12a0dSDavid Brownell static struct class spi_master_class = {
29358ae12a0dSDavid Brownell 	.name		= "spi_master",
29368caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
2937eca2ebc7SMartin Sperl 	.dev_groups	= spi_master_groups,
29388ae12a0dSDavid Brownell };
29398ae12a0dSDavid Brownell 
29406c364062SGeert Uytterhoeven #ifdef CONFIG_SPI_SLAVE
29416c364062SGeert Uytterhoeven /**
29426c364062SGeert Uytterhoeven  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
29436c364062SGeert Uytterhoeven  *		     controller
29446c364062SGeert Uytterhoeven  * @spi: device used for the current transfer
29456c364062SGeert Uytterhoeven  */
29466c364062SGeert Uytterhoeven int spi_slave_abort(struct spi_device *spi)
29476c364062SGeert Uytterhoeven {
29488caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
29496c364062SGeert Uytterhoeven 
29508caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
29518caab75fSGeert Uytterhoeven 		return ctlr->slave_abort(ctlr);
29526c364062SGeert Uytterhoeven 
29536c364062SGeert Uytterhoeven 	return -ENOTSUPP;
29546c364062SGeert Uytterhoeven }
29556c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_slave_abort);
29566c364062SGeert Uytterhoeven 
2957b8d3b056SYang Yingliang int spi_target_abort(struct spi_device *spi)
2958b8d3b056SYang Yingliang {
2959b8d3b056SYang Yingliang 	struct spi_controller *ctlr = spi->controller;
2960b8d3b056SYang Yingliang 
2961b8d3b056SYang Yingliang 	if (spi_controller_is_target(ctlr) && ctlr->target_abort)
2962b8d3b056SYang Yingliang 		return ctlr->target_abort(ctlr);
2963b8d3b056SYang Yingliang 
2964b8d3b056SYang Yingliang 	return -ENOTSUPP;
2965b8d3b056SYang Yingliang }
2966b8d3b056SYang Yingliang EXPORT_SYMBOL_GPL(spi_target_abort);
2967b8d3b056SYang Yingliang 
2968cc8b4659SGeert Uytterhoeven static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2969cc8b4659SGeert Uytterhoeven 			  char *buf)
29706c364062SGeert Uytterhoeven {
29718caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
29728caab75fSGeert Uytterhoeven 						   dev);
29736c364062SGeert Uytterhoeven 	struct device *child;
29746c364062SGeert Uytterhoeven 
2975c21b0837SAndy Shevchenko 	child = device_find_any_child(&ctlr->dev);
2976f2daa466SAndy Shevchenko 	return sysfs_emit(buf, "%s\n", child ? to_spi_device(child)->modalias : NULL);
29776c364062SGeert Uytterhoeven }
29786c364062SGeert Uytterhoeven 
2979cc8b4659SGeert Uytterhoeven static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2980cc8b4659SGeert Uytterhoeven 			   const char *buf, size_t count)
29816c364062SGeert Uytterhoeven {
29828caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
29838caab75fSGeert Uytterhoeven 						   dev);
29846c364062SGeert Uytterhoeven 	struct spi_device *spi;
29856c364062SGeert Uytterhoeven 	struct device *child;
29866c364062SGeert Uytterhoeven 	char name[32];
29876c364062SGeert Uytterhoeven 	int rc;
29886c364062SGeert Uytterhoeven 
29896c364062SGeert Uytterhoeven 	rc = sscanf(buf, "%31s", name);
29906c364062SGeert Uytterhoeven 	if (rc != 1 || !name[0])
29916c364062SGeert Uytterhoeven 		return -EINVAL;
29926c364062SGeert Uytterhoeven 
2993c21b0837SAndy Shevchenko 	child = device_find_any_child(&ctlr->dev);
29946c364062SGeert Uytterhoeven 	if (child) {
29956c364062SGeert Uytterhoeven 		/* Remove registered slave */
29966c364062SGeert Uytterhoeven 		device_unregister(child);
29976c364062SGeert Uytterhoeven 		put_device(child);
29986c364062SGeert Uytterhoeven 	}
29996c364062SGeert Uytterhoeven 
30006c364062SGeert Uytterhoeven 	if (strcmp(name, "(null)")) {
30016c364062SGeert Uytterhoeven 		/* Register new slave */
30026c364062SGeert Uytterhoeven 		spi = spi_alloc_device(ctlr);
30036c364062SGeert Uytterhoeven 		if (!spi)
30046c364062SGeert Uytterhoeven 			return -ENOMEM;
30056c364062SGeert Uytterhoeven 
300651e99de5SWolfram Sang 		strscpy(spi->modalias, name, sizeof(spi->modalias));
30076c364062SGeert Uytterhoeven 
30086c364062SGeert Uytterhoeven 		rc = spi_add_device(spi);
30096c364062SGeert Uytterhoeven 		if (rc) {
30106c364062SGeert Uytterhoeven 			spi_dev_put(spi);
30116c364062SGeert Uytterhoeven 			return rc;
30126c364062SGeert Uytterhoeven 		}
30136c364062SGeert Uytterhoeven 	}
30146c364062SGeert Uytterhoeven 
30156c364062SGeert Uytterhoeven 	return count;
30166c364062SGeert Uytterhoeven }
30176c364062SGeert Uytterhoeven 
3018cc8b4659SGeert Uytterhoeven static DEVICE_ATTR_RW(slave);
30196c364062SGeert Uytterhoeven 
30206c364062SGeert Uytterhoeven static struct attribute *spi_slave_attrs[] = {
30216c364062SGeert Uytterhoeven 	&dev_attr_slave.attr,
30226c364062SGeert Uytterhoeven 	NULL,
30236c364062SGeert Uytterhoeven };
30246c364062SGeert Uytterhoeven 
30256c364062SGeert Uytterhoeven static const struct attribute_group spi_slave_group = {
30266c364062SGeert Uytterhoeven 	.attrs = spi_slave_attrs,
30276c364062SGeert Uytterhoeven };
30286c364062SGeert Uytterhoeven 
30296c364062SGeert Uytterhoeven static const struct attribute_group *spi_slave_groups[] = {
30308caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
30316c364062SGeert Uytterhoeven 	&spi_slave_group,
30326c364062SGeert Uytterhoeven 	NULL,
30336c364062SGeert Uytterhoeven };
30346c364062SGeert Uytterhoeven 
30356c364062SGeert Uytterhoeven static struct class spi_slave_class = {
30366c364062SGeert Uytterhoeven 	.name		= "spi_slave",
30378caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
30386c364062SGeert Uytterhoeven 	.dev_groups	= spi_slave_groups,
30396c364062SGeert Uytterhoeven };
30406c364062SGeert Uytterhoeven #else
30416c364062SGeert Uytterhoeven extern struct class spi_slave_class;	/* dummy */
30426c364062SGeert Uytterhoeven #endif
30438ae12a0dSDavid Brownell 
30448ae12a0dSDavid Brownell /**
30456c364062SGeert Uytterhoeven  * __spi_alloc_controller - allocate an SPI master or slave controller
30468ae12a0dSDavid Brownell  * @dev: the controller, possibly using the platform_bus
304733e34dc6SDavid Brownell  * @size: how much zeroed driver-private data to allocate; the pointer to this
3048229e6af1SLukas Wunner  *	memory is in the driver_data field of the returned device, accessible
3049229e6af1SLukas Wunner  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
3050229e6af1SLukas Wunner  *	drivers granting DMA access to portions of their private data need to
3051229e6af1SLukas Wunner  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
30526c364062SGeert Uytterhoeven  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
30536c364062SGeert Uytterhoeven  *	slave (true) controller
305433e34dc6SDavid Brownell  * Context: can sleep
30558ae12a0dSDavid Brownell  *
30566c364062SGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
30578ae12a0dSDavid Brownell  * only ones directly touching chip registers.  It's how they allocate
30588caab75fSGeert Uytterhoeven  * an spi_controller structure, prior to calling spi_register_controller().
30598ae12a0dSDavid Brownell  *
306097d56dc6SJavier Martinez Canillas  * This must be called from context that can sleep.
30618ae12a0dSDavid Brownell  *
30626c364062SGeert Uytterhoeven  * The caller is responsible for assigning the bus number and initializing the
30638caab75fSGeert Uytterhoeven  * controller's methods before calling spi_register_controller(); and (after
30648caab75fSGeert Uytterhoeven  * errors adding the device) calling spi_controller_put() to prevent a memory
30658caab75fSGeert Uytterhoeven  * leak.
306697d56dc6SJavier Martinez Canillas  *
30676c364062SGeert Uytterhoeven  * Return: the SPI controller structure on success, else NULL.
30688ae12a0dSDavid Brownell  */
30698caab75fSGeert Uytterhoeven struct spi_controller *__spi_alloc_controller(struct device *dev,
30706c364062SGeert Uytterhoeven 					      unsigned int size, bool slave)
30718ae12a0dSDavid Brownell {
30728caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr;
3073229e6af1SLukas Wunner 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
30748ae12a0dSDavid Brownell 
30750c868461SDavid Brownell 	if (!dev)
30760c868461SDavid Brownell 		return NULL;
30770c868461SDavid Brownell 
3078229e6af1SLukas Wunner 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
30798caab75fSGeert Uytterhoeven 	if (!ctlr)
30808ae12a0dSDavid Brownell 		return NULL;
30818ae12a0dSDavid Brownell 
30828caab75fSGeert Uytterhoeven 	device_initialize(&ctlr->dev);
308316a8e2fbSUwe Kleine-König 	INIT_LIST_HEAD(&ctlr->queue);
308416a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->queue_lock);
308516a8e2fbSUwe Kleine-König 	spin_lock_init(&ctlr->bus_lock_spinlock);
308616a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->bus_lock_mutex);
308716a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->io_mutex);
308816a8e2fbSUwe Kleine-König 	mutex_init(&ctlr->add_lock);
30898caab75fSGeert Uytterhoeven 	ctlr->bus_num = -1;
30908caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = 1;
30918caab75fSGeert Uytterhoeven 	ctlr->slave = slave;
30926c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
30938caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_slave_class;
30946c364062SGeert Uytterhoeven 	else
30958caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_master_class;
30968caab75fSGeert Uytterhoeven 	ctlr->dev.parent = dev;
30978caab75fSGeert Uytterhoeven 	pm_suspend_ignore_children(&ctlr->dev, true);
3098229e6af1SLukas Wunner 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
30998ae12a0dSDavid Brownell 
31008caab75fSGeert Uytterhoeven 	return ctlr;
31018ae12a0dSDavid Brownell }
31026c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(__spi_alloc_controller);
31038ae12a0dSDavid Brownell 
31045e844cc3SLukas Wunner static void devm_spi_release_controller(struct device *dev, void *ctlr)
31055e844cc3SLukas Wunner {
31065e844cc3SLukas Wunner 	spi_controller_put(*(struct spi_controller **)ctlr);
31075e844cc3SLukas Wunner }
31085e844cc3SLukas Wunner 
31095e844cc3SLukas Wunner /**
31105e844cc3SLukas Wunner  * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
31115e844cc3SLukas Wunner  * @dev: physical device of SPI controller
31125e844cc3SLukas Wunner  * @size: how much zeroed driver-private data to allocate
31135e844cc3SLukas Wunner  * @slave: whether to allocate an SPI master (false) or SPI slave (true)
31145e844cc3SLukas Wunner  * Context: can sleep
31155e844cc3SLukas Wunner  *
31165e844cc3SLukas Wunner  * Allocate an SPI controller and automatically release a reference on it
31175e844cc3SLukas Wunner  * when @dev is unbound from its driver.  Drivers are thus relieved from
31185e844cc3SLukas Wunner  * having to call spi_controller_put().
31195e844cc3SLukas Wunner  *
31205e844cc3SLukas Wunner  * The arguments to this function are identical to __spi_alloc_controller().
31215e844cc3SLukas Wunner  *
31225e844cc3SLukas Wunner  * Return: the SPI controller structure on success, else NULL.
31235e844cc3SLukas Wunner  */
31245e844cc3SLukas Wunner struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
31255e844cc3SLukas Wunner 						   unsigned int size,
31265e844cc3SLukas Wunner 						   bool slave)
31275e844cc3SLukas Wunner {
31285e844cc3SLukas Wunner 	struct spi_controller **ptr, *ctlr;
31295e844cc3SLukas Wunner 
31305e844cc3SLukas Wunner 	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
31315e844cc3SLukas Wunner 			   GFP_KERNEL);
31325e844cc3SLukas Wunner 	if (!ptr)
31335e844cc3SLukas Wunner 		return NULL;
31345e844cc3SLukas Wunner 
31355e844cc3SLukas Wunner 	ctlr = __spi_alloc_controller(dev, size, slave);
31365e844cc3SLukas Wunner 	if (ctlr) {
3137794aaf01SWilliam A. Kennington III 		ctlr->devm_allocated = true;
31385e844cc3SLukas Wunner 		*ptr = ctlr;
31395e844cc3SLukas Wunner 		devres_add(dev, ptr);
31405e844cc3SLukas Wunner 	} else {
31415e844cc3SLukas Wunner 		devres_free(ptr);
31425e844cc3SLukas Wunner 	}
31435e844cc3SLukas Wunner 
31445e844cc3SLukas Wunner 	return ctlr;
31455e844cc3SLukas Wunner }
31465e844cc3SLukas Wunner EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
31475e844cc3SLukas Wunner 
3148f3186dd8SLinus Walleij /**
3149f3186dd8SLinus Walleij  * spi_get_gpio_descs() - grab chip select GPIOs for the master
3150f3186dd8SLinus Walleij  * @ctlr: The SPI master to grab GPIO descriptors for
3151f3186dd8SLinus Walleij  */
3152f3186dd8SLinus Walleij static int spi_get_gpio_descs(struct spi_controller *ctlr)
3153f3186dd8SLinus Walleij {
3154f3186dd8SLinus Walleij 	int nb, i;
3155f3186dd8SLinus Walleij 	struct gpio_desc **cs;
3156f3186dd8SLinus Walleij 	struct device *dev = &ctlr->dev;
31577d93aecdSGeert Uytterhoeven 	unsigned long native_cs_mask = 0;
31587d93aecdSGeert Uytterhoeven 	unsigned int num_cs_gpios = 0;
3159f3186dd8SLinus Walleij 
3160f3186dd8SLinus Walleij 	nb = gpiod_count(dev, "cs");
316131ed8ebcSAndy Shevchenko 	if (nb < 0) {
3162f3186dd8SLinus Walleij 		/* No GPIOs at all is fine, else return the error */
316331ed8ebcSAndy Shevchenko 		if (nb == -ENOENT)
3164f3186dd8SLinus Walleij 			return 0;
3165f3186dd8SLinus Walleij 		return nb;
316631ed8ebcSAndy Shevchenko 	}
316731ed8ebcSAndy Shevchenko 
316831ed8ebcSAndy Shevchenko 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
3169f3186dd8SLinus Walleij 
3170f3186dd8SLinus Walleij 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
3171f3186dd8SLinus Walleij 			  GFP_KERNEL);
3172f3186dd8SLinus Walleij 	if (!cs)
3173f3186dd8SLinus Walleij 		return -ENOMEM;
3174f3186dd8SLinus Walleij 	ctlr->cs_gpiods = cs;
3175f3186dd8SLinus Walleij 
3176f3186dd8SLinus Walleij 	for (i = 0; i < nb; i++) {
3177f3186dd8SLinus Walleij 		/*
3178f3186dd8SLinus Walleij 		 * Most chipselects are active low, the inverted
3179f3186dd8SLinus Walleij 		 * semantics are handled by special quirks in gpiolib,
3180f3186dd8SLinus Walleij 		 * so initializing them GPIOD_OUT_LOW here means
3181f3186dd8SLinus Walleij 		 * "unasserted", in most cases this will drive the physical
3182f3186dd8SLinus Walleij 		 * line high.
3183f3186dd8SLinus Walleij 		 */
3184f3186dd8SLinus Walleij 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
3185f3186dd8SLinus Walleij 						      GPIOD_OUT_LOW);
31861723fdecSGeert Uytterhoeven 		if (IS_ERR(cs[i]))
31871723fdecSGeert Uytterhoeven 			return PTR_ERR(cs[i]);
3188f3186dd8SLinus Walleij 
3189f3186dd8SLinus Walleij 		if (cs[i]) {
3190f3186dd8SLinus Walleij 			/*
3191f3186dd8SLinus Walleij 			 * If we find a CS GPIO, name it after the device and
3192f3186dd8SLinus Walleij 			 * chip select line.
3193f3186dd8SLinus Walleij 			 */
3194f3186dd8SLinus Walleij 			char *gpioname;
3195f3186dd8SLinus Walleij 
3196f3186dd8SLinus Walleij 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
3197f3186dd8SLinus Walleij 						  dev_name(dev), i);
3198f3186dd8SLinus Walleij 			if (!gpioname)
3199f3186dd8SLinus Walleij 				return -ENOMEM;
3200f3186dd8SLinus Walleij 			gpiod_set_consumer_name(cs[i], gpioname);
32017d93aecdSGeert Uytterhoeven 			num_cs_gpios++;
32027d93aecdSGeert Uytterhoeven 			continue;
3203f3186dd8SLinus Walleij 		}
32047d93aecdSGeert Uytterhoeven 
32057d93aecdSGeert Uytterhoeven 		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
32067d93aecdSGeert Uytterhoeven 			dev_err(dev, "Invalid native chip select %d\n", i);
32077d93aecdSGeert Uytterhoeven 			return -EINVAL;
32087d93aecdSGeert Uytterhoeven 		}
32097d93aecdSGeert Uytterhoeven 		native_cs_mask |= BIT(i);
32107d93aecdSGeert Uytterhoeven 	}
32117d93aecdSGeert Uytterhoeven 
3212f60d7270SAndy Shevchenko 	ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
3213dbaca8e5SAndy Shevchenko 
321482238d2cSAndy Shevchenko 	if ((ctlr->flags & SPI_CONTROLLER_GPIO_SS) && num_cs_gpios &&
3215dbaca8e5SAndy Shevchenko 	    ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
32167d93aecdSGeert Uytterhoeven 		dev_err(dev, "No unused native chip select available\n");
32177d93aecdSGeert Uytterhoeven 		return -EINVAL;
3218f3186dd8SLinus Walleij 	}
3219f3186dd8SLinus Walleij 
3220f3186dd8SLinus Walleij 	return 0;
3221f3186dd8SLinus Walleij }
3222f3186dd8SLinus Walleij 
3223bdf3a3b5SBoris Brezillon static int spi_controller_check_ops(struct spi_controller *ctlr)
3224bdf3a3b5SBoris Brezillon {
3225bdf3a3b5SBoris Brezillon 	/*
3226b5932f5cSBoris Brezillon 	 * The controller may implement only the high-level SPI-memory like
3227b5932f5cSBoris Brezillon 	 * operations if it does not support regular SPI transfers, and this is
3228b5932f5cSBoris Brezillon 	 * valid use case.
322976a85704SWilliam Zhang 	 * If ->mem_ops or ->mem_ops->exec_op is NULL, we request that at least
323076a85704SWilliam Zhang 	 * one of the ->transfer_xxx() method be implemented.
3231bdf3a3b5SBoris Brezillon 	 */
323220064c47SWilliam Zhang 	if (!ctlr->mem_ops || !ctlr->mem_ops->exec_op) {
323376a85704SWilliam Zhang 		if (!ctlr->transfer && !ctlr->transfer_one &&
3234b5932f5cSBoris Brezillon 		   !ctlr->transfer_one_message) {
3235b5932f5cSBoris Brezillon 			return -EINVAL;
3236b5932f5cSBoris Brezillon 		}
323776a85704SWilliam Zhang 	}
3238bdf3a3b5SBoris Brezillon 
3239bdf3a3b5SBoris Brezillon 	return 0;
3240bdf3a3b5SBoris Brezillon }
3241bdf3a3b5SBoris Brezillon 
3242440c4733SAndy Shevchenko /* Allocate dynamic bus number using Linux idr */
3243440c4733SAndy Shevchenko static int spi_controller_id_alloc(struct spi_controller *ctlr, int start, int end)
3244440c4733SAndy Shevchenko {
3245440c4733SAndy Shevchenko 	int id;
3246440c4733SAndy Shevchenko 
3247440c4733SAndy Shevchenko 	mutex_lock(&board_lock);
3248440c4733SAndy Shevchenko 	id = idr_alloc(&spi_master_idr, ctlr, start, end, GFP_KERNEL);
3249440c4733SAndy Shevchenko 	mutex_unlock(&board_lock);
3250440c4733SAndy Shevchenko 	if (WARN(id < 0, "couldn't get idr"))
3251440c4733SAndy Shevchenko 		return id == -ENOSPC ? -EBUSY : id;
3252440c4733SAndy Shevchenko 	ctlr->bus_num = id;
3253440c4733SAndy Shevchenko 	return 0;
3254440c4733SAndy Shevchenko }
3255440c4733SAndy Shevchenko 
32568ae12a0dSDavid Brownell /**
32578caab75fSGeert Uytterhoeven  * spi_register_controller - register SPI master or slave controller
32588caab75fSGeert Uytterhoeven  * @ctlr: initialized master, originally from spi_alloc_master() or
32598caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
326033e34dc6SDavid Brownell  * Context: can sleep
32618ae12a0dSDavid Brownell  *
32628caab75fSGeert Uytterhoeven  * SPI controllers connect to their drivers using some non-SPI bus,
32638ae12a0dSDavid Brownell  * such as the platform bus.  The final stage of probe() in that code
32648caab75fSGeert Uytterhoeven  * includes calling spi_register_controller() to hook up to this SPI bus glue.
32658ae12a0dSDavid Brownell  *
32668ae12a0dSDavid Brownell  * SPI controllers use board specific (often SOC specific) bus numbers,
32678ae12a0dSDavid Brownell  * and board-specific addressing for SPI devices combines those numbers
32688ae12a0dSDavid Brownell  * with chip select numbers.  Since SPI does not directly support dynamic
32698ae12a0dSDavid Brownell  * device identification, boards need configuration tables telling which
32708ae12a0dSDavid Brownell  * chip is at which address.
32718ae12a0dSDavid Brownell  *
32728ae12a0dSDavid Brownell  * This must be called from context that can sleep.  It returns zero on
32738caab75fSGeert Uytterhoeven  * success, else a negative error code (dropping the controller's refcount).
32740c868461SDavid Brownell  * After a successful return, the caller is responsible for calling
32758caab75fSGeert Uytterhoeven  * spi_unregister_controller().
327697d56dc6SJavier Martinez Canillas  *
327797d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
32788ae12a0dSDavid Brownell  */
32798caab75fSGeert Uytterhoeven int spi_register_controller(struct spi_controller *ctlr)
32808ae12a0dSDavid Brownell {
32818caab75fSGeert Uytterhoeven 	struct device		*dev = ctlr->dev.parent;
32822b9603a0SFeng Tang 	struct boardinfo	*bi;
3283440c4733SAndy Shevchenko 	int			first_dynamic;
3284b93318a2SSergei Shtylyov 	int			status;
32854d8ff6b0SAmit Kumar Mahapatra 	int			idx;
32868ae12a0dSDavid Brownell 
32870c868461SDavid Brownell 	if (!dev)
32880c868461SDavid Brownell 		return -ENODEV;
32890c868461SDavid Brownell 
3290bdf3a3b5SBoris Brezillon 	/*
3291bdf3a3b5SBoris Brezillon 	 * Make sure all necessary hooks are implemented before registering
3292bdf3a3b5SBoris Brezillon 	 * the SPI controller.
3293bdf3a3b5SBoris Brezillon 	 */
3294bdf3a3b5SBoris Brezillon 	status = spi_controller_check_ops(ctlr);
3295bdf3a3b5SBoris Brezillon 	if (status)
3296bdf3a3b5SBoris Brezillon 		return status;
3297bdf3a3b5SBoris Brezillon 
3298440c4733SAndy Shevchenko 	if (ctlr->bus_num < 0)
3299440c4733SAndy Shevchenko 		ctlr->bus_num = of_alias_get_id(ctlr->dev.of_node, "spi");
330004b2d03aSGeert Uytterhoeven 	if (ctlr->bus_num >= 0) {
330195c8222fSDavid Jander 		/* Devices with a fixed bus num must check-in with the num */
3302440c4733SAndy Shevchenko 		status = spi_controller_id_alloc(ctlr, ctlr->bus_num, ctlr->bus_num + 1);
3303440c4733SAndy Shevchenko 		if (status)
3304440c4733SAndy Shevchenko 			return status;
33059b61e302SSuniel Mahesh 	}
33068caab75fSGeert Uytterhoeven 	if (ctlr->bus_num < 0) {
330742bdd706SLucas Stach 		first_dynamic = of_alias_get_highest_id("spi");
330842bdd706SLucas Stach 		if (first_dynamic < 0)
330942bdd706SLucas Stach 			first_dynamic = 0;
331042bdd706SLucas Stach 		else
331142bdd706SLucas Stach 			first_dynamic++;
331242bdd706SLucas Stach 
3313440c4733SAndy Shevchenko 		status = spi_controller_id_alloc(ctlr, first_dynamic, 0);
3314440c4733SAndy Shevchenko 		if (status)
3315440c4733SAndy Shevchenko 			return status;
33168ae12a0dSDavid Brownell 	}
33178caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
33188caab75fSGeert Uytterhoeven 	init_completion(&ctlr->xfer_completion);
331969fa9590SDavid Jander 	init_completion(&ctlr->cur_msg_completion);
33208caab75fSGeert Uytterhoeven 	if (!ctlr->max_dma_len)
33218caab75fSGeert Uytterhoeven 		ctlr->max_dma_len = INT_MAX;
3322cf32b71eSErnst Schwab 
3323350de7ceSAndy Shevchenko 	/*
3324350de7ceSAndy Shevchenko 	 * Register the device, then userspace will see it.
3325350de7ceSAndy Shevchenko 	 * Registration fails if the bus ID is in use.
33268ae12a0dSDavid Brownell 	 */
33278caab75fSGeert Uytterhoeven 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
33280a919ae4SAndrey Smirnov 
3329f48dc6b9SLinus Walleij 	if (!spi_controller_is_slave(ctlr) && ctlr->use_gpio_descriptors) {
33300a919ae4SAndrey Smirnov 		status = spi_get_gpio_descs(ctlr);
33310a919ae4SAndrey Smirnov 		if (status)
3332f9981d4fSAaro Koskinen 			goto free_bus_id;
33330a919ae4SAndrey Smirnov 		/*
33340a919ae4SAndrey Smirnov 		 * A controller using GPIO descriptors always
33350a919ae4SAndrey Smirnov 		 * supports SPI_CS_HIGH if need be.
33360a919ae4SAndrey Smirnov 		 */
33370a919ae4SAndrey Smirnov 		ctlr->mode_bits |= SPI_CS_HIGH;
33380a919ae4SAndrey Smirnov 	}
33390a919ae4SAndrey Smirnov 
3340f9481b08STudor Ambarus 	/*
3341f9481b08STudor Ambarus 	 * Even if it's just one always-selected device, there must
3342f9481b08STudor Ambarus 	 * be at least one chipselect.
3343f9481b08STudor Ambarus 	 */
3344f9981d4fSAaro Koskinen 	if (!ctlr->num_chipselect) {
3345f9981d4fSAaro Koskinen 		status = -EINVAL;
3346f9981d4fSAaro Koskinen 		goto free_bus_id;
3347f9981d4fSAaro Koskinen 	}
3348f9481b08STudor Ambarus 
334995c8222fSDavid Jander 	/* Setting last_cs to -1 means no chip selected */
33504d8ff6b0SAmit Kumar Mahapatra 	for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
33514d8ff6b0SAmit Kumar Mahapatra 		ctlr->last_cs[idx] = -1;
33526bb477dfSYun Zhou 
33538caab75fSGeert Uytterhoeven 	status = device_add(&ctlr->dev);
3354f9981d4fSAaro Koskinen 	if (status < 0)
3355f9981d4fSAaro Koskinen 		goto free_bus_id;
33569b61e302SSuniel Mahesh 	dev_dbg(dev, "registered %s %s\n",
33578caab75fSGeert Uytterhoeven 			spi_controller_is_slave(ctlr) ? "slave" : "master",
33589b61e302SSuniel Mahesh 			dev_name(&ctlr->dev));
33598ae12a0dSDavid Brownell 
3360b5932f5cSBoris Brezillon 	/*
3361b5932f5cSBoris Brezillon 	 * If we're using a queued driver, start the queue. Note that we don't
3362b5932f5cSBoris Brezillon 	 * need the queueing logic if the driver is only supporting high-level
3363b5932f5cSBoris Brezillon 	 * memory operations.
3364b5932f5cSBoris Brezillon 	 */
3365b5932f5cSBoris Brezillon 	if (ctlr->transfer) {
33668caab75fSGeert Uytterhoeven 		dev_info(dev, "controller is unqueued, this is deprecated\n");
3367b5932f5cSBoris Brezillon 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
33688caab75fSGeert Uytterhoeven 		status = spi_controller_initialize_queue(ctlr);
3369ffbbdd21SLinus Walleij 		if (status) {
33708caab75fSGeert Uytterhoeven 			device_del(&ctlr->dev);
3371f9981d4fSAaro Koskinen 			goto free_bus_id;
3372ffbbdd21SLinus Walleij 		}
3373ffbbdd21SLinus Walleij 	}
337495c8222fSDavid Jander 	/* Add statistics */
33756598b91bSDavid Jander 	ctlr->pcpu_statistics = spi_alloc_pcpu_stats(dev);
33766598b91bSDavid Jander 	if (!ctlr->pcpu_statistics) {
33776598b91bSDavid Jander 		dev_err(dev, "Error allocating per-cpu statistics\n");
3378d52b095bSDan Carpenter 		status = -ENOMEM;
33796598b91bSDavid Jander 		goto destroy_queue;
33806598b91bSDavid Jander 	}
3381ffbbdd21SLinus Walleij 
33822b9603a0SFeng Tang 	mutex_lock(&board_lock);
33838caab75fSGeert Uytterhoeven 	list_add_tail(&ctlr->list, &spi_controller_list);
33842b9603a0SFeng Tang 	list_for_each_entry(bi, &board_list, list)
33858caab75fSGeert Uytterhoeven 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
33862b9603a0SFeng Tang 	mutex_unlock(&board_lock);
33872b9603a0SFeng Tang 
338864bee4d2SMika Westerberg 	/* Register devices from the device tree and ACPI */
33898caab75fSGeert Uytterhoeven 	of_register_spi_devices(ctlr);
33908caab75fSGeert Uytterhoeven 	acpi_register_spi_devices(ctlr);
3391f9981d4fSAaro Koskinen 	return status;
3392f9981d4fSAaro Koskinen 
33936598b91bSDavid Jander destroy_queue:
33946598b91bSDavid Jander 	spi_destroy_queue(ctlr);
3395f9981d4fSAaro Koskinen free_bus_id:
3396f9981d4fSAaro Koskinen 	mutex_lock(&board_lock);
3397f9981d4fSAaro Koskinen 	idr_remove(&spi_master_idr, ctlr->bus_num);
3398f9981d4fSAaro Koskinen 	mutex_unlock(&board_lock);
33998ae12a0dSDavid Brownell 	return status;
34008ae12a0dSDavid Brownell }
34018caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_register_controller);
34028ae12a0dSDavid Brownell 
340343cc5a0aSYang Yingliang static void devm_spi_unregister(struct device *dev, void *res)
3404666d5b4cSMark Brown {
340543cc5a0aSYang Yingliang 	spi_unregister_controller(*(struct spi_controller **)res);
3406666d5b4cSMark Brown }
3407666d5b4cSMark Brown 
3408666d5b4cSMark Brown /**
34098caab75fSGeert Uytterhoeven  * devm_spi_register_controller - register managed SPI master or slave
34108caab75fSGeert Uytterhoeven  *	controller
34118caab75fSGeert Uytterhoeven  * @dev:    device managing SPI controller
34128caab75fSGeert Uytterhoeven  * @ctlr: initialized controller, originally from spi_alloc_master() or
34138caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
3414666d5b4cSMark Brown  * Context: can sleep
3415666d5b4cSMark Brown  *
34168caab75fSGeert Uytterhoeven  * Register a SPI device as with spi_register_controller() which will
341768b892f1SJohan Hovold  * automatically be unregistered and freed.
341897d56dc6SJavier Martinez Canillas  *
341997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3420666d5b4cSMark Brown  */
34218caab75fSGeert Uytterhoeven int devm_spi_register_controller(struct device *dev,
34228caab75fSGeert Uytterhoeven 				 struct spi_controller *ctlr)
3423666d5b4cSMark Brown {
342443cc5a0aSYang Yingliang 	struct spi_controller **ptr;
3425666d5b4cSMark Brown 	int ret;
3426666d5b4cSMark Brown 
342743cc5a0aSYang Yingliang 	ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
342843cc5a0aSYang Yingliang 	if (!ptr)
342943cc5a0aSYang Yingliang 		return -ENOMEM;
343059ebbe40STian Tao 
343143cc5a0aSYang Yingliang 	ret = spi_register_controller(ctlr);
343243cc5a0aSYang Yingliang 	if (!ret) {
343343cc5a0aSYang Yingliang 		*ptr = ctlr;
343443cc5a0aSYang Yingliang 		devres_add(dev, ptr);
343543cc5a0aSYang Yingliang 	} else {
343643cc5a0aSYang Yingliang 		devres_free(ptr);
343743cc5a0aSYang Yingliang 	}
343843cc5a0aSYang Yingliang 
343943cc5a0aSYang Yingliang 	return ret;
3440666d5b4cSMark Brown }
34418caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(devm_spi_register_controller);
3442666d5b4cSMark Brown 
344334860089SDavid Lamparter static int __unregister(struct device *dev, void *null)
34448ae12a0dSDavid Brownell {
34450c868461SDavid Brownell 	spi_unregister_device(to_spi_device(dev));
34468ae12a0dSDavid Brownell 	return 0;
34478ae12a0dSDavid Brownell }
34488ae12a0dSDavid Brownell 
34498ae12a0dSDavid Brownell /**
34508caab75fSGeert Uytterhoeven  * spi_unregister_controller - unregister SPI master or slave controller
34518caab75fSGeert Uytterhoeven  * @ctlr: the controller being unregistered
345233e34dc6SDavid Brownell  * Context: can sleep
34538ae12a0dSDavid Brownell  *
34548caab75fSGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
34558ae12a0dSDavid Brownell  * only ones directly touching chip registers.
34568ae12a0dSDavid Brownell  *
34578ae12a0dSDavid Brownell  * This must be called from context that can sleep.
345868b892f1SJohan Hovold  *
345968b892f1SJohan Hovold  * Note that this function also drops a reference to the controller.
34608ae12a0dSDavid Brownell  */
34618caab75fSGeert Uytterhoeven void spi_unregister_controller(struct spi_controller *ctlr)
34628ae12a0dSDavid Brownell {
34639b61e302SSuniel Mahesh 	struct spi_controller *found;
346467f7b278SJohan Hovold 	int id = ctlr->bus_num;
346589fc9a1aSJeff Garzik 
3466ddf75be4SLukas Wunner 	/* Prevent addition of new devices, unregister existing ones */
3467ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
34686098475dSMark Brown 		mutex_lock(&ctlr->add_lock);
3469ddf75be4SLukas Wunner 
347084855678SLukas Wunner 	device_for_each_child(&ctlr->dev, NULL, __unregister);
347184855678SLukas Wunner 
34729b61e302SSuniel Mahesh 	/* First make sure that this controller was ever added */
34739b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
347467f7b278SJohan Hovold 	found = idr_find(&spi_master_idr, id);
34759b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
34768caab75fSGeert Uytterhoeven 	if (ctlr->queued) {
34778caab75fSGeert Uytterhoeven 		if (spi_destroy_queue(ctlr))
34788caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue remove failed\n");
3479ffbbdd21SLinus Walleij 	}
34802b9603a0SFeng Tang 	mutex_lock(&board_lock);
34818caab75fSGeert Uytterhoeven 	list_del(&ctlr->list);
34822b9603a0SFeng Tang 	mutex_unlock(&board_lock);
34832b9603a0SFeng Tang 
34845e844cc3SLukas Wunner 	device_del(&ctlr->dev);
34855e844cc3SLukas Wunner 
348695c8222fSDavid Jander 	/* Free bus id */
34879b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
3488613bd1eaSJarkko Nikula 	if (found == ctlr)
348967f7b278SJohan Hovold 		idr_remove(&spi_master_idr, id);
34909b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
3491ddf75be4SLukas Wunner 
3492ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
34936098475dSMark Brown 		mutex_unlock(&ctlr->add_lock);
34946c53b45cSMichael Walle 
3495702ca026SAndy Shevchenko 	/*
3496702ca026SAndy Shevchenko 	 * Release the last reference on the controller if its driver
34976c53b45cSMichael Walle 	 * has not yet been converted to devm_spi_alloc_master/slave().
34986c53b45cSMichael Walle 	 */
34996c53b45cSMichael Walle 	if (!ctlr->devm_allocated)
35006c53b45cSMichael Walle 		put_device(&ctlr->dev);
35018ae12a0dSDavid Brownell }
35028caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_controller);
35038ae12a0dSDavid Brownell 
3504bef4a48fSMark Hasemeyer static inline int __spi_check_suspended(const struct spi_controller *ctlr)
3505bef4a48fSMark Hasemeyer {
3506bef4a48fSMark Hasemeyer 	return ctlr->flags & SPI_CONTROLLER_SUSPENDED ? -ESHUTDOWN : 0;
3507bef4a48fSMark Hasemeyer }
3508bef4a48fSMark Hasemeyer 
3509bef4a48fSMark Hasemeyer static inline void __spi_mark_suspended(struct spi_controller *ctlr)
3510bef4a48fSMark Hasemeyer {
3511bef4a48fSMark Hasemeyer 	mutex_lock(&ctlr->bus_lock_mutex);
3512bef4a48fSMark Hasemeyer 	ctlr->flags |= SPI_CONTROLLER_SUSPENDED;
3513bef4a48fSMark Hasemeyer 	mutex_unlock(&ctlr->bus_lock_mutex);
3514bef4a48fSMark Hasemeyer }
3515bef4a48fSMark Hasemeyer 
3516bef4a48fSMark Hasemeyer static inline void __spi_mark_resumed(struct spi_controller *ctlr)
3517bef4a48fSMark Hasemeyer {
3518bef4a48fSMark Hasemeyer 	mutex_lock(&ctlr->bus_lock_mutex);
3519bef4a48fSMark Hasemeyer 	ctlr->flags &= ~SPI_CONTROLLER_SUSPENDED;
3520bef4a48fSMark Hasemeyer 	mutex_unlock(&ctlr->bus_lock_mutex);
3521bef4a48fSMark Hasemeyer }
3522bef4a48fSMark Hasemeyer 
35238caab75fSGeert Uytterhoeven int spi_controller_suspend(struct spi_controller *ctlr)
3524ffbbdd21SLinus Walleij {
3525bef4a48fSMark Hasemeyer 	int ret = 0;
3526ffbbdd21SLinus Walleij 
35278caab75fSGeert Uytterhoeven 	/* Basically no-ops for non-queued controllers */
3528bef4a48fSMark Hasemeyer 	if (ctlr->queued) {
35298caab75fSGeert Uytterhoeven 		ret = spi_stop_queue(ctlr);
3530ffbbdd21SLinus Walleij 		if (ret)
35318caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue stop failed\n");
3532bef4a48fSMark Hasemeyer 	}
3533ffbbdd21SLinus Walleij 
3534bef4a48fSMark Hasemeyer 	__spi_mark_suspended(ctlr);
3535ffbbdd21SLinus Walleij 	return ret;
3536ffbbdd21SLinus Walleij }
35378caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_suspend);
3538ffbbdd21SLinus Walleij 
35398caab75fSGeert Uytterhoeven int spi_controller_resume(struct spi_controller *ctlr)
3540ffbbdd21SLinus Walleij {
3541bef4a48fSMark Hasemeyer 	int ret = 0;
3542ffbbdd21SLinus Walleij 
3543bef4a48fSMark Hasemeyer 	__spi_mark_resumed(ctlr);
3544ffbbdd21SLinus Walleij 
3545bef4a48fSMark Hasemeyer 	if (ctlr->queued) {
35468caab75fSGeert Uytterhoeven 		ret = spi_start_queue(ctlr);
3547ffbbdd21SLinus Walleij 		if (ret)
35488caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue restart failed\n");
3549bef4a48fSMark Hasemeyer 	}
3550ffbbdd21SLinus Walleij 	return ret;
3551ffbbdd21SLinus Walleij }
35528caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_resume);
3553ffbbdd21SLinus Walleij 
35548ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
35558ae12a0dSDavid Brownell 
3556523baf5aSMartin Sperl /* Core methods for spi_message alterations */
3557523baf5aSMartin Sperl 
35588caab75fSGeert Uytterhoeven static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3559523baf5aSMartin Sperl 					    struct spi_message *msg,
3560523baf5aSMartin Sperl 					    void *res)
3561523baf5aSMartin Sperl {
3562523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer = res;
3563523baf5aSMartin Sperl 	size_t i;
3564523baf5aSMartin Sperl 
356595c8222fSDavid Jander 	/* Call extra callback if requested */
3566523baf5aSMartin Sperl 	if (rxfer->release)
35678caab75fSGeert Uytterhoeven 		rxfer->release(ctlr, msg, res);
3568523baf5aSMartin Sperl 
356995c8222fSDavid Jander 	/* Insert replaced transfers back into the message */
3570523baf5aSMartin Sperl 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3571523baf5aSMartin Sperl 
357295c8222fSDavid Jander 	/* Remove the formerly inserted entries */
3573523baf5aSMartin Sperl 	for (i = 0; i < rxfer->inserted; i++)
3574523baf5aSMartin Sperl 		list_del(&rxfer->inserted_transfers[i].transfer_list);
3575523baf5aSMartin Sperl }
3576523baf5aSMartin Sperl 
3577523baf5aSMartin Sperl /**
3578523baf5aSMartin Sperl  * spi_replace_transfers - replace transfers with several transfers
3579523baf5aSMartin Sperl  *                         and register change with spi_message.resources
3580523baf5aSMartin Sperl  * @msg:           the spi_message we work upon
3581523baf5aSMartin Sperl  * @xfer_first:    the first spi_transfer we want to replace
3582523baf5aSMartin Sperl  * @remove:        number of transfers to remove
3583523baf5aSMartin Sperl  * @insert:        the number of transfers we want to insert instead
3584523baf5aSMartin Sperl  * @release:       extra release code necessary in some circumstances
3585523baf5aSMartin Sperl  * @extradatasize: extra data to allocate (with alignment guarantees
3586523baf5aSMartin Sperl  *                 of struct @spi_transfer)
358705885397SMartin Sperl  * @gfp:           gfp flags
3588523baf5aSMartin Sperl  *
3589523baf5aSMartin Sperl  * Returns: pointer to @spi_replaced_transfers,
3590523baf5aSMartin Sperl  *          PTR_ERR(...) in case of errors.
3591523baf5aSMartin Sperl  */
3592da21fde0SUwe Kleine-König static struct spi_replaced_transfers *spi_replace_transfers(
3593523baf5aSMartin Sperl 	struct spi_message *msg,
3594523baf5aSMartin Sperl 	struct spi_transfer *xfer_first,
3595523baf5aSMartin Sperl 	size_t remove,
3596523baf5aSMartin Sperl 	size_t insert,
3597523baf5aSMartin Sperl 	spi_replaced_release_t release,
3598523baf5aSMartin Sperl 	size_t extradatasize,
3599523baf5aSMartin Sperl 	gfp_t gfp)
3600523baf5aSMartin Sperl {
3601523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer;
3602523baf5aSMartin Sperl 	struct spi_transfer *xfer;
3603523baf5aSMartin Sperl 	size_t i;
3604523baf5aSMartin Sperl 
360595c8222fSDavid Jander 	/* Allocate the structure using spi_res */
3606523baf5aSMartin Sperl 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3607aef97522SGustavo A. R. Silva 			      struct_size(rxfer, inserted_transfers, insert)
3608523baf5aSMartin Sperl 			      + extradatasize,
3609523baf5aSMartin Sperl 			      gfp);
3610523baf5aSMartin Sperl 	if (!rxfer)
3611523baf5aSMartin Sperl 		return ERR_PTR(-ENOMEM);
3612523baf5aSMartin Sperl 
361395c8222fSDavid Jander 	/* The release code to invoke before running the generic release */
3614523baf5aSMartin Sperl 	rxfer->release = release;
3615523baf5aSMartin Sperl 
361695c8222fSDavid Jander 	/* Assign extradata */
3617523baf5aSMartin Sperl 	if (extradatasize)
3618523baf5aSMartin Sperl 		rxfer->extradata =
3619523baf5aSMartin Sperl 			&rxfer->inserted_transfers[insert];
3620523baf5aSMartin Sperl 
362195c8222fSDavid Jander 	/* Init the replaced_transfers list */
3622523baf5aSMartin Sperl 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3623523baf5aSMartin Sperl 
3624350de7ceSAndy Shevchenko 	/*
3625350de7ceSAndy Shevchenko 	 * Assign the list_entry after which we should reinsert
3626523baf5aSMartin Sperl 	 * the @replaced_transfers - it may be spi_message.messages!
3627523baf5aSMartin Sperl 	 */
3628523baf5aSMartin Sperl 	rxfer->replaced_after = xfer_first->transfer_list.prev;
3629523baf5aSMartin Sperl 
363095c8222fSDavid Jander 	/* Remove the requested number of transfers */
3631523baf5aSMartin Sperl 	for (i = 0; i < remove; i++) {
3632350de7ceSAndy Shevchenko 		/*
3633350de7ceSAndy Shevchenko 		 * If the entry after replaced_after it is msg->transfers
3634523baf5aSMartin Sperl 		 * then we have been requested to remove more transfers
3635350de7ceSAndy Shevchenko 		 * than are in the list.
3636523baf5aSMartin Sperl 		 */
3637523baf5aSMartin Sperl 		if (rxfer->replaced_after->next == &msg->transfers) {
3638523baf5aSMartin Sperl 			dev_err(&msg->spi->dev,
3639523baf5aSMartin Sperl 				"requested to remove more spi_transfers than are available\n");
364095c8222fSDavid Jander 			/* Insert replaced transfers back into the message */
3641523baf5aSMartin Sperl 			list_splice(&rxfer->replaced_transfers,
3642523baf5aSMartin Sperl 				    rxfer->replaced_after);
3643523baf5aSMartin Sperl 
364495c8222fSDavid Jander 			/* Free the spi_replace_transfer structure... */
3645523baf5aSMartin Sperl 			spi_res_free(rxfer);
3646523baf5aSMartin Sperl 
364795c8222fSDavid Jander 			/* ...and return with an error */
3648523baf5aSMartin Sperl 			return ERR_PTR(-EINVAL);
3649523baf5aSMartin Sperl 		}
3650523baf5aSMartin Sperl 
3651350de7ceSAndy Shevchenko 		/*
3652350de7ceSAndy Shevchenko 		 * Remove the entry after replaced_after from list of
3653350de7ceSAndy Shevchenko 		 * transfers and add it to list of replaced_transfers.
3654523baf5aSMartin Sperl 		 */
3655523baf5aSMartin Sperl 		list_move_tail(rxfer->replaced_after->next,
3656523baf5aSMartin Sperl 			       &rxfer->replaced_transfers);
3657523baf5aSMartin Sperl 	}
3658523baf5aSMartin Sperl 
3659350de7ceSAndy Shevchenko 	/*
3660350de7ceSAndy Shevchenko 	 * Create copy of the given xfer with identical settings
3661350de7ceSAndy Shevchenko 	 * based on the first transfer to get removed.
3662523baf5aSMartin Sperl 	 */
3663523baf5aSMartin Sperl 	for (i = 0; i < insert; i++) {
366495c8222fSDavid Jander 		/* We need to run in reverse order */
3665523baf5aSMartin Sperl 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3666523baf5aSMartin Sperl 
366795c8222fSDavid Jander 		/* Copy all spi_transfer data */
3668523baf5aSMartin Sperl 		memcpy(xfer, xfer_first, sizeof(*xfer));
3669523baf5aSMartin Sperl 
367095c8222fSDavid Jander 		/* Add to list */
3671523baf5aSMartin Sperl 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3672523baf5aSMartin Sperl 
367395c8222fSDavid Jander 		/* Clear cs_change and delay for all but the last */
3674523baf5aSMartin Sperl 		if (i) {
3675523baf5aSMartin Sperl 			xfer->cs_change = false;
3676bebcfd27SAlexandru Ardelean 			xfer->delay.value = 0;
3677523baf5aSMartin Sperl 		}
3678523baf5aSMartin Sperl 	}
3679523baf5aSMartin Sperl 
368095c8222fSDavid Jander 	/* Set up inserted... */
3681523baf5aSMartin Sperl 	rxfer->inserted = insert;
3682523baf5aSMartin Sperl 
368395c8222fSDavid Jander 	/* ...and register it with spi_res/spi_message */
3684523baf5aSMartin Sperl 	spi_res_add(msg, rxfer);
3685523baf5aSMartin Sperl 
3686523baf5aSMartin Sperl 	return rxfer;
3687523baf5aSMartin Sperl }
3688523baf5aSMartin Sperl 
36898caab75fSGeert Uytterhoeven static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3690d9f12122SMartin Sperl 					struct spi_message *msg,
3691d9f12122SMartin Sperl 					struct spi_transfer **xferp,
3692c0c0293cSDavid Lechner 					size_t maxsize)
3693d9f12122SMartin Sperl {
3694d9f12122SMartin Sperl 	struct spi_transfer *xfer = *xferp, *xfers;
3695d9f12122SMartin Sperl 	struct spi_replaced_transfers *srt;
3696d9f12122SMartin Sperl 	size_t offset;
3697d9f12122SMartin Sperl 	size_t count, i;
3698d9f12122SMartin Sperl 
369995c8222fSDavid Jander 	/* Calculate how many we have to replace */
3700d9f12122SMartin Sperl 	count = DIV_ROUND_UP(xfer->len, maxsize);
3701d9f12122SMartin Sperl 
370295c8222fSDavid Jander 	/* Create replacement */
3703c0c0293cSDavid Lechner 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, GFP_KERNEL);
3704657d32efSDan Carpenter 	if (IS_ERR(srt))
3705657d32efSDan Carpenter 		return PTR_ERR(srt);
3706d9f12122SMartin Sperl 	xfers = srt->inserted_transfers;
3707d9f12122SMartin Sperl 
3708350de7ceSAndy Shevchenko 	/*
3709350de7ceSAndy Shevchenko 	 * Now handle each of those newly inserted spi_transfers.
3710350de7ceSAndy Shevchenko 	 * Note that the replacements spi_transfers all are preset
3711d9f12122SMartin Sperl 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3712d9f12122SMartin Sperl 	 * are all identical (as well as most others)
3713d9f12122SMartin Sperl 	 * so we just have to fix up len and the pointers.
3714d9f12122SMartin Sperl 	 *
3715350de7ceSAndy Shevchenko 	 * This also includes support for the depreciated
3716350de7ceSAndy Shevchenko 	 * spi_message.is_dma_mapped interface.
3717d9f12122SMartin Sperl 	 */
3718d9f12122SMartin Sperl 
3719350de7ceSAndy Shevchenko 	/*
3720350de7ceSAndy Shevchenko 	 * The first transfer just needs the length modified, so we
3721350de7ceSAndy Shevchenko 	 * run it outside the loop.
3722d9f12122SMartin Sperl 	 */
3723c8dab77aSFabio Estevam 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3724d9f12122SMartin Sperl 
372595c8222fSDavid Jander 	/* All the others need rx_buf/tx_buf also set */
3726d9f12122SMartin Sperl 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3727702ca026SAndy Shevchenko 		/* Update rx_buf, tx_buf and DMA */
3728d9f12122SMartin Sperl 		if (xfers[i].rx_buf)
3729d9f12122SMartin Sperl 			xfers[i].rx_buf += offset;
3730d9f12122SMartin Sperl 		if (xfers[i].rx_dma)
3731d9f12122SMartin Sperl 			xfers[i].rx_dma += offset;
3732d9f12122SMartin Sperl 		if (xfers[i].tx_buf)
3733d9f12122SMartin Sperl 			xfers[i].tx_buf += offset;
3734d9f12122SMartin Sperl 		if (xfers[i].tx_dma)
3735d9f12122SMartin Sperl 			xfers[i].tx_dma += offset;
3736d9f12122SMartin Sperl 
373795c8222fSDavid Jander 		/* Update length */
3738d9f12122SMartin Sperl 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3739d9f12122SMartin Sperl 	}
3740d9f12122SMartin Sperl 
3741350de7ceSAndy Shevchenko 	/*
3742350de7ceSAndy Shevchenko 	 * We set up xferp to the last entry we have inserted,
3743350de7ceSAndy Shevchenko 	 * so that we skip those already split transfers.
3744d9f12122SMartin Sperl 	 */
3745d9f12122SMartin Sperl 	*xferp = &xfers[count - 1];
3746d9f12122SMartin Sperl 
374795c8222fSDavid Jander 	/* Increment statistics counters */
37486598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics,
3749d9f12122SMartin Sperl 				       transfers_split_maxsize);
37506598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics,
3751d9f12122SMartin Sperl 				       transfers_split_maxsize);
3752d9f12122SMartin Sperl 
3753d9f12122SMartin Sperl 	return 0;
3754d9f12122SMartin Sperl }
3755d9f12122SMartin Sperl 
3756d9f12122SMartin Sperl /**
3757ce2424d7SMauro Carvalho Chehab  * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3758d9f12122SMartin Sperl  *                               when an individual transfer exceeds a
3759d9f12122SMartin Sperl  *                               certain size
37608caab75fSGeert Uytterhoeven  * @ctlr:    the @spi_controller for this transfer
37613700ce95SMasanari Iida  * @msg:   the @spi_message to transform
37623700ce95SMasanari Iida  * @maxsize:  the maximum when to apply this
3763d9f12122SMartin Sperl  *
3764fab53feaSDavid Lechner  * This function allocates resources that are automatically freed during the
3765fab53feaSDavid Lechner  * spi message unoptimize phase so this function should only be called from
3766fab53feaSDavid Lechner  * optimize_message callbacks.
3767fab53feaSDavid Lechner  *
3768d9f12122SMartin Sperl  * Return: status of transformation
3769d9f12122SMartin Sperl  */
37708caab75fSGeert Uytterhoeven int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3771d9f12122SMartin Sperl 				struct spi_message *msg,
3772c0c0293cSDavid Lechner 				size_t maxsize)
3773d9f12122SMartin Sperl {
3774d9f12122SMartin Sperl 	struct spi_transfer *xfer;
3775d9f12122SMartin Sperl 	int ret;
3776d9f12122SMartin Sperl 
3777350de7ceSAndy Shevchenko 	/*
3778350de7ceSAndy Shevchenko 	 * Iterate over the transfer_list,
3779d9f12122SMartin Sperl 	 * but note that xfer is advanced to the last transfer inserted
3780d9f12122SMartin Sperl 	 * to avoid checking sizes again unnecessarily (also xfer does
3781350de7ceSAndy Shevchenko 	 * potentially belong to a different list by the time the
3782350de7ceSAndy Shevchenko 	 * replacement has happened).
3783d9f12122SMartin Sperl 	 */
3784d9f12122SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3785d9f12122SMartin Sperl 		if (xfer->len > maxsize) {
37868caab75fSGeert Uytterhoeven 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3787c0c0293cSDavid Lechner 							   maxsize);
3788d9f12122SMartin Sperl 			if (ret)
3789d9f12122SMartin Sperl 				return ret;
3790d9f12122SMartin Sperl 		}
3791d9f12122SMartin Sperl 	}
3792d9f12122SMartin Sperl 
3793d9f12122SMartin Sperl 	return 0;
3794d9f12122SMartin Sperl }
3795d9f12122SMartin Sperl EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
37968ae12a0dSDavid Brownell 
3797027781f3SLeonard Göhrs 
3798027781f3SLeonard Göhrs /**
3799702ca026SAndy Shevchenko  * spi_split_transfers_maxwords - split SPI transfers into multiple transfers
3800027781f3SLeonard Göhrs  *                                when an individual transfer exceeds a
3801027781f3SLeonard Göhrs  *                                certain number of SPI words
3802027781f3SLeonard Göhrs  * @ctlr:     the @spi_controller for this transfer
3803027781f3SLeonard Göhrs  * @msg:      the @spi_message to transform
3804027781f3SLeonard Göhrs  * @maxwords: the number of words to limit each transfer to
3805027781f3SLeonard Göhrs  *
3806fab53feaSDavid Lechner  * This function allocates resources that are automatically freed during the
3807fab53feaSDavid Lechner  * spi message unoptimize phase so this function should only be called from
3808fab53feaSDavid Lechner  * optimize_message callbacks.
3809fab53feaSDavid Lechner  *
3810027781f3SLeonard Göhrs  * Return: status of transformation
3811027781f3SLeonard Göhrs  */
3812027781f3SLeonard Göhrs int spi_split_transfers_maxwords(struct spi_controller *ctlr,
3813027781f3SLeonard Göhrs 				 struct spi_message *msg,
3814c0c0293cSDavid Lechner 				 size_t maxwords)
3815027781f3SLeonard Göhrs {
3816027781f3SLeonard Göhrs 	struct spi_transfer *xfer;
3817027781f3SLeonard Göhrs 
3818027781f3SLeonard Göhrs 	/*
3819027781f3SLeonard Göhrs 	 * Iterate over the transfer_list,
3820027781f3SLeonard Göhrs 	 * but note that xfer is advanced to the last transfer inserted
3821027781f3SLeonard Göhrs 	 * to avoid checking sizes again unnecessarily (also xfer does
3822027781f3SLeonard Göhrs 	 * potentially belong to a different list by the time the
3823027781f3SLeonard Göhrs 	 * replacement has happened).
3824027781f3SLeonard Göhrs 	 */
3825027781f3SLeonard Göhrs 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3826027781f3SLeonard Göhrs 		size_t maxsize;
3827027781f3SLeonard Göhrs 		int ret;
3828027781f3SLeonard Göhrs 
38292b308e71SAndy Shevchenko 		maxsize = maxwords * roundup_pow_of_two(BITS_TO_BYTES(xfer->bits_per_word));
3830027781f3SLeonard Göhrs 		if (xfer->len > maxsize) {
3831027781f3SLeonard Göhrs 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3832c0c0293cSDavid Lechner 							   maxsize);
3833027781f3SLeonard Göhrs 			if (ret)
3834027781f3SLeonard Göhrs 				return ret;
3835027781f3SLeonard Göhrs 		}
3836027781f3SLeonard Göhrs 	}
3837027781f3SLeonard Göhrs 
3838027781f3SLeonard Göhrs 	return 0;
3839027781f3SLeonard Göhrs }
3840027781f3SLeonard Göhrs EXPORT_SYMBOL_GPL(spi_split_transfers_maxwords);
3841027781f3SLeonard Göhrs 
38428ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
38438ae12a0dSDavid Brownell 
3844702ca026SAndy Shevchenko /*
3845702ca026SAndy Shevchenko  * Core methods for SPI controller protocol drivers. Some of the
38467d077197SDavid Brownell  * other core methods are currently defined as inline functions.
38477d077197SDavid Brownell  */
38487d077197SDavid Brownell 
38498caab75fSGeert Uytterhoeven static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
38508caab75fSGeert Uytterhoeven 					u8 bits_per_word)
385163ab645fSStefan Brüns {
38528caab75fSGeert Uytterhoeven 	if (ctlr->bits_per_word_mask) {
385363ab645fSStefan Brüns 		/* Only 32 bits fit in the mask */
385463ab645fSStefan Brüns 		if (bits_per_word > 32)
385563ab645fSStefan Brüns 			return -EINVAL;
38568caab75fSGeert Uytterhoeven 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
385763ab645fSStefan Brüns 			return -EINVAL;
385863ab645fSStefan Brüns 	}
385963ab645fSStefan Brüns 
386063ab645fSStefan Brüns 	return 0;
386163ab645fSStefan Brüns }
386263ab645fSStefan Brüns 
38637d077197SDavid Brownell /**
3864684a4784STudor Ambarus  * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3865684a4784STudor Ambarus  * @spi: the device that requires specific CS timing configuration
3866684a4784STudor Ambarus  *
3867684a4784STudor Ambarus  * Return: zero on success, else a negative error code.
3868684a4784STudor Ambarus  */
3869684a4784STudor Ambarus static int spi_set_cs_timing(struct spi_device *spi)
3870684a4784STudor Ambarus {
3871684a4784STudor Ambarus 	struct device *parent = spi->controller->dev.parent;
3872684a4784STudor Ambarus 	int status = 0;
3873684a4784STudor Ambarus 
3874303feb3cSAmit Kumar Mahapatra 	if (spi->controller->set_cs_timing && !spi_get_csgpiod(spi, 0)) {
3875684a4784STudor Ambarus 		if (spi->controller->auto_runtime_pm) {
3876684a4784STudor Ambarus 			status = pm_runtime_get_sync(parent);
3877684a4784STudor Ambarus 			if (status < 0) {
3878684a4784STudor Ambarus 				pm_runtime_put_noidle(parent);
3879684a4784STudor Ambarus 				dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3880684a4784STudor Ambarus 					status);
3881684a4784STudor Ambarus 				return status;
3882684a4784STudor Ambarus 			}
3883684a4784STudor Ambarus 
3884684a4784STudor Ambarus 			status = spi->controller->set_cs_timing(spi);
3885684a4784STudor Ambarus 			pm_runtime_mark_last_busy(parent);
3886684a4784STudor Ambarus 			pm_runtime_put_autosuspend(parent);
3887684a4784STudor Ambarus 		} else {
3888684a4784STudor Ambarus 			status = spi->controller->set_cs_timing(spi);
3889684a4784STudor Ambarus 		}
3890684a4784STudor Ambarus 	}
3891684a4784STudor Ambarus 	return status;
3892684a4784STudor Ambarus }
3893684a4784STudor Ambarus 
3894684a4784STudor Ambarus /**
38957d077197SDavid Brownell  * spi_setup - setup SPI mode and clock rate
38967d077197SDavid Brownell  * @spi: the device whose settings are being modified
38977d077197SDavid Brownell  * Context: can sleep, and no requests are queued to the device
38987d077197SDavid Brownell  *
38997d077197SDavid Brownell  * SPI protocol drivers may need to update the transfer mode if the
39007d077197SDavid Brownell  * device doesn't work with its default.  They may likewise need
39017d077197SDavid Brownell  * to update clock rates or word sizes from initial values.  This function
39027d077197SDavid Brownell  * changes those settings, and must be called from a context that can sleep.
39037d077197SDavid Brownell  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
39047d077197SDavid Brownell  * effect the next time the device is selected and data is transferred to
3905702ca026SAndy Shevchenko  * or from it.  When this function returns, the SPI device is deselected.
39067d077197SDavid Brownell  *
39077d077197SDavid Brownell  * Note that this call will fail if the protocol driver specifies an option
39087d077197SDavid Brownell  * that the underlying controller or its driver does not support.  For
39097d077197SDavid Brownell  * example, not all hardware supports wire transfers using nine bit words,
39107d077197SDavid Brownell  * LSB-first wire encoding, or active-high chipselects.
391197d56dc6SJavier Martinez Canillas  *
391297d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
39137d077197SDavid Brownell  */
39147d077197SDavid Brownell int spi_setup(struct spi_device *spi)
39157d077197SDavid Brownell {
391683596fbeSGeert Uytterhoeven 	unsigned	bad_bits, ugly_bits;
391773f93db5SPaul Kocialkowski 	int		status = 0;
39187d077197SDavid Brownell 
3919d962608cSDragos Bogdan 	/*
3920350de7ceSAndy Shevchenko 	 * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3921350de7ceSAndy Shevchenko 	 * are set at the same time.
3922f477b7fbSwangyuhang 	 */
3923d962608cSDragos Bogdan 	if ((hweight_long(spi->mode &
3924d962608cSDragos Bogdan 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3925d962608cSDragos Bogdan 	    (hweight_long(spi->mode &
3926d962608cSDragos Bogdan 		(SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3927f477b7fbSwangyuhang 		dev_err(&spi->dev,
3928d962608cSDragos Bogdan 		"setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3929f477b7fbSwangyuhang 		return -EINVAL;
3930f477b7fbSwangyuhang 	}
3931350de7ceSAndy Shevchenko 	/* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
3932f477b7fbSwangyuhang 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
39336b03061fSYogesh Narayan Gaur 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
39346b03061fSYogesh Narayan Gaur 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3935f477b7fbSwangyuhang 		return -EINVAL;
3936350de7ceSAndy Shevchenko 	/*
3937350de7ceSAndy Shevchenko 	 * Help drivers fail *cleanly* when they need options
3938350de7ceSAndy Shevchenko 	 * that aren't supported with their current controller.
3939cbaa62e0SDavid Lechner 	 * SPI_CS_WORD has a fallback software implementation,
3940cbaa62e0SDavid Lechner 	 * so it is ignored here.
3941e7db06b5SDavid Brownell 	 */
3942d962608cSDragos Bogdan 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3943d962608cSDragos Bogdan 				 SPI_NO_TX | SPI_NO_RX);
394483596fbeSGeert Uytterhoeven 	ugly_bits = bad_bits &
39456b03061fSYogesh Narayan Gaur 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
39466b03061fSYogesh Narayan Gaur 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
394783596fbeSGeert Uytterhoeven 	if (ugly_bits) {
394883596fbeSGeert Uytterhoeven 		dev_warn(&spi->dev,
394983596fbeSGeert Uytterhoeven 			 "setup: ignoring unsupported mode bits %x\n",
395083596fbeSGeert Uytterhoeven 			 ugly_bits);
395183596fbeSGeert Uytterhoeven 		spi->mode &= ~ugly_bits;
395283596fbeSGeert Uytterhoeven 		bad_bits &= ~ugly_bits;
395383596fbeSGeert Uytterhoeven 	}
3954e7db06b5SDavid Brownell 	if (bad_bits) {
3955eb288a1fSLinus Walleij 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3956e7db06b5SDavid Brownell 			bad_bits);
3957e7db06b5SDavid Brownell 		return -EINVAL;
3958e7db06b5SDavid Brownell 	}
3959e7db06b5SDavid Brownell 
3960b3fe2e51SPaul Kocialkowski 	if (!spi->bits_per_word) {
39617d077197SDavid Brownell 		spi->bits_per_word = 8;
3962b3fe2e51SPaul Kocialkowski 	} else {
3963b3fe2e51SPaul Kocialkowski 		/*
3964b3fe2e51SPaul Kocialkowski 		 * Some controllers may not support the default 8 bits-per-word
3965b3fe2e51SPaul Kocialkowski 		 * so only perform the check when this is explicitly provided.
3966b3fe2e51SPaul Kocialkowski 		 */
39678caab75fSGeert Uytterhoeven 		status = __spi_validate_bits_per_word(spi->controller,
39688caab75fSGeert Uytterhoeven 						      spi->bits_per_word);
39695ab8d262SAndy Shevchenko 		if (status)
39705ab8d262SAndy Shevchenko 			return status;
3971b3fe2e51SPaul Kocialkowski 	}
397263ab645fSStefan Brüns 
39736820e812STudor Ambarus 	if (spi->controller->max_speed_hz &&
39746820e812STudor Ambarus 	    (!spi->max_speed_hz ||
39756820e812STudor Ambarus 	     spi->max_speed_hz > spi->controller->max_speed_hz))
39768caab75fSGeert Uytterhoeven 		spi->max_speed_hz = spi->controller->max_speed_hz;
3977052eb2d4SAxel Lin 
39784fae3a58SSerge Semin 	mutex_lock(&spi->controller->io_mutex);
39794fae3a58SSerge Semin 
3980c914dbf8SJoe Burmeister 	if (spi->controller->setup) {
39818caab75fSGeert Uytterhoeven 		status = spi->controller->setup(spi);
3982c914dbf8SJoe Burmeister 		if (status) {
3983c914dbf8SJoe Burmeister 			mutex_unlock(&spi->controller->io_mutex);
3984c914dbf8SJoe Burmeister 			dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
3985c914dbf8SJoe Burmeister 				status);
3986c914dbf8SJoe Burmeister 			return status;
3987c914dbf8SJoe Burmeister 		}
3988c914dbf8SJoe Burmeister 	}
39897d077197SDavid Brownell 
3990684a4784STudor Ambarus 	status = spi_set_cs_timing(spi);
3991684a4784STudor Ambarus 	if (status) {
3992684a4784STudor Ambarus 		mutex_unlock(&spi->controller->io_mutex);
3993684a4784STudor Ambarus 		return status;
3994684a4784STudor Ambarus 	}
3995684a4784STudor Ambarus 
3996d948e6caSLuhua Xu 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3997dd769f15SMinghao Chi 		status = pm_runtime_resume_and_get(spi->controller->dev.parent);
3998d948e6caSLuhua Xu 		if (status < 0) {
39994fae3a58SSerge Semin 			mutex_unlock(&spi->controller->io_mutex);
4000d948e6caSLuhua Xu 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
4001d948e6caSLuhua Xu 				status);
4002d948e6caSLuhua Xu 			return status;
4003d948e6caSLuhua Xu 		}
400457a94607STony Lindgren 
400557a94607STony Lindgren 		/*
400657a94607STony Lindgren 		 * We do not want to return positive value from pm_runtime_get,
400757a94607STony Lindgren 		 * there are many instances of devices calling spi_setup() and
400857a94607STony Lindgren 		 * checking for a non-zero return value instead of a negative
400957a94607STony Lindgren 		 * return value.
401057a94607STony Lindgren 		 */
401157a94607STony Lindgren 		status = 0;
401257a94607STony Lindgren 
4013d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
4014d948e6caSLuhua Xu 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
4015d948e6caSLuhua Xu 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
4016d948e6caSLuhua Xu 	} else {
4017d347b4aaSDavid Bauer 		spi_set_cs(spi, false, true);
4018d948e6caSLuhua Xu 	}
4019abeedb01SFranklin S Cooper Jr 
40204fae3a58SSerge Semin 	mutex_unlock(&spi->controller->io_mutex);
40214fae3a58SSerge Semin 
4022924b5867SDouglas Anderson 	if (spi->rt && !spi->controller->rt) {
4023924b5867SDouglas Anderson 		spi->controller->rt = true;
4024924b5867SDouglas Anderson 		spi_set_thread_rt(spi->controller);
4025924b5867SDouglas Anderson 	}
4026924b5867SDouglas Anderson 
40275cb4e1f3SAndy Shevchenko 	trace_spi_setup(spi, status);
40285cb4e1f3SAndy Shevchenko 
402940b82c2dSAndy Shevchenko 	dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
403040b82c2dSAndy Shevchenko 			spi->mode & SPI_MODE_X_MASK,
40317d077197SDavid Brownell 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
40327d077197SDavid Brownell 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
40337d077197SDavid Brownell 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
40347d077197SDavid Brownell 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
40357d077197SDavid Brownell 			spi->bits_per_word, spi->max_speed_hz,
40367d077197SDavid Brownell 			status);
40377d077197SDavid Brownell 
40387d077197SDavid Brownell 	return status;
40397d077197SDavid Brownell }
40407d077197SDavid Brownell EXPORT_SYMBOL_GPL(spi_setup);
40417d077197SDavid Brownell 
40426c613f68SAlexandru Ardelean static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
40436c613f68SAlexandru Ardelean 				       struct spi_device *spi)
40446c613f68SAlexandru Ardelean {
40456c613f68SAlexandru Ardelean 	int delay1, delay2;
40466c613f68SAlexandru Ardelean 
40473984d39bSAlexandru Ardelean 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
40486c613f68SAlexandru Ardelean 	if (delay1 < 0)
40496c613f68SAlexandru Ardelean 		return delay1;
40506c613f68SAlexandru Ardelean 
40513984d39bSAlexandru Ardelean 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
40526c613f68SAlexandru Ardelean 	if (delay2 < 0)
40536c613f68SAlexandru Ardelean 		return delay2;
40546c613f68SAlexandru Ardelean 
40556c613f68SAlexandru Ardelean 	if (delay1 < delay2)
40566c613f68SAlexandru Ardelean 		memcpy(&xfer->word_delay, &spi->word_delay,
40576c613f68SAlexandru Ardelean 		       sizeof(xfer->word_delay));
40586c613f68SAlexandru Ardelean 
40596c613f68SAlexandru Ardelean 	return 0;
40606c613f68SAlexandru Ardelean }
40616c613f68SAlexandru Ardelean 
406290808738SMark Brown static int __spi_validate(struct spi_device *spi, struct spi_message *message)
4063cf32b71eSErnst Schwab {
40648caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4065e6811d1dSLaxman Dewangan 	struct spi_transfer *xfer;
40666ea31293SAtsushi Nemoto 	int w_size;
4067cf32b71eSErnst Schwab 
406824a0013aSMark Brown 	if (list_empty(&message->transfers))
406924a0013aSMark Brown 		return -EINVAL;
407024a0013aSMark Brown 
4071b204aa0fSDavid Lechner 	message->spi = spi;
4072b204aa0fSDavid Lechner 
4073350de7ceSAndy Shevchenko 	/*
4074350de7ceSAndy Shevchenko 	 * Half-duplex links include original MicroWire, and ones with
4075cf32b71eSErnst Schwab 	 * only one data pin like SPI_3WIRE (switches direction) or where
4076cf32b71eSErnst Schwab 	 * either MOSI or MISO is missing.  They can also be caused by
4077cf32b71eSErnst Schwab 	 * software limitations.
4078cf32b71eSErnst Schwab 	 */
40798caab75fSGeert Uytterhoeven 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
40808caab75fSGeert Uytterhoeven 	    (spi->mode & SPI_3WIRE)) {
40818caab75fSGeert Uytterhoeven 		unsigned flags = ctlr->flags;
4082cf32b71eSErnst Schwab 
4083cf32b71eSErnst Schwab 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
4084cf32b71eSErnst Schwab 			if (xfer->rx_buf && xfer->tx_buf)
4085cf32b71eSErnst Schwab 				return -EINVAL;
40868caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
4087cf32b71eSErnst Schwab 				return -EINVAL;
40888caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
4089cf32b71eSErnst Schwab 				return -EINVAL;
4090cf32b71eSErnst Schwab 		}
4091cf32b71eSErnst Schwab 	}
4092cf32b71eSErnst Schwab 
4093350de7ceSAndy Shevchenko 	/*
4094059b8ffeSLaxman Dewangan 	 * Set transfer bits_per_word and max speed as spi device default if
4095059b8ffeSLaxman Dewangan 	 * it is not set for this transfer.
4096f477b7fbSwangyuhang 	 * Set transfer tx_nbits and rx_nbits as single transfer default
4097f477b7fbSwangyuhang 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
4098b7bb367aSJonas Bonn 	 * Ensure transfer word_delay is at least as long as that required by
4099b7bb367aSJonas Bonn 	 * device itself.
4100e6811d1dSLaxman Dewangan 	 */
410177e80588SMartin Sperl 	message->frame_length = 0;
4102e6811d1dSLaxman Dewangan 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
41035d7e2b5eSMartin Sperl 		xfer->effective_speed_hz = 0;
4104078726ceSSourav Poddar 		message->frame_length += xfer->len;
4105e6811d1dSLaxman Dewangan 		if (!xfer->bits_per_word)
4106e6811d1dSLaxman Dewangan 			xfer->bits_per_word = spi->bits_per_word;
4107a6f87fadSAxel Lin 
4108a6f87fadSAxel Lin 		if (!xfer->speed_hz)
4109059b8ffeSLaxman Dewangan 			xfer->speed_hz = spi->max_speed_hz;
4110a6f87fadSAxel Lin 
41118caab75fSGeert Uytterhoeven 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
41128caab75fSGeert Uytterhoeven 			xfer->speed_hz = ctlr->max_speed_hz;
411356ede94aSGabor Juhos 
41148caab75fSGeert Uytterhoeven 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
4115543bb255SStephen Warren 			return -EINVAL;
4116a2fd4f9fSMark Brown 
41174d94bd21SIvan T. Ivanov 		/*
41184d94bd21SIvan T. Ivanov 		 * SPI transfer length should be multiple of SPI word size
4119350de7ceSAndy Shevchenko 		 * where SPI word size should be power-of-two multiple.
41204d94bd21SIvan T. Ivanov 		 */
41214d94bd21SIvan T. Ivanov 		if (xfer->bits_per_word <= 8)
41224d94bd21SIvan T. Ivanov 			w_size = 1;
41234d94bd21SIvan T. Ivanov 		else if (xfer->bits_per_word <= 16)
41244d94bd21SIvan T. Ivanov 			w_size = 2;
41254d94bd21SIvan T. Ivanov 		else
41264d94bd21SIvan T. Ivanov 			w_size = 4;
41274d94bd21SIvan T. Ivanov 
41284d94bd21SIvan T. Ivanov 		/* No partial transfers accepted */
41296ea31293SAtsushi Nemoto 		if (xfer->len % w_size)
41304d94bd21SIvan T. Ivanov 			return -EINVAL;
41314d94bd21SIvan T. Ivanov 
41328caab75fSGeert Uytterhoeven 		if (xfer->speed_hz && ctlr->min_speed_hz &&
41338caab75fSGeert Uytterhoeven 		    xfer->speed_hz < ctlr->min_speed_hz)
4134a2fd4f9fSMark Brown 			return -EINVAL;
4135f477b7fbSwangyuhang 
4136f477b7fbSwangyuhang 		if (xfer->tx_buf && !xfer->tx_nbits)
4137f477b7fbSwangyuhang 			xfer->tx_nbits = SPI_NBITS_SINGLE;
4138f477b7fbSwangyuhang 		if (xfer->rx_buf && !xfer->rx_nbits)
4139f477b7fbSwangyuhang 			xfer->rx_nbits = SPI_NBITS_SINGLE;
4140350de7ceSAndy Shevchenko 		/*
4141350de7ceSAndy Shevchenko 		 * Check transfer tx/rx_nbits:
41421afd9989SGeert Uytterhoeven 		 * 1. check the value matches one of single, dual and quad
41431afd9989SGeert Uytterhoeven 		 * 2. check tx/rx_nbits match the mode in spi_device
4144f477b7fbSwangyuhang 		 */
4145db90a441SSourav Poddar 		if (xfer->tx_buf) {
4146d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_TX)
4147d962608cSDragos Bogdan 				return -EINVAL;
4148f477b7fbSwangyuhang 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
4149f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_DUAL &&
4150f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_QUAD)
4151a2fd4f9fSMark Brown 				return -EINVAL;
4152f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
4153f477b7fbSwangyuhang 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
4154f477b7fbSwangyuhang 				return -EINVAL;
4155f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
4156f477b7fbSwangyuhang 				!(spi->mode & SPI_TX_QUAD))
4157f477b7fbSwangyuhang 				return -EINVAL;
4158db90a441SSourav Poddar 		}
415995c8222fSDavid Jander 		/* Check transfer rx_nbits */
4160db90a441SSourav Poddar 		if (xfer->rx_buf) {
4161d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_RX)
4162d962608cSDragos Bogdan 				return -EINVAL;
4163f477b7fbSwangyuhang 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
4164f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_DUAL &&
4165f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_QUAD)
4166f477b7fbSwangyuhang 				return -EINVAL;
4167f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
4168f477b7fbSwangyuhang 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
4169f477b7fbSwangyuhang 				return -EINVAL;
4170f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
4171f477b7fbSwangyuhang 				!(spi->mode & SPI_RX_QUAD))
4172f477b7fbSwangyuhang 				return -EINVAL;
4173e6811d1dSLaxman Dewangan 		}
4174b7bb367aSJonas Bonn 
41756c613f68SAlexandru Ardelean 		if (_spi_xfer_word_delay_update(xfer, spi))
41766c613f68SAlexandru Ardelean 			return -EINVAL;
4177e6811d1dSLaxman Dewangan 	}
4178e6811d1dSLaxman Dewangan 
4179cf32b71eSErnst Schwab 	message->status = -EINPROGRESS;
418090808738SMark Brown 
418190808738SMark Brown 	return 0;
418290808738SMark Brown }
418390808738SMark Brown 
41847b1d87afSDavid Lechner /*
4185fab53feaSDavid Lechner  * spi_split_transfers - generic handling of transfer splitting
4186fab53feaSDavid Lechner  * @msg: the message to split
4187fab53feaSDavid Lechner  *
4188fab53feaSDavid Lechner  * Under certain conditions, a SPI controller may not support arbitrary
4189fab53feaSDavid Lechner  * transfer sizes or other features required by a peripheral. This function
4190fab53feaSDavid Lechner  * will split the transfers in the message into smaller transfers that are
4191fab53feaSDavid Lechner  * supported by the controller.
4192fab53feaSDavid Lechner  *
4193fab53feaSDavid Lechner  * Controllers with special requirements not covered here can also split
4194fab53feaSDavid Lechner  * transfers in the optimize_message() callback.
4195fab53feaSDavid Lechner  *
4196fab53feaSDavid Lechner  * Context: can sleep
4197fab53feaSDavid Lechner  * Return: zero on success, else a negative error code
4198fab53feaSDavid Lechner  */
4199fab53feaSDavid Lechner static int spi_split_transfers(struct spi_message *msg)
4200fab53feaSDavid Lechner {
4201fab53feaSDavid Lechner 	struct spi_controller *ctlr = msg->spi->controller;
4202fab53feaSDavid Lechner 	struct spi_transfer *xfer;
4203fab53feaSDavid Lechner 	int ret;
4204fab53feaSDavid Lechner 
4205fab53feaSDavid Lechner 	/*
4206fab53feaSDavid Lechner 	 * If an SPI controller does not support toggling the CS line on each
4207fab53feaSDavid Lechner 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
4208fab53feaSDavid Lechner 	 * for the CS line, we can emulate the CS-per-word hardware function by
4209fab53feaSDavid Lechner 	 * splitting transfers into one-word transfers and ensuring that
4210fab53feaSDavid Lechner 	 * cs_change is set for each transfer.
4211fab53feaSDavid Lechner 	 */
4212fab53feaSDavid Lechner 	if ((msg->spi->mode & SPI_CS_WORD) &&
4213fab53feaSDavid Lechner 	    (!(ctlr->mode_bits & SPI_CS_WORD) || spi_is_csgpiod(msg->spi))) {
4214fab53feaSDavid Lechner 		ret = spi_split_transfers_maxwords(ctlr, msg, 1);
4215fab53feaSDavid Lechner 		if (ret)
4216fab53feaSDavid Lechner 			return ret;
4217fab53feaSDavid Lechner 
4218fab53feaSDavid Lechner 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
4219fab53feaSDavid Lechner 			/* Don't change cs_change on the last entry in the list */
4220fab53feaSDavid Lechner 			if (list_is_last(&xfer->transfer_list, &msg->transfers))
4221fab53feaSDavid Lechner 				break;
4222fab53feaSDavid Lechner 
4223fab53feaSDavid Lechner 			xfer->cs_change = 1;
4224fab53feaSDavid Lechner 		}
4225fab53feaSDavid Lechner 	} else {
4226fab53feaSDavid Lechner 		ret = spi_split_transfers_maxsize(ctlr, msg,
4227fab53feaSDavid Lechner 						  spi_max_transfer_size(msg->spi));
4228fab53feaSDavid Lechner 		if (ret)
4229fab53feaSDavid Lechner 			return ret;
4230fab53feaSDavid Lechner 	}
4231fab53feaSDavid Lechner 
4232fab53feaSDavid Lechner 	return 0;
4233fab53feaSDavid Lechner }
4234fab53feaSDavid Lechner 
4235fab53feaSDavid Lechner /*
42367b1d87afSDavid Lechner  * __spi_optimize_message - shared implementation for spi_optimize_message()
42377b1d87afSDavid Lechner  *                          and spi_maybe_optimize_message()
42387b1d87afSDavid Lechner  * @spi: the device that will be used for the message
42397b1d87afSDavid Lechner  * @msg: the message to optimize
42407b1d87afSDavid Lechner  *
42417b1d87afSDavid Lechner  * Peripheral drivers will call spi_optimize_message() and the spi core will
42427b1d87afSDavid Lechner  * call spi_maybe_optimize_message() instead of calling this directly.
42437b1d87afSDavid Lechner  *
42447b1d87afSDavid Lechner  * It is not valid to call this on a message that has already been optimized.
42457b1d87afSDavid Lechner  *
42467b1d87afSDavid Lechner  * Return: zero on success, else a negative error code
42477b1d87afSDavid Lechner  */
42487b1d87afSDavid Lechner static int __spi_optimize_message(struct spi_device *spi,
42497b1d87afSDavid Lechner 				  struct spi_message *msg)
42507b1d87afSDavid Lechner {
42517b1d87afSDavid Lechner 	struct spi_controller *ctlr = spi->controller;
42527b1d87afSDavid Lechner 	int ret;
42537b1d87afSDavid Lechner 
42547b1d87afSDavid Lechner 	ret = __spi_validate(spi, msg);
42557b1d87afSDavid Lechner 	if (ret)
42567b1d87afSDavid Lechner 		return ret;
42577b1d87afSDavid Lechner 
4258fab53feaSDavid Lechner 	ret = spi_split_transfers(msg);
42597b1d87afSDavid Lechner 	if (ret)
42607b1d87afSDavid Lechner 		return ret;
4261fab53feaSDavid Lechner 
4262fab53feaSDavid Lechner 	if (ctlr->optimize_message) {
4263fab53feaSDavid Lechner 		ret = ctlr->optimize_message(msg);
4264fab53feaSDavid Lechner 		if (ret) {
4265fab53feaSDavid Lechner 			spi_res_release(ctlr, msg);
4266fab53feaSDavid Lechner 			return ret;
4267fab53feaSDavid Lechner 		}
42687b1d87afSDavid Lechner 	}
42697b1d87afSDavid Lechner 
42707b1d87afSDavid Lechner 	msg->optimized = true;
42717b1d87afSDavid Lechner 
42727b1d87afSDavid Lechner 	return 0;
42737b1d87afSDavid Lechner }
42747b1d87afSDavid Lechner 
42757b1d87afSDavid Lechner /*
42767b1d87afSDavid Lechner  * spi_maybe_optimize_message - optimize message if it isn't already pre-optimized
42777b1d87afSDavid Lechner  * @spi: the device that will be used for the message
42787b1d87afSDavid Lechner  * @msg: the message to optimize
42797b1d87afSDavid Lechner  * Return: zero on success, else a negative error code
42807b1d87afSDavid Lechner  */
42817b1d87afSDavid Lechner static int spi_maybe_optimize_message(struct spi_device *spi,
42827b1d87afSDavid Lechner 				      struct spi_message *msg)
42837b1d87afSDavid Lechner {
42847b1d87afSDavid Lechner 	if (msg->pre_optimized)
42857b1d87afSDavid Lechner 		return 0;
42867b1d87afSDavid Lechner 
42877b1d87afSDavid Lechner 	return __spi_optimize_message(spi, msg);
42887b1d87afSDavid Lechner }
42897b1d87afSDavid Lechner 
42907b1d87afSDavid Lechner /**
42917b1d87afSDavid Lechner  * spi_optimize_message - do any one-time validation and setup for a SPI message
42927b1d87afSDavid Lechner  * @spi: the device that will be used for the message
42937b1d87afSDavid Lechner  * @msg: the message to optimize
42947b1d87afSDavid Lechner  *
42957b1d87afSDavid Lechner  * Peripheral drivers that reuse the same message repeatedly may call this to
42967b1d87afSDavid Lechner  * perform as much message prep as possible once, rather than repeating it each
42977b1d87afSDavid Lechner  * time a message transfer is performed to improve throughput and reduce CPU
42987b1d87afSDavid Lechner  * usage.
42997b1d87afSDavid Lechner  *
43007b1d87afSDavid Lechner  * Once a message has been optimized, it cannot be modified with the exception
43017b1d87afSDavid Lechner  * of updating the contents of any xfer->tx_buf (the pointer can't be changed,
43027b1d87afSDavid Lechner  * only the data in the memory it points to).
43037b1d87afSDavid Lechner  *
43047b1d87afSDavid Lechner  * Calls to this function must be balanced with calls to spi_unoptimize_message()
43057b1d87afSDavid Lechner  * to avoid leaking resources.
43067b1d87afSDavid Lechner  *
43077b1d87afSDavid Lechner  * Context: can sleep
43087b1d87afSDavid Lechner  * Return: zero on success, else a negative error code
43097b1d87afSDavid Lechner  */
43107b1d87afSDavid Lechner int spi_optimize_message(struct spi_device *spi, struct spi_message *msg)
43117b1d87afSDavid Lechner {
43127b1d87afSDavid Lechner 	int ret;
43137b1d87afSDavid Lechner 
43147b1d87afSDavid Lechner 	ret = __spi_optimize_message(spi, msg);
43157b1d87afSDavid Lechner 	if (ret)
43167b1d87afSDavid Lechner 		return ret;
43177b1d87afSDavid Lechner 
43187b1d87afSDavid Lechner 	/*
43197b1d87afSDavid Lechner 	 * This flag indicates that the peripheral driver called spi_optimize_message()
43207b1d87afSDavid Lechner 	 * and therefore we shouldn't unoptimize message automatically when finalizing
43217b1d87afSDavid Lechner 	 * the message but rather wait until spi_unoptimize_message() is called
43227b1d87afSDavid Lechner 	 * by the peripheral driver.
43237b1d87afSDavid Lechner 	 */
43247b1d87afSDavid Lechner 	msg->pre_optimized = true;
43257b1d87afSDavid Lechner 
43267b1d87afSDavid Lechner 	return 0;
43277b1d87afSDavid Lechner }
43287b1d87afSDavid Lechner EXPORT_SYMBOL_GPL(spi_optimize_message);
43297b1d87afSDavid Lechner 
43307b1d87afSDavid Lechner /**
43317b1d87afSDavid Lechner  * spi_unoptimize_message - releases any resources allocated by spi_optimize_message()
43327b1d87afSDavid Lechner  * @msg: the message to unoptimize
43337b1d87afSDavid Lechner  *
43347b1d87afSDavid Lechner  * Calls to this function must be balanced with calls to spi_optimize_message().
43357b1d87afSDavid Lechner  *
43367b1d87afSDavid Lechner  * Context: can sleep
43377b1d87afSDavid Lechner  */
43387b1d87afSDavid Lechner void spi_unoptimize_message(struct spi_message *msg)
43397b1d87afSDavid Lechner {
43407b1d87afSDavid Lechner 	__spi_unoptimize_message(msg);
43417b1d87afSDavid Lechner 	msg->pre_optimized = false;
43427b1d87afSDavid Lechner }
43437b1d87afSDavid Lechner EXPORT_SYMBOL_GPL(spi_unoptimize_message);
43447b1d87afSDavid Lechner 
434590808738SMark Brown static int __spi_async(struct spi_device *spi, struct spi_message *message)
434690808738SMark Brown {
43478caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4348b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
434990808738SMark Brown 
4350b5932f5cSBoris Brezillon 	/*
4351b5932f5cSBoris Brezillon 	 * Some controllers do not support doing regular SPI transfers. Return
4352b5932f5cSBoris Brezillon 	 * ENOTSUPP when this is the case.
4353b5932f5cSBoris Brezillon 	 */
4354b5932f5cSBoris Brezillon 	if (!ctlr->transfer)
4355b5932f5cSBoris Brezillon 		return -ENOTSUPP;
4356b5932f5cSBoris Brezillon 
43576598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async);
43586598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async);
4359eca2ebc7SMartin Sperl 
436090808738SMark Brown 	trace_spi_message_submit(message);
436190808738SMark Brown 
4362b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported) {
4363b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
4364b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
4365b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
4366b42faeeeSVladimir Oltean 		}
4367b42faeeeSVladimir Oltean 	}
4368b42faeeeSVladimir Oltean 
43698caab75fSGeert Uytterhoeven 	return ctlr->transfer(spi, message);
4370cf32b71eSErnst Schwab }
4371cf32b71eSErnst Schwab 
4372568d0697SDavid Brownell /**
4373568d0697SDavid Brownell  * spi_async - asynchronous SPI transfer
4374568d0697SDavid Brownell  * @spi: device with which data will be exchanged
4375568d0697SDavid Brownell  * @message: describes the data transfers, including completion callback
4376702ca026SAndy Shevchenko  * Context: any (IRQs may be blocked, etc)
4377568d0697SDavid Brownell  *
4378568d0697SDavid Brownell  * This call may be used in_irq and other contexts which can't sleep,
4379568d0697SDavid Brownell  * as well as from task contexts which can sleep.
4380568d0697SDavid Brownell  *
4381568d0697SDavid Brownell  * The completion callback is invoked in a context which can't sleep.
4382568d0697SDavid Brownell  * Before that invocation, the value of message->status is undefined.
4383568d0697SDavid Brownell  * When the callback is issued, message->status holds either zero (to
4384568d0697SDavid Brownell  * indicate complete success) or a negative error code.  After that
4385568d0697SDavid Brownell  * callback returns, the driver which issued the transfer request may
4386568d0697SDavid Brownell  * deallocate the associated memory; it's no longer in use by any SPI
4387568d0697SDavid Brownell  * core or controller driver code.
4388568d0697SDavid Brownell  *
4389568d0697SDavid Brownell  * Note that although all messages to a spi_device are handled in
4390568d0697SDavid Brownell  * FIFO order, messages may go to different devices in other orders.
4391568d0697SDavid Brownell  * Some device might be higher priority, or have various "hard" access
4392568d0697SDavid Brownell  * time requirements, for example.
4393568d0697SDavid Brownell  *
4394568d0697SDavid Brownell  * On detection of any fault during the transfer, processing of
4395568d0697SDavid Brownell  * the entire message is aborted, and the device is deselected.
4396568d0697SDavid Brownell  * Until returning from the associated message completion callback,
4397568d0697SDavid Brownell  * no other spi_message queued to that device will be processed.
4398568d0697SDavid Brownell  * (This rule applies equally to all the synchronous transfer calls,
4399568d0697SDavid Brownell  * which are wrappers around this core asynchronous primitive.)
440097d56dc6SJavier Martinez Canillas  *
440197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4402568d0697SDavid Brownell  */
4403568d0697SDavid Brownell int spi_async(struct spi_device *spi, struct spi_message *message)
4404568d0697SDavid Brownell {
44058caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
4406cf32b71eSErnst Schwab 	int ret;
4407cf32b71eSErnst Schwab 	unsigned long flags;
4408568d0697SDavid Brownell 
44097b1d87afSDavid Lechner 	ret = spi_maybe_optimize_message(spi, message);
44107b1d87afSDavid Lechner 	if (ret)
441190808738SMark Brown 		return ret;
441290808738SMark Brown 
44138caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
4414568d0697SDavid Brownell 
44158caab75fSGeert Uytterhoeven 	if (ctlr->bus_lock_flag)
4416cf32b71eSErnst Schwab 		ret = -EBUSY;
4417cf32b71eSErnst Schwab 	else
4418cf32b71eSErnst Schwab 		ret = __spi_async(spi, message);
4419568d0697SDavid Brownell 
44208caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4421cf32b71eSErnst Schwab 
44227b1d87afSDavid Lechner 	spi_maybe_unoptimize_message(message);
44237b1d87afSDavid Lechner 
4424cf32b71eSErnst Schwab 	return ret;
4425568d0697SDavid Brownell }
4426568d0697SDavid Brownell EXPORT_SYMBOL_GPL(spi_async);
4427568d0697SDavid Brownell 
4428ae7d2346SDavid Jander static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg)
4429ae7d2346SDavid Jander {
4430ae7d2346SDavid Jander 	bool was_busy;
4431ae7d2346SDavid Jander 	int ret;
4432ae7d2346SDavid Jander 
4433ae7d2346SDavid Jander 	mutex_lock(&ctlr->io_mutex);
4434ae7d2346SDavid Jander 
44351a9cafcbSDavid Jander 	was_busy = ctlr->busy;
4436ae7d2346SDavid Jander 
443772c5c59bSDavid Jander 	ctlr->cur_msg = msg;
4438ae7d2346SDavid Jander 	ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
4439ae7d2346SDavid Jander 	if (ret)
4440bef4a48fSMark Hasemeyer 		dev_err(&ctlr->dev, "noqueue transfer failed\n");
444169fa9590SDavid Jander 	ctlr->cur_msg = NULL;
444269fa9590SDavid Jander 	ctlr->fallback = false;
444369fa9590SDavid Jander 
4444ae7d2346SDavid Jander 	if (!was_busy) {
4445ae7d2346SDavid Jander 		kfree(ctlr->dummy_rx);
4446ae7d2346SDavid Jander 		ctlr->dummy_rx = NULL;
4447ae7d2346SDavid Jander 		kfree(ctlr->dummy_tx);
4448ae7d2346SDavid Jander 		ctlr->dummy_tx = NULL;
4449ae7d2346SDavid Jander 		if (ctlr->unprepare_transfer_hardware &&
4450ae7d2346SDavid Jander 		    ctlr->unprepare_transfer_hardware(ctlr))
4451ae7d2346SDavid Jander 			dev_err(&ctlr->dev,
4452ae7d2346SDavid Jander 				"failed to unprepare transfer hardware\n");
4453ae7d2346SDavid Jander 		spi_idle_runtime_pm(ctlr);
4454ae7d2346SDavid Jander 	}
4455ae7d2346SDavid Jander 
4456ae7d2346SDavid Jander 	mutex_unlock(&ctlr->io_mutex);
4457ae7d2346SDavid Jander }
4458ae7d2346SDavid Jander 
44597d077197SDavid Brownell /*-------------------------------------------------------------------------*/
44607d077197SDavid Brownell 
4461350de7ceSAndy Shevchenko /*
4462350de7ceSAndy Shevchenko  * Utility methods for SPI protocol drivers, layered on
44637d077197SDavid Brownell  * top of the core.  Some other utility methods are defined as
44647d077197SDavid Brownell  * inline functions.
44657d077197SDavid Brownell  */
44667d077197SDavid Brownell 
44675d870c8eSAndrew Morton static void spi_complete(void *arg)
44685d870c8eSAndrew Morton {
44695d870c8eSAndrew Morton 	complete(arg);
44705d870c8eSAndrew Morton }
44715d870c8eSAndrew Morton 
4472ef4d96ecSMark Brown static int __spi_sync(struct spi_device *spi, struct spi_message *message)
4473cf32b71eSErnst Schwab {
4474cf32b71eSErnst Schwab 	DECLARE_COMPLETION_ONSTACK(done);
44750da9a579SDavid Lechner 	unsigned long flags;
4476cf32b71eSErnst Schwab 	int status;
44778caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
44780461a414SMark Brown 
4479bef4a48fSMark Hasemeyer 	if (__spi_check_suspended(ctlr)) {
4480bef4a48fSMark Hasemeyer 		dev_warn_once(&spi->dev, "Attempted to sync while suspend\n");
4481bef4a48fSMark Hasemeyer 		return -ESHUTDOWN;
4482bef4a48fSMark Hasemeyer 	}
4483bef4a48fSMark Hasemeyer 
44847b1d87afSDavid Lechner 	status = spi_maybe_optimize_message(spi, message);
44857b1d87afSDavid Lechner 	if (status)
44860461a414SMark Brown 		return status;
4487cf32b71eSErnst Schwab 
44886598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync);
44896598b91bSDavid Jander 	SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync);
4490eca2ebc7SMartin Sperl 
4491350de7ceSAndy Shevchenko 	/*
4492ae7d2346SDavid Jander 	 * Checking queue_empty here only guarantees async/sync message
4493ae7d2346SDavid Jander 	 * ordering when coming from the same context. It does not need to
4494ae7d2346SDavid Jander 	 * guard against reentrancy from a different context. The io_mutex
4495ae7d2346SDavid Jander 	 * will catch those cases.
44960461a414SMark Brown 	 */
4497b30f7c8eSMark Brown 	if (READ_ONCE(ctlr->queue_empty) && !ctlr->must_async) {
4498ae7d2346SDavid Jander 		message->actual_length = 0;
4499ae7d2346SDavid Jander 		message->status = -EINPROGRESS;
45000461a414SMark Brown 
45010461a414SMark Brown 		trace_spi_message_submit(message);
45020461a414SMark Brown 
4503ae7d2346SDavid Jander 		SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate);
4504ae7d2346SDavid Jander 		SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate);
45050461a414SMark Brown 
4506ae7d2346SDavid Jander 		__spi_transfer_message_noqueue(ctlr, message);
4507ae7d2346SDavid Jander 
4508ae7d2346SDavid Jander 		return message->status;
4509ae7d2346SDavid Jander 	}
4510ae7d2346SDavid Jander 
4511ae7d2346SDavid Jander 	/*
4512ae7d2346SDavid Jander 	 * There are messages in the async queue that could have originated
4513ae7d2346SDavid Jander 	 * from the same context, so we need to preserve ordering.
4514ae7d2346SDavid Jander 	 * Therefor we send the message to the async queue and wait until they
4515ae7d2346SDavid Jander 	 * are completed.
4516ae7d2346SDavid Jander 	 */
4517ae7d2346SDavid Jander 	message->complete = spi_complete;
4518ae7d2346SDavid Jander 	message->context = &done;
45190da9a579SDavid Lechner 
45200da9a579SDavid Lechner 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
45210da9a579SDavid Lechner 	status = __spi_async(spi, message);
45220da9a579SDavid Lechner 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
45230da9a579SDavid Lechner 
4524cf32b71eSErnst Schwab 	if (status == 0) {
4525cf32b71eSErnst Schwab 		wait_for_completion(&done);
4526cf32b71eSErnst Schwab 		status = message->status;
4527cf32b71eSErnst Schwab 	}
4528cf32b71eSErnst Schwab 	message->context = NULL;
4529ae7d2346SDavid Jander 
4530cf32b71eSErnst Schwab 	return status;
4531cf32b71eSErnst Schwab }
4532cf32b71eSErnst Schwab 
45338ae12a0dSDavid Brownell /**
45348ae12a0dSDavid Brownell  * spi_sync - blocking/synchronous SPI data transfers
45358ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
45368ae12a0dSDavid Brownell  * @message: describes the data transfers
453733e34dc6SDavid Brownell  * Context: can sleep
45388ae12a0dSDavid Brownell  *
45398ae12a0dSDavid Brownell  * This call may only be used from a context that may sleep.  The sleep
45408ae12a0dSDavid Brownell  * is non-interruptible, and has no timeout.  Low-overhead controller
45418ae12a0dSDavid Brownell  * drivers may DMA directly into and out of the message buffers.
45428ae12a0dSDavid Brownell  *
45438ae12a0dSDavid Brownell  * Note that the SPI device's chip select is active during the message,
45448ae12a0dSDavid Brownell  * and then is normally disabled between messages.  Drivers for some
45458ae12a0dSDavid Brownell  * frequently-used devices may want to minimize costs of selecting a chip,
45468ae12a0dSDavid Brownell  * by leaving it selected in anticipation that the next message will go
45478ae12a0dSDavid Brownell  * to the same chip.  (That may increase power usage.)
45488ae12a0dSDavid Brownell  *
45490c868461SDavid Brownell  * Also, the caller is guaranteeing that the memory associated with the
45500c868461SDavid Brownell  * message will not be freed before this call returns.
45510c868461SDavid Brownell  *
455297d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
45538ae12a0dSDavid Brownell  */
45548ae12a0dSDavid Brownell int spi_sync(struct spi_device *spi, struct spi_message *message)
45558ae12a0dSDavid Brownell {
4556ef4d96ecSMark Brown 	int ret;
4557ef4d96ecSMark Brown 
45588caab75fSGeert Uytterhoeven 	mutex_lock(&spi->controller->bus_lock_mutex);
4559ef4d96ecSMark Brown 	ret = __spi_sync(spi, message);
45608caab75fSGeert Uytterhoeven 	mutex_unlock(&spi->controller->bus_lock_mutex);
4561ef4d96ecSMark Brown 
4562ef4d96ecSMark Brown 	return ret;
45638ae12a0dSDavid Brownell }
45648ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_sync);
45658ae12a0dSDavid Brownell 
4566cf32b71eSErnst Schwab /**
4567cf32b71eSErnst Schwab  * spi_sync_locked - version of spi_sync with exclusive bus usage
4568cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
4569cf32b71eSErnst Schwab  * @message: describes the data transfers
4570cf32b71eSErnst Schwab  * Context: can sleep
4571cf32b71eSErnst Schwab  *
4572cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4573cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.  Low-overhead controller
4574cf32b71eSErnst Schwab  * drivers may DMA directly into and out of the message buffers.
4575cf32b71eSErnst Schwab  *
4576cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
457725985edcSLucas De Marchi  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
4578cf32b71eSErnst Schwab  * be released by a spi_bus_unlock call when the exclusive access is over.
4579cf32b71eSErnst Schwab  *
458097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
4581cf32b71eSErnst Schwab  */
4582cf32b71eSErnst Schwab int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
4583cf32b71eSErnst Schwab {
4584ef4d96ecSMark Brown 	return __spi_sync(spi, message);
4585cf32b71eSErnst Schwab }
4586cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_sync_locked);
4587cf32b71eSErnst Schwab 
4588cf32b71eSErnst Schwab /**
4589cf32b71eSErnst Schwab  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
45908caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that should be locked for exclusive bus access
4591cf32b71eSErnst Schwab  * Context: can sleep
4592cf32b71eSErnst Schwab  *
4593cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4594cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4595cf32b71eSErnst Schwab  *
4596cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
4597cf32b71eSErnst Schwab  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
4598cf32b71eSErnst Schwab  * exclusive access is over. Data transfer must be done by spi_sync_locked
4599cf32b71eSErnst Schwab  * and spi_async_locked calls when the SPI bus lock is held.
4600cf32b71eSErnst Schwab  *
460197d56dc6SJavier Martinez Canillas  * Return: always zero.
4602cf32b71eSErnst Schwab  */
46038caab75fSGeert Uytterhoeven int spi_bus_lock(struct spi_controller *ctlr)
4604cf32b71eSErnst Schwab {
4605cf32b71eSErnst Schwab 	unsigned long flags;
4606cf32b71eSErnst Schwab 
46078caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->bus_lock_mutex);
4608cf32b71eSErnst Schwab 
46098caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
46108caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 1;
46118caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
4612cf32b71eSErnst Schwab 
461395c8222fSDavid Jander 	/* Mutex remains locked until spi_bus_unlock() is called */
4614cf32b71eSErnst Schwab 
4615cf32b71eSErnst Schwab 	return 0;
4616cf32b71eSErnst Schwab }
4617cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_lock);
4618cf32b71eSErnst Schwab 
4619cf32b71eSErnst Schwab /**
4620cf32b71eSErnst Schwab  * spi_bus_unlock - release the lock for exclusive SPI bus usage
46218caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that was locked for exclusive bus access
4622cf32b71eSErnst Schwab  * Context: can sleep
4623cf32b71eSErnst Schwab  *
4624cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
4625cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
4626cf32b71eSErnst Schwab  *
4627cf32b71eSErnst Schwab  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
4628cf32b71eSErnst Schwab  * call.
4629cf32b71eSErnst Schwab  *
463097d56dc6SJavier Martinez Canillas  * Return: always zero.
4631cf32b71eSErnst Schwab  */
46328caab75fSGeert Uytterhoeven int spi_bus_unlock(struct spi_controller *ctlr)
4633cf32b71eSErnst Schwab {
46348caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
4635cf32b71eSErnst Schwab 
46368caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->bus_lock_mutex);
4637cf32b71eSErnst Schwab 
4638cf32b71eSErnst Schwab 	return 0;
4639cf32b71eSErnst Schwab }
4640cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_unlock);
4641cf32b71eSErnst Schwab 
464295c8222fSDavid Jander /* Portable code must never pass more than 32 bytes */
4643a9948b61SDavid Brownell #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
46448ae12a0dSDavid Brownell 
46458ae12a0dSDavid Brownell static u8	*buf;
46468ae12a0dSDavid Brownell 
46478ae12a0dSDavid Brownell /**
46488ae12a0dSDavid Brownell  * spi_write_then_read - SPI synchronous write followed by read
46498ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
4650702ca026SAndy Shevchenko  * @txbuf: data to be written (need not be DMA-safe)
46518ae12a0dSDavid Brownell  * @n_tx: size of txbuf, in bytes
4652702ca026SAndy Shevchenko  * @rxbuf: buffer into which data will be read (need not be DMA-safe)
465327570497SJiri Pirko  * @n_rx: size of rxbuf, in bytes
465433e34dc6SDavid Brownell  * Context: can sleep
46558ae12a0dSDavid Brownell  *
46568ae12a0dSDavid Brownell  * This performs a half duplex MicroWire style transaction with the
46578ae12a0dSDavid Brownell  * device, sending txbuf and then reading rxbuf.  The return value
46588ae12a0dSDavid Brownell  * is zero for success, else a negative errno status code.
4659b885244eSDavid Brownell  * This call may only be used from a context that may sleep.
46608ae12a0dSDavid Brownell  *
4661c373643bSMark Brown  * Parameters to this routine are always copied using a small buffer.
466233e34dc6SDavid Brownell  * Performance-sensitive or bulk transfer code should instead use
4663702ca026SAndy Shevchenko  * spi_{async,sync}() calls with DMA-safe buffers.
466497d56dc6SJavier Martinez Canillas  *
466597d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
46668ae12a0dSDavid Brownell  */
46678ae12a0dSDavid Brownell int spi_write_then_read(struct spi_device *spi,
46680c4a1590SMark Brown 		const void *txbuf, unsigned n_tx,
46690c4a1590SMark Brown 		void *rxbuf, unsigned n_rx)
46708ae12a0dSDavid Brownell {
4671068f4070SDavid Brownell 	static DEFINE_MUTEX(lock);
46728ae12a0dSDavid Brownell 
46738ae12a0dSDavid Brownell 	int			status;
46748ae12a0dSDavid Brownell 	struct spi_message	message;
4675bdff549eSDavid Brownell 	struct spi_transfer	x[2];
46768ae12a0dSDavid Brownell 	u8			*local_buf;
46778ae12a0dSDavid Brownell 
4678350de7ceSAndy Shevchenko 	/*
4679350de7ceSAndy Shevchenko 	 * Use preallocated DMA-safe buffer if we can. We can't avoid
4680b3a223eeSMark Brown 	 * copying here, (as a pure convenience thing), but we can
4681b3a223eeSMark Brown 	 * keep heap costs out of the hot path unless someone else is
4682b3a223eeSMark Brown 	 * using the pre-allocated buffer or the transfer is too large.
46838ae12a0dSDavid Brownell 	 */
4684b3a223eeSMark Brown 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
46852cd94c8aSMark Brown 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
46862cd94c8aSMark Brown 				    GFP_KERNEL | GFP_DMA);
4687b3a223eeSMark Brown 		if (!local_buf)
4688b3a223eeSMark Brown 			return -ENOMEM;
4689b3a223eeSMark Brown 	} else {
4690b3a223eeSMark Brown 		local_buf = buf;
4691b3a223eeSMark Brown 	}
46928ae12a0dSDavid Brownell 
46938275c642SVitaly Wool 	spi_message_init(&message);
46945fe5f05eSJingoo Han 	memset(x, 0, sizeof(x));
4695bdff549eSDavid Brownell 	if (n_tx) {
4696bdff549eSDavid Brownell 		x[0].len = n_tx;
4697bdff549eSDavid Brownell 		spi_message_add_tail(&x[0], &message);
4698bdff549eSDavid Brownell 	}
4699bdff549eSDavid Brownell 	if (n_rx) {
4700bdff549eSDavid Brownell 		x[1].len = n_rx;
4701bdff549eSDavid Brownell 		spi_message_add_tail(&x[1], &message);
4702bdff549eSDavid Brownell 	}
47038275c642SVitaly Wool 
47048ae12a0dSDavid Brownell 	memcpy(local_buf, txbuf, n_tx);
4705bdff549eSDavid Brownell 	x[0].tx_buf = local_buf;
4706bdff549eSDavid Brownell 	x[1].rx_buf = local_buf + n_tx;
47078ae12a0dSDavid Brownell 
4708702ca026SAndy Shevchenko 	/* Do the I/O */
47098ae12a0dSDavid Brownell 	status = spi_sync(spi, &message);
47109b938b74SMarc Pignat 	if (status == 0)
4711bdff549eSDavid Brownell 		memcpy(rxbuf, x[1].rx_buf, n_rx);
47128ae12a0dSDavid Brownell 
4713bdff549eSDavid Brownell 	if (x[0].tx_buf == buf)
4714068f4070SDavid Brownell 		mutex_unlock(&lock);
47158ae12a0dSDavid Brownell 	else
47168ae12a0dSDavid Brownell 		kfree(local_buf);
47178ae12a0dSDavid Brownell 
47188ae12a0dSDavid Brownell 	return status;
47198ae12a0dSDavid Brownell }
47208ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_write_then_read);
47218ae12a0dSDavid Brownell 
47228ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
47238ae12a0dSDavid Brownell 
4724da21fde0SUwe Kleine-König #if IS_ENABLED(CONFIG_OF_DYNAMIC)
472595c8222fSDavid Jander /* Must call put_device() when done with returned spi_device device */
4726da21fde0SUwe Kleine-König static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4727ce79d54aSPantelis Antoniou {
4728cfba5de9SSuzuki K Poulose 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4729cfba5de9SSuzuki K Poulose 
4730ce79d54aSPantelis Antoniou 	return dev ? to_spi_device(dev) : NULL;
4731ce79d54aSPantelis Antoniou }
4732ce79d54aSPantelis Antoniou 
473395c8222fSDavid Jander /* The spi controllers are not using spi_bus, so we find it with another way */
47348caab75fSGeert Uytterhoeven static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4735ce79d54aSPantelis Antoniou {
4736ce79d54aSPantelis Antoniou 	struct device *dev;
4737ce79d54aSPantelis Antoniou 
4738cfba5de9SSuzuki K Poulose 	dev = class_find_device_by_of_node(&spi_master_class, node);
47396c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4740cfba5de9SSuzuki K Poulose 		dev = class_find_device_by_of_node(&spi_slave_class, node);
4741ce79d54aSPantelis Antoniou 	if (!dev)
4742ce79d54aSPantelis Antoniou 		return NULL;
4743ce79d54aSPantelis Antoniou 
474495c8222fSDavid Jander 	/* Reference got in class_find_device */
47458caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
4746ce79d54aSPantelis Antoniou }
4747ce79d54aSPantelis Antoniou 
4748ce79d54aSPantelis Antoniou static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4749ce79d54aSPantelis Antoniou 			 void *arg)
4750ce79d54aSPantelis Antoniou {
4751ce79d54aSPantelis Antoniou 	struct of_reconfig_data *rd = arg;
47528caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
4753ce79d54aSPantelis Antoniou 	struct spi_device *spi;
4754ce79d54aSPantelis Antoniou 
4755ce79d54aSPantelis Antoniou 	switch (of_reconfig_get_state_change(action, arg)) {
4756ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_ADD:
47578caab75fSGeert Uytterhoeven 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
47588caab75fSGeert Uytterhoeven 		if (ctlr == NULL)
475995c8222fSDavid Jander 			return NOTIFY_OK;	/* Not for us */
4760ce79d54aSPantelis Antoniou 
4761bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
47628caab75fSGeert Uytterhoeven 			put_device(&ctlr->dev);
4763bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4764bd6c1644SGeert Uytterhoeven 		}
4765bd6c1644SGeert Uytterhoeven 
47661a50d940SGeert Uytterhoeven 		/*
47671a50d940SGeert Uytterhoeven 		 * Clear the flag before adding the device so that fw_devlink
47681a50d940SGeert Uytterhoeven 		 * doesn't skip adding consumers to this device.
47691a50d940SGeert Uytterhoeven 		 */
47701a50d940SGeert Uytterhoeven 		rd->dn->fwnode.flags &= ~FWNODE_FLAG_NOT_DEVICE;
47718caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, rd->dn);
47728caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
4773ce79d54aSPantelis Antoniou 
4774ce79d54aSPantelis Antoniou 		if (IS_ERR(spi)) {
477525c56c88SRob Herring 			pr_err("%s: failed to create for '%pOF'\n",
477625c56c88SRob Herring 					__func__, rd->dn);
4777e0af98a7SRalf Ramsauer 			of_node_clear_flag(rd->dn, OF_POPULATED);
4778ce79d54aSPantelis Antoniou 			return notifier_from_errno(PTR_ERR(spi));
4779ce79d54aSPantelis Antoniou 		}
4780ce79d54aSPantelis Antoniou 		break;
4781ce79d54aSPantelis Antoniou 
4782ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_REMOVE:
478395c8222fSDavid Jander 		/* Already depopulated? */
4784bd6c1644SGeert Uytterhoeven 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4785bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4786bd6c1644SGeert Uytterhoeven 
478795c8222fSDavid Jander 		/* Find our device by node */
4788ce79d54aSPantelis Antoniou 		spi = of_find_spi_device_by_node(rd->dn);
4789ce79d54aSPantelis Antoniou 		if (spi == NULL)
479095c8222fSDavid Jander 			return NOTIFY_OK;	/* No? not meant for us */
4791ce79d54aSPantelis Antoniou 
479295c8222fSDavid Jander 		/* Unregister takes one ref away */
4793ce79d54aSPantelis Antoniou 		spi_unregister_device(spi);
4794ce79d54aSPantelis Antoniou 
479595c8222fSDavid Jander 		/* And put the reference of the find */
4796ce79d54aSPantelis Antoniou 		put_device(&spi->dev);
4797ce79d54aSPantelis Antoniou 		break;
4798ce79d54aSPantelis Antoniou 	}
4799ce79d54aSPantelis Antoniou 
4800ce79d54aSPantelis Antoniou 	return NOTIFY_OK;
4801ce79d54aSPantelis Antoniou }
4802ce79d54aSPantelis Antoniou 
4803ce79d54aSPantelis Antoniou static struct notifier_block spi_of_notifier = {
4804ce79d54aSPantelis Antoniou 	.notifier_call = of_spi_notify,
4805ce79d54aSPantelis Antoniou };
4806ce79d54aSPantelis Antoniou #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4807ce79d54aSPantelis Antoniou extern struct notifier_block spi_of_notifier;
4808ce79d54aSPantelis Antoniou #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4809ce79d54aSPantelis Antoniou 
48107f24467fSOctavian Purdila #if IS_ENABLED(CONFIG_ACPI)
48118caab75fSGeert Uytterhoeven static int spi_acpi_controller_match(struct device *dev, const void *data)
48127f24467fSOctavian Purdila {
48137f24467fSOctavian Purdila 	return ACPI_COMPANION(dev->parent) == data;
48147f24467fSOctavian Purdila }
48157f24467fSOctavian Purdila 
4816a8ecbc54SHans de Goede struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
48177f24467fSOctavian Purdila {
48187f24467fSOctavian Purdila 	struct device *dev;
48197f24467fSOctavian Purdila 
48207f24467fSOctavian Purdila 	dev = class_find_device(&spi_master_class, NULL, adev,
48218caab75fSGeert Uytterhoeven 				spi_acpi_controller_match);
48226c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
48236c364062SGeert Uytterhoeven 		dev = class_find_device(&spi_slave_class, NULL, adev,
48248caab75fSGeert Uytterhoeven 					spi_acpi_controller_match);
48257f24467fSOctavian Purdila 	if (!dev)
48267f24467fSOctavian Purdila 		return NULL;
48277f24467fSOctavian Purdila 
48288caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
48297f24467fSOctavian Purdila }
4830a8ecbc54SHans de Goede EXPORT_SYMBOL_GPL(acpi_spi_find_controller_by_adev);
48317f24467fSOctavian Purdila 
48327f24467fSOctavian Purdila static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
48337f24467fSOctavian Purdila {
48347f24467fSOctavian Purdila 	struct device *dev;
48357f24467fSOctavian Purdila 
483600500147SSuzuki K Poulose 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
48375b16668eSWolfram Sang 	return to_spi_device(dev);
48387f24467fSOctavian Purdila }
48397f24467fSOctavian Purdila 
48407f24467fSOctavian Purdila static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
48417f24467fSOctavian Purdila 			   void *arg)
48427f24467fSOctavian Purdila {
48437f24467fSOctavian Purdila 	struct acpi_device *adev = arg;
48448caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
48457f24467fSOctavian Purdila 	struct spi_device *spi;
48467f24467fSOctavian Purdila 
48477f24467fSOctavian Purdila 	switch (value) {
48487f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_ADD:
484962fcb99bSRafael J. Wysocki 		ctlr = acpi_spi_find_controller_by_adev(acpi_dev_parent(adev));
48508caab75fSGeert Uytterhoeven 		if (!ctlr)
48517f24467fSOctavian Purdila 			break;
48527f24467fSOctavian Purdila 
48538caab75fSGeert Uytterhoeven 		acpi_register_spi_device(ctlr, adev);
48548caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
48557f24467fSOctavian Purdila 		break;
48567f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_REMOVE:
48577f24467fSOctavian Purdila 		if (!acpi_device_enumerated(adev))
48587f24467fSOctavian Purdila 			break;
48597f24467fSOctavian Purdila 
48607f24467fSOctavian Purdila 		spi = acpi_spi_find_device_by_adev(adev);
48617f24467fSOctavian Purdila 		if (!spi)
48627f24467fSOctavian Purdila 			break;
48637f24467fSOctavian Purdila 
48647f24467fSOctavian Purdila 		spi_unregister_device(spi);
48657f24467fSOctavian Purdila 		put_device(&spi->dev);
48667f24467fSOctavian Purdila 		break;
48677f24467fSOctavian Purdila 	}
48687f24467fSOctavian Purdila 
48697f24467fSOctavian Purdila 	return NOTIFY_OK;
48707f24467fSOctavian Purdila }
48717f24467fSOctavian Purdila 
48727f24467fSOctavian Purdila static struct notifier_block spi_acpi_notifier = {
48737f24467fSOctavian Purdila 	.notifier_call = acpi_spi_notify,
48747f24467fSOctavian Purdila };
48757f24467fSOctavian Purdila #else
48767f24467fSOctavian Purdila extern struct notifier_block spi_acpi_notifier;
48777f24467fSOctavian Purdila #endif
48787f24467fSOctavian Purdila 
48798ae12a0dSDavid Brownell static int __init spi_init(void)
48808ae12a0dSDavid Brownell {
4881b885244eSDavid Brownell 	int	status;
48828ae12a0dSDavid Brownell 
4883e94b1766SChristoph Lameter 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4884b885244eSDavid Brownell 	if (!buf) {
4885b885244eSDavid Brownell 		status = -ENOMEM;
4886b885244eSDavid Brownell 		goto err0;
48878ae12a0dSDavid Brownell 	}
4888b885244eSDavid Brownell 
4889b885244eSDavid Brownell 	status = bus_register(&spi_bus_type);
4890b885244eSDavid Brownell 	if (status < 0)
4891b885244eSDavid Brownell 		goto err1;
4892b885244eSDavid Brownell 
4893b885244eSDavid Brownell 	status = class_register(&spi_master_class);
4894b885244eSDavid Brownell 	if (status < 0)
4895b885244eSDavid Brownell 		goto err2;
4896ce79d54aSPantelis Antoniou 
48976c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
48986c364062SGeert Uytterhoeven 		status = class_register(&spi_slave_class);
48996c364062SGeert Uytterhoeven 		if (status < 0)
49006c364062SGeert Uytterhoeven 			goto err3;
49016c364062SGeert Uytterhoeven 	}
49026c364062SGeert Uytterhoeven 
49035267720eSFabio Estevam 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4904ce79d54aSPantelis Antoniou 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
49057f24467fSOctavian Purdila 	if (IS_ENABLED(CONFIG_ACPI))
49067f24467fSOctavian Purdila 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4907ce79d54aSPantelis Antoniou 
4908b885244eSDavid Brownell 	return 0;
4909b885244eSDavid Brownell 
49106c364062SGeert Uytterhoeven err3:
49116c364062SGeert Uytterhoeven 	class_unregister(&spi_master_class);
4912b885244eSDavid Brownell err2:
4913b885244eSDavid Brownell 	bus_unregister(&spi_bus_type);
4914b885244eSDavid Brownell err1:
4915b885244eSDavid Brownell 	kfree(buf);
4916b885244eSDavid Brownell 	buf = NULL;
4917b885244eSDavid Brownell err0:
4918b885244eSDavid Brownell 	return status;
4919b885244eSDavid Brownell }
4920b885244eSDavid Brownell 
4921350de7ceSAndy Shevchenko /*
4922350de7ceSAndy Shevchenko  * A board_info is normally registered in arch_initcall(),
4923350de7ceSAndy Shevchenko  * but even essential drivers wait till later.
4924b885244eSDavid Brownell  *
4925350de7ceSAndy Shevchenko  * REVISIT only boardinfo really needs static linking. The rest (device and
4926350de7ceSAndy Shevchenko  * driver registration) _could_ be dynamically linked (modular) ... Costs
4927b885244eSDavid Brownell  * include needing to have boardinfo data structures be much more public.
49288ae12a0dSDavid Brownell  */
4929673c0c00SDavid Brownell postcore_initcall(spi_init);
4930