xref: /linux/drivers/spi/spi.c (revision 47afc77bbfeac163d81c7a675d608c18561aa680)
1b445bfcbSMarco Felsch // SPDX-License-Identifier: GPL-2.0-or-later
2787f4889SMark Brown // SPI init/core code
3787f4889SMark Brown //
4787f4889SMark Brown // Copyright (C) 2005 David Brownell
5787f4889SMark Brown // Copyright (C) 2008 Secret Lab Technologies Ltd.
68ae12a0dSDavid Brownell 
78ae12a0dSDavid Brownell #include <linux/kernel.h>
88ae12a0dSDavid Brownell #include <linux/device.h>
98ae12a0dSDavid Brownell #include <linux/init.h>
108ae12a0dSDavid Brownell #include <linux/cache.h>
1199adef31SMark Brown #include <linux/dma-mapping.h>
1299adef31SMark Brown #include <linux/dmaengine.h>
1394040828SMatthias Kaehlcke #include <linux/mutex.h>
142b7a32f7SSinan Akman #include <linux/of_device.h>
15d57a4282SGrant Likely #include <linux/of_irq.h>
1686be408bSSylwester Nawrocki #include <linux/clk/clk-conf.h>
175a0e3ad6STejun Heo #include <linux/slab.h>
18e0626e38SAnton Vorontsov #include <linux/mod_devicetable.h>
198ae12a0dSDavid Brownell #include <linux/spi/spi.h>
20b5932f5cSBoris Brezillon #include <linux/spi/spi-mem.h>
2174317984SJean-Christophe PLAGNIOL-VILLARD #include <linux/of_gpio.h>
22f3186dd8SLinus Walleij #include <linux/gpio/consumer.h>
233ae22e8cSMark Brown #include <linux/pm_runtime.h>
24f48c767cSUlf Hansson #include <linux/pm_domain.h>
25826cf175SDmitry Torokhov #include <linux/property.h>
26025ed130SPaul Gortmaker #include <linux/export.h>
278bd75c77SClark Williams #include <linux/sched/rt.h>
28ae7e81c0SIngo Molnar #include <uapi/linux/sched/types.h>
29ffbbdd21SLinus Walleij #include <linux/delay.h>
30ffbbdd21SLinus Walleij #include <linux/kthread.h>
3164bee4d2SMika Westerberg #include <linux/ioport.h>
3264bee4d2SMika Westerberg #include <linux/acpi.h>
33b1b8153cSVignesh R #include <linux/highmem.h>
349b61e302SSuniel Mahesh #include <linux/idr.h>
358a2e487eSLukas Wunner #include <linux/platform_data/x86/apple.h>
368ae12a0dSDavid Brownell 
3756ec1978SMark Brown #define CREATE_TRACE_POINTS
3856ec1978SMark Brown #include <trace/events/spi.h>
39ca1438dcSArnd Bergmann EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40ca1438dcSArnd Bergmann EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
419b61e302SSuniel Mahesh 
4246336966SBoris Brezillon #include "internals.h"
4346336966SBoris Brezillon 
449b61e302SSuniel Mahesh static DEFINE_IDR(spi_master_idr);
4556ec1978SMark Brown 
468ae12a0dSDavid Brownell static void spidev_release(struct device *dev)
478ae12a0dSDavid Brownell {
480ffa0285SHans-Peter Nilsson 	struct spi_device	*spi = to_spi_device(dev);
498ae12a0dSDavid Brownell 
508caab75fSGeert Uytterhoeven 	/* spi controllers may cleanup for released devices */
518caab75fSGeert Uytterhoeven 	if (spi->controller->cleanup)
528caab75fSGeert Uytterhoeven 		spi->controller->cleanup(spi);
538ae12a0dSDavid Brownell 
548caab75fSGeert Uytterhoeven 	spi_controller_put(spi->controller);
555039563eSTrent Piepho 	kfree(spi->driver_override);
5607a389feSRoman Tereshonkov 	kfree(spi);
578ae12a0dSDavid Brownell }
588ae12a0dSDavid Brownell 
598ae12a0dSDavid Brownell static ssize_t
608ae12a0dSDavid Brownell modalias_show(struct device *dev, struct device_attribute *a, char *buf)
618ae12a0dSDavid Brownell {
628ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
638c4ff6d0SZhang Rui 	int len;
648c4ff6d0SZhang Rui 
658c4ff6d0SZhang Rui 	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
668c4ff6d0SZhang Rui 	if (len != -ENODEV)
678c4ff6d0SZhang Rui 		return len;
688ae12a0dSDavid Brownell 
69d8e328b3SGrant Likely 	return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
708ae12a0dSDavid Brownell }
71aa7da564SGreg Kroah-Hartman static DEVICE_ATTR_RO(modalias);
728ae12a0dSDavid Brownell 
735039563eSTrent Piepho static ssize_t driver_override_store(struct device *dev,
745039563eSTrent Piepho 				     struct device_attribute *a,
755039563eSTrent Piepho 				     const char *buf, size_t count)
765039563eSTrent Piepho {
775039563eSTrent Piepho 	struct spi_device *spi = to_spi_device(dev);
785039563eSTrent Piepho 	const char *end = memchr(buf, '\n', count);
795039563eSTrent Piepho 	const size_t len = end ? end - buf : count;
805039563eSTrent Piepho 	const char *driver_override, *old;
815039563eSTrent Piepho 
825039563eSTrent Piepho 	/* We need to keep extra room for a newline when displaying value */
835039563eSTrent Piepho 	if (len >= (PAGE_SIZE - 1))
845039563eSTrent Piepho 		return -EINVAL;
855039563eSTrent Piepho 
865039563eSTrent Piepho 	driver_override = kstrndup(buf, len, GFP_KERNEL);
875039563eSTrent Piepho 	if (!driver_override)
885039563eSTrent Piepho 		return -ENOMEM;
895039563eSTrent Piepho 
905039563eSTrent Piepho 	device_lock(dev);
915039563eSTrent Piepho 	old = spi->driver_override;
925039563eSTrent Piepho 	if (len) {
935039563eSTrent Piepho 		spi->driver_override = driver_override;
945039563eSTrent Piepho 	} else {
95be73e323SAndy Shevchenko 		/* Empty string, disable driver override */
965039563eSTrent Piepho 		spi->driver_override = NULL;
975039563eSTrent Piepho 		kfree(driver_override);
985039563eSTrent Piepho 	}
995039563eSTrent Piepho 	device_unlock(dev);
1005039563eSTrent Piepho 	kfree(old);
1015039563eSTrent Piepho 
1025039563eSTrent Piepho 	return count;
1035039563eSTrent Piepho }
1045039563eSTrent Piepho 
1055039563eSTrent Piepho static ssize_t driver_override_show(struct device *dev,
1065039563eSTrent Piepho 				    struct device_attribute *a, char *buf)
1075039563eSTrent Piepho {
1085039563eSTrent Piepho 	const struct spi_device *spi = to_spi_device(dev);
1095039563eSTrent Piepho 	ssize_t len;
1105039563eSTrent Piepho 
1115039563eSTrent Piepho 	device_lock(dev);
1125039563eSTrent Piepho 	len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
1135039563eSTrent Piepho 	device_unlock(dev);
1145039563eSTrent Piepho 	return len;
1155039563eSTrent Piepho }
1165039563eSTrent Piepho static DEVICE_ATTR_RW(driver_override);
1175039563eSTrent Piepho 
118eca2ebc7SMartin Sperl #define SPI_STATISTICS_ATTRS(field, file)				\
1198caab75fSGeert Uytterhoeven static ssize_t spi_controller_##field##_show(struct device *dev,	\
120eca2ebc7SMartin Sperl 					     struct device_attribute *attr, \
121eca2ebc7SMartin Sperl 					     char *buf)			\
122eca2ebc7SMartin Sperl {									\
1238caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev,			\
1248caab75fSGeert Uytterhoeven 					 struct spi_controller, dev);	\
1258caab75fSGeert Uytterhoeven 	return spi_statistics_##field##_show(&ctlr->statistics, buf);	\
126eca2ebc7SMartin Sperl }									\
1278caab75fSGeert Uytterhoeven static struct device_attribute dev_attr_spi_controller_##field = {	\
128ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
1298caab75fSGeert Uytterhoeven 	.show = spi_controller_##field##_show,				\
130eca2ebc7SMartin Sperl };									\
131eca2ebc7SMartin Sperl static ssize_t spi_device_##field##_show(struct device *dev,		\
132eca2ebc7SMartin Sperl 					 struct device_attribute *attr,	\
133eca2ebc7SMartin Sperl 					char *buf)			\
134eca2ebc7SMartin Sperl {									\
135d1eba93bSGeliang Tang 	struct spi_device *spi = to_spi_device(dev);			\
136eca2ebc7SMartin Sperl 	return spi_statistics_##field##_show(&spi->statistics, buf);	\
137eca2ebc7SMartin Sperl }									\
138eca2ebc7SMartin Sperl static struct device_attribute dev_attr_spi_device_##field = {		\
139ad25c92eSGeert Uytterhoeven 	.attr = { .name = file, .mode = 0444 },				\
140eca2ebc7SMartin Sperl 	.show = spi_device_##field##_show,				\
141eca2ebc7SMartin Sperl }
142eca2ebc7SMartin Sperl 
143eca2ebc7SMartin Sperl #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string)	\
144eca2ebc7SMartin Sperl static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
145eca2ebc7SMartin Sperl 					    char *buf)			\
146eca2ebc7SMartin Sperl {									\
147eca2ebc7SMartin Sperl 	unsigned long flags;						\
148eca2ebc7SMartin Sperl 	ssize_t len;							\
149eca2ebc7SMartin Sperl 	spin_lock_irqsave(&stat->lock, flags);				\
150eca2ebc7SMartin Sperl 	len = sprintf(buf, format_string, stat->field);			\
151eca2ebc7SMartin Sperl 	spin_unlock_irqrestore(&stat->lock, flags);			\
152eca2ebc7SMartin Sperl 	return len;							\
153eca2ebc7SMartin Sperl }									\
154eca2ebc7SMartin Sperl SPI_STATISTICS_ATTRS(name, file)
155eca2ebc7SMartin Sperl 
156eca2ebc7SMartin Sperl #define SPI_STATISTICS_SHOW(field, format_string)			\
157eca2ebc7SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(field, __stringify(field),		\
158eca2ebc7SMartin Sperl 				 field, format_string)
159eca2ebc7SMartin Sperl 
160eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(messages, "%lu");
161eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(transfers, "%lu");
162eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(errors, "%lu");
163eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(timedout, "%lu");
164eca2ebc7SMartin Sperl 
165eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(spi_sync, "%lu");
166eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
167eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(spi_async, "%lu");
168eca2ebc7SMartin Sperl 
169eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(bytes, "%llu");
170eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(bytes_rx, "%llu");
171eca2ebc7SMartin Sperl SPI_STATISTICS_SHOW(bytes_tx, "%llu");
172eca2ebc7SMartin Sperl 
1736b7bc061SMartin Sperl #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number)		\
1746b7bc061SMartin Sperl 	SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index,		\
1756b7bc061SMartin Sperl 				 "transfer_bytes_histo_" number,	\
1766b7bc061SMartin Sperl 				 transfer_bytes_histo[index],  "%lu")
1776b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(0,  "0-1");
1786b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(1,  "2-3");
1796b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(2,  "4-7");
1806b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(3,  "8-15");
1816b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(4,  "16-31");
1826b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(5,  "32-63");
1836b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(6,  "64-127");
1846b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(7,  "128-255");
1856b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(8,  "256-511");
1866b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(9,  "512-1023");
1876b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
1886b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
1896b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
1906b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
1916b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
1926b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
1936b7bc061SMartin Sperl SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
1946b7bc061SMartin Sperl 
195d9f12122SMartin Sperl SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
196d9f12122SMartin Sperl 
197aa7da564SGreg Kroah-Hartman static struct attribute *spi_dev_attrs[] = {
198aa7da564SGreg Kroah-Hartman 	&dev_attr_modalias.attr,
1995039563eSTrent Piepho 	&dev_attr_driver_override.attr,
200aa7da564SGreg Kroah-Hartman 	NULL,
2018ae12a0dSDavid Brownell };
202eca2ebc7SMartin Sperl 
203eca2ebc7SMartin Sperl static const struct attribute_group spi_dev_group = {
204eca2ebc7SMartin Sperl 	.attrs  = spi_dev_attrs,
205eca2ebc7SMartin Sperl };
206eca2ebc7SMartin Sperl 
207eca2ebc7SMartin Sperl static struct attribute *spi_device_statistics_attrs[] = {
208eca2ebc7SMartin Sperl 	&dev_attr_spi_device_messages.attr,
209eca2ebc7SMartin Sperl 	&dev_attr_spi_device_transfers.attr,
210eca2ebc7SMartin Sperl 	&dev_attr_spi_device_errors.attr,
211eca2ebc7SMartin Sperl 	&dev_attr_spi_device_timedout.attr,
212eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync.attr,
213eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_sync_immediate.attr,
214eca2ebc7SMartin Sperl 	&dev_attr_spi_device_spi_async.attr,
215eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes.attr,
216eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_rx.attr,
217eca2ebc7SMartin Sperl 	&dev_attr_spi_device_bytes_tx.attr,
2186b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo0.attr,
2196b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo1.attr,
2206b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo2.attr,
2216b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo3.attr,
2226b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo4.attr,
2236b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo5.attr,
2246b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo6.attr,
2256b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo7.attr,
2266b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo8.attr,
2276b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo9.attr,
2286b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo10.attr,
2296b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo11.attr,
2306b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo12.attr,
2316b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo13.attr,
2326b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo14.attr,
2336b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo15.attr,
2346b7bc061SMartin Sperl 	&dev_attr_spi_device_transfer_bytes_histo16.attr,
235d9f12122SMartin Sperl 	&dev_attr_spi_device_transfers_split_maxsize.attr,
236eca2ebc7SMartin Sperl 	NULL,
237eca2ebc7SMartin Sperl };
238eca2ebc7SMartin Sperl 
239eca2ebc7SMartin Sperl static const struct attribute_group spi_device_statistics_group = {
240eca2ebc7SMartin Sperl 	.name  = "statistics",
241eca2ebc7SMartin Sperl 	.attrs  = spi_device_statistics_attrs,
242eca2ebc7SMartin Sperl };
243eca2ebc7SMartin Sperl 
244eca2ebc7SMartin Sperl static const struct attribute_group *spi_dev_groups[] = {
245eca2ebc7SMartin Sperl 	&spi_dev_group,
246eca2ebc7SMartin Sperl 	&spi_device_statistics_group,
247eca2ebc7SMartin Sperl 	NULL,
248eca2ebc7SMartin Sperl };
249eca2ebc7SMartin Sperl 
2508caab75fSGeert Uytterhoeven static struct attribute *spi_controller_statistics_attrs[] = {
2518caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_messages.attr,
2528caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers.attr,
2538caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_errors.attr,
2548caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_timedout.attr,
2558caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync.attr,
2568caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_sync_immediate.attr,
2578caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_spi_async.attr,
2588caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes.attr,
2598caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_rx.attr,
2608caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_bytes_tx.attr,
2618caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo0.attr,
2628caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo1.attr,
2638caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo2.attr,
2648caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo3.attr,
2658caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo4.attr,
2668caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo5.attr,
2678caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo6.attr,
2688caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo7.attr,
2698caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo8.attr,
2708caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo9.attr,
2718caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo10.attr,
2728caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo11.attr,
2738caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo12.attr,
2748caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo13.attr,
2758caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo14.attr,
2768caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo15.attr,
2778caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfer_bytes_histo16.attr,
2788caab75fSGeert Uytterhoeven 	&dev_attr_spi_controller_transfers_split_maxsize.attr,
279eca2ebc7SMartin Sperl 	NULL,
280eca2ebc7SMartin Sperl };
281eca2ebc7SMartin Sperl 
2828caab75fSGeert Uytterhoeven static const struct attribute_group spi_controller_statistics_group = {
283eca2ebc7SMartin Sperl 	.name  = "statistics",
2848caab75fSGeert Uytterhoeven 	.attrs  = spi_controller_statistics_attrs,
285eca2ebc7SMartin Sperl };
286eca2ebc7SMartin Sperl 
287eca2ebc7SMartin Sperl static const struct attribute_group *spi_master_groups[] = {
2888caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
289eca2ebc7SMartin Sperl 	NULL,
290eca2ebc7SMartin Sperl };
291eca2ebc7SMartin Sperl 
292eca2ebc7SMartin Sperl void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
293eca2ebc7SMartin Sperl 				       struct spi_transfer *xfer,
2948caab75fSGeert Uytterhoeven 				       struct spi_controller *ctlr)
295eca2ebc7SMartin Sperl {
296eca2ebc7SMartin Sperl 	unsigned long flags;
2976b7bc061SMartin Sperl 	int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
2986b7bc061SMartin Sperl 
2996b7bc061SMartin Sperl 	if (l2len < 0)
3006b7bc061SMartin Sperl 		l2len = 0;
301eca2ebc7SMartin Sperl 
302eca2ebc7SMartin Sperl 	spin_lock_irqsave(&stats->lock, flags);
303eca2ebc7SMartin Sperl 
304eca2ebc7SMartin Sperl 	stats->transfers++;
3056b7bc061SMartin Sperl 	stats->transfer_bytes_histo[l2len]++;
306eca2ebc7SMartin Sperl 
307eca2ebc7SMartin Sperl 	stats->bytes += xfer->len;
308eca2ebc7SMartin Sperl 	if ((xfer->tx_buf) &&
3098caab75fSGeert Uytterhoeven 	    (xfer->tx_buf != ctlr->dummy_tx))
310eca2ebc7SMartin Sperl 		stats->bytes_tx += xfer->len;
311eca2ebc7SMartin Sperl 	if ((xfer->rx_buf) &&
3128caab75fSGeert Uytterhoeven 	    (xfer->rx_buf != ctlr->dummy_rx))
313eca2ebc7SMartin Sperl 		stats->bytes_rx += xfer->len;
314eca2ebc7SMartin Sperl 
315eca2ebc7SMartin Sperl 	spin_unlock_irqrestore(&stats->lock, flags);
316eca2ebc7SMartin Sperl }
317eca2ebc7SMartin Sperl EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
3188ae12a0dSDavid Brownell 
3198ae12a0dSDavid Brownell /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
3208ae12a0dSDavid Brownell  * and the sysfs version makes coldplug work too.
3218ae12a0dSDavid Brownell  */
3228ae12a0dSDavid Brownell 
32375368bf6SAnton Vorontsov static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
32475368bf6SAnton Vorontsov 						const struct spi_device *sdev)
32575368bf6SAnton Vorontsov {
32675368bf6SAnton Vorontsov 	while (id->name[0]) {
32775368bf6SAnton Vorontsov 		if (!strcmp(sdev->modalias, id->name))
32875368bf6SAnton Vorontsov 			return id;
32975368bf6SAnton Vorontsov 		id++;
33075368bf6SAnton Vorontsov 	}
33175368bf6SAnton Vorontsov 	return NULL;
33275368bf6SAnton Vorontsov }
33375368bf6SAnton Vorontsov 
33475368bf6SAnton Vorontsov const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
33575368bf6SAnton Vorontsov {
33675368bf6SAnton Vorontsov 	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
33775368bf6SAnton Vorontsov 
33875368bf6SAnton Vorontsov 	return spi_match_id(sdrv->id_table, sdev);
33975368bf6SAnton Vorontsov }
34075368bf6SAnton Vorontsov EXPORT_SYMBOL_GPL(spi_get_device_id);
34175368bf6SAnton Vorontsov 
3428ae12a0dSDavid Brownell static int spi_match_device(struct device *dev, struct device_driver *drv)
3438ae12a0dSDavid Brownell {
3448ae12a0dSDavid Brownell 	const struct spi_device	*spi = to_spi_device(dev);
34575368bf6SAnton Vorontsov 	const struct spi_driver	*sdrv = to_spi_driver(drv);
34675368bf6SAnton Vorontsov 
3475039563eSTrent Piepho 	/* Check override first, and if set, only use the named driver */
3485039563eSTrent Piepho 	if (spi->driver_override)
3495039563eSTrent Piepho 		return strcmp(spi->driver_override, drv->name) == 0;
3505039563eSTrent Piepho 
3512b7a32f7SSinan Akman 	/* Attempt an OF style match */
3522b7a32f7SSinan Akman 	if (of_driver_match_device(dev, drv))
3532b7a32f7SSinan Akman 		return 1;
3542b7a32f7SSinan Akman 
35564bee4d2SMika Westerberg 	/* Then try ACPI */
35664bee4d2SMika Westerberg 	if (acpi_driver_match_device(dev, drv))
35764bee4d2SMika Westerberg 		return 1;
35864bee4d2SMika Westerberg 
35975368bf6SAnton Vorontsov 	if (sdrv->id_table)
36075368bf6SAnton Vorontsov 		return !!spi_match_id(sdrv->id_table, spi);
3618ae12a0dSDavid Brownell 
36235f74fcaSKay Sievers 	return strcmp(spi->modalias, drv->name) == 0;
3638ae12a0dSDavid Brownell }
3648ae12a0dSDavid Brownell 
3657eff2e7aSKay Sievers static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
3668ae12a0dSDavid Brownell {
3678ae12a0dSDavid Brownell 	const struct spi_device		*spi = to_spi_device(dev);
3688c4ff6d0SZhang Rui 	int rc;
3698c4ff6d0SZhang Rui 
3708c4ff6d0SZhang Rui 	rc = acpi_device_uevent_modalias(dev, env);
3718c4ff6d0SZhang Rui 	if (rc != -ENODEV)
3728c4ff6d0SZhang Rui 		return rc;
3738ae12a0dSDavid Brownell 
3742856670fSAndy Shevchenko 	return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
3758ae12a0dSDavid Brownell }
3768ae12a0dSDavid Brownell 
3779db34ee6SUwe Kleine-König static int spi_probe(struct device *dev)
378b885244eSDavid Brownell {
379b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
38044af7927SJon Hunter 	struct spi_device		*spi = to_spi_device(dev);
38133cf00e5SMika Westerberg 	int ret;
382b885244eSDavid Brownell 
38386be408bSSylwester Nawrocki 	ret = of_clk_set_defaults(dev->of_node, false);
38486be408bSSylwester Nawrocki 	if (ret)
38586be408bSSylwester Nawrocki 		return ret;
38686be408bSSylwester Nawrocki 
38744af7927SJon Hunter 	if (dev->of_node) {
38844af7927SJon Hunter 		spi->irq = of_irq_get(dev->of_node, 0);
38944af7927SJon Hunter 		if (spi->irq == -EPROBE_DEFER)
39044af7927SJon Hunter 			return -EPROBE_DEFER;
39144af7927SJon Hunter 		if (spi->irq < 0)
39244af7927SJon Hunter 			spi->irq = 0;
39344af7927SJon Hunter 	}
39444af7927SJon Hunter 
395676e7c25SUlf Hansson 	ret = dev_pm_domain_attach(dev, true);
39671f277a7SUlf Hansson 	if (ret)
39771f277a7SUlf Hansson 		return ret;
39871f277a7SUlf Hansson 
399440408dbSUwe Kleine-König 	if (sdrv->probe) {
40044af7927SJon Hunter 		ret = sdrv->probe(spi);
40133cf00e5SMika Westerberg 		if (ret)
402676e7c25SUlf Hansson 			dev_pm_domain_detach(dev, true);
403440408dbSUwe Kleine-König 	}
40433cf00e5SMika Westerberg 
40533cf00e5SMika Westerberg 	return ret;
406b885244eSDavid Brownell }
407b885244eSDavid Brownell 
4089db34ee6SUwe Kleine-König static int spi_remove(struct device *dev)
409b885244eSDavid Brownell {
410b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
411b885244eSDavid Brownell 
4127795d475SUwe Kleine-König 	if (sdrv->remove) {
4137795d475SUwe Kleine-König 		int ret;
4147795d475SUwe Kleine-König 
415aec35f4eSJean Delvare 		ret = sdrv->remove(to_spi_device(dev));
4167795d475SUwe Kleine-König 		if (ret)
4177795d475SUwe Kleine-König 			dev_warn(dev,
4187795d475SUwe Kleine-König 				 "Failed to unbind driver (%pe), ignoring\n",
4197795d475SUwe Kleine-König 				 ERR_PTR(ret));
4207795d475SUwe Kleine-König 	}
4217795d475SUwe Kleine-König 
422676e7c25SUlf Hansson 	dev_pm_domain_detach(dev, true);
42333cf00e5SMika Westerberg 
4247795d475SUwe Kleine-König 	return 0;
425b885244eSDavid Brownell }
426b885244eSDavid Brownell 
4279db34ee6SUwe Kleine-König static void spi_shutdown(struct device *dev)
428b885244eSDavid Brownell {
429a6f483b2SMarek Szyprowski 	if (dev->driver) {
430b885244eSDavid Brownell 		const struct spi_driver	*sdrv = to_spi_driver(dev->driver);
431b885244eSDavid Brownell 
4329db34ee6SUwe Kleine-König 		if (sdrv->shutdown)
433b885244eSDavid Brownell 			sdrv->shutdown(to_spi_device(dev));
434b885244eSDavid Brownell 	}
435a6f483b2SMarek Szyprowski }
436b885244eSDavid Brownell 
4379db34ee6SUwe Kleine-König struct bus_type spi_bus_type = {
4389db34ee6SUwe Kleine-König 	.name		= "spi",
4399db34ee6SUwe Kleine-König 	.dev_groups	= spi_dev_groups,
4409db34ee6SUwe Kleine-König 	.match		= spi_match_device,
4419db34ee6SUwe Kleine-König 	.uevent		= spi_uevent,
4429db34ee6SUwe Kleine-König 	.probe		= spi_probe,
4439db34ee6SUwe Kleine-König 	.remove		= spi_remove,
4449db34ee6SUwe Kleine-König 	.shutdown	= spi_shutdown,
4459db34ee6SUwe Kleine-König };
4469db34ee6SUwe Kleine-König EXPORT_SYMBOL_GPL(spi_bus_type);
4479db34ee6SUwe Kleine-König 
44833e34dc6SDavid Brownell /**
449ca5d2485SAndrew F. Davis  * __spi_register_driver - register a SPI driver
45088c9321dSThierry Reding  * @owner: owner module of the driver to register
45133e34dc6SDavid Brownell  * @sdrv: the driver to register
45233e34dc6SDavid Brownell  * Context: can sleep
45397d56dc6SJavier Martinez Canillas  *
45497d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
45533e34dc6SDavid Brownell  */
456ca5d2485SAndrew F. Davis int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
457b885244eSDavid Brownell {
458ca5d2485SAndrew F. Davis 	sdrv->driver.owner = owner;
459b885244eSDavid Brownell 	sdrv->driver.bus = &spi_bus_type;
460b885244eSDavid Brownell 	return driver_register(&sdrv->driver);
461b885244eSDavid Brownell }
462ca5d2485SAndrew F. Davis EXPORT_SYMBOL_GPL(__spi_register_driver);
463b885244eSDavid Brownell 
4648ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
4658ae12a0dSDavid Brownell 
4668ae12a0dSDavid Brownell /* SPI devices should normally not be created by SPI device drivers; that
4678caab75fSGeert Uytterhoeven  * would make them board-specific.  Similarly with SPI controller drivers.
4688ae12a0dSDavid Brownell  * Device registration normally goes into like arch/.../mach.../board-YYY.c
4698ae12a0dSDavid Brownell  * with other readonly (flashable) information about mainboard devices.
4708ae12a0dSDavid Brownell  */
4718ae12a0dSDavid Brownell 
4728ae12a0dSDavid Brownell struct boardinfo {
4738ae12a0dSDavid Brownell 	struct list_head	list;
4742b9603a0SFeng Tang 	struct spi_board_info	board_info;
4758ae12a0dSDavid Brownell };
4768ae12a0dSDavid Brownell 
4778ae12a0dSDavid Brownell static LIST_HEAD(board_list);
4788caab75fSGeert Uytterhoeven static LIST_HEAD(spi_controller_list);
4792b9603a0SFeng Tang 
4802b9603a0SFeng Tang /*
481be73e323SAndy Shevchenko  * Used to protect add/del operation for board_info list and
4828caab75fSGeert Uytterhoeven  * spi_controller list, and their matching process
4839b61e302SSuniel Mahesh  * also used to protect object of type struct idr
4842b9603a0SFeng Tang  */
48594040828SMatthias Kaehlcke static DEFINE_MUTEX(board_lock);
4868ae12a0dSDavid Brownell 
487ddf75be4SLukas Wunner /*
488ddf75be4SLukas Wunner  * Prevents addition of devices with same chip select and
489ddf75be4SLukas Wunner  * addition of devices below an unregistering controller.
490ddf75be4SLukas Wunner  */
491ddf75be4SLukas Wunner static DEFINE_MUTEX(spi_add_lock);
492ddf75be4SLukas Wunner 
493dc87c98eSGrant Likely /**
494dc87c98eSGrant Likely  * spi_alloc_device - Allocate a new SPI device
4958caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
496dc87c98eSGrant Likely  * Context: can sleep
497dc87c98eSGrant Likely  *
498dc87c98eSGrant Likely  * Allows a driver to allocate and initialize a spi_device without
499dc87c98eSGrant Likely  * registering it immediately.  This allows a driver to directly
500dc87c98eSGrant Likely  * fill the spi_device with device parameters before calling
501dc87c98eSGrant Likely  * spi_add_device() on it.
502dc87c98eSGrant Likely  *
503dc87c98eSGrant Likely  * Caller is responsible to call spi_add_device() on the returned
5048caab75fSGeert Uytterhoeven  * spi_device structure to add it to the SPI controller.  If the caller
505dc87c98eSGrant Likely  * needs to discard the spi_device without adding it, then it should
506dc87c98eSGrant Likely  * call spi_dev_put() on it.
507dc87c98eSGrant Likely  *
50897d56dc6SJavier Martinez Canillas  * Return: a pointer to the new device, or NULL.
509dc87c98eSGrant Likely  */
5108caab75fSGeert Uytterhoeven struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
511dc87c98eSGrant Likely {
512dc87c98eSGrant Likely 	struct spi_device	*spi;
513dc87c98eSGrant Likely 
5148caab75fSGeert Uytterhoeven 	if (!spi_controller_get(ctlr))
515dc87c98eSGrant Likely 		return NULL;
516dc87c98eSGrant Likely 
5175fe5f05eSJingoo Han 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
518dc87c98eSGrant Likely 	if (!spi) {
5198caab75fSGeert Uytterhoeven 		spi_controller_put(ctlr);
520dc87c98eSGrant Likely 		return NULL;
521dc87c98eSGrant Likely 	}
522dc87c98eSGrant Likely 
5238caab75fSGeert Uytterhoeven 	spi->master = spi->controller = ctlr;
5248caab75fSGeert Uytterhoeven 	spi->dev.parent = &ctlr->dev;
525dc87c98eSGrant Likely 	spi->dev.bus = &spi_bus_type;
526dc87c98eSGrant Likely 	spi->dev.release = spidev_release;
527446411e1SAndreas Larsson 	spi->cs_gpio = -ENOENT;
528ea235786SJohn Garry 	spi->mode = ctlr->buswidth_override_bits;
529eca2ebc7SMartin Sperl 
530eca2ebc7SMartin Sperl 	spin_lock_init(&spi->statistics.lock);
531eca2ebc7SMartin Sperl 
532dc87c98eSGrant Likely 	device_initialize(&spi->dev);
533dc87c98eSGrant Likely 	return spi;
534dc87c98eSGrant Likely }
535dc87c98eSGrant Likely EXPORT_SYMBOL_GPL(spi_alloc_device);
536dc87c98eSGrant Likely 
537e13ac47bSJarkko Nikula static void spi_dev_set_name(struct spi_device *spi)
538e13ac47bSJarkko Nikula {
539e13ac47bSJarkko Nikula 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
540e13ac47bSJarkko Nikula 
541e13ac47bSJarkko Nikula 	if (adev) {
542e13ac47bSJarkko Nikula 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
543e13ac47bSJarkko Nikula 		return;
544e13ac47bSJarkko Nikula 	}
545e13ac47bSJarkko Nikula 
5468caab75fSGeert Uytterhoeven 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
547e13ac47bSJarkko Nikula 		     spi->chip_select);
548e13ac47bSJarkko Nikula }
549e13ac47bSJarkko Nikula 
550b6fb8d3aSMika Westerberg static int spi_dev_check(struct device *dev, void *data)
551b6fb8d3aSMika Westerberg {
552b6fb8d3aSMika Westerberg 	struct spi_device *spi = to_spi_device(dev);
553b6fb8d3aSMika Westerberg 	struct spi_device *new_spi = data;
554b6fb8d3aSMika Westerberg 
5558caab75fSGeert Uytterhoeven 	if (spi->controller == new_spi->controller &&
556b6fb8d3aSMika Westerberg 	    spi->chip_select == new_spi->chip_select)
557b6fb8d3aSMika Westerberg 		return -EBUSY;
558b6fb8d3aSMika Westerberg 	return 0;
559b6fb8d3aSMika Westerberg }
560b6fb8d3aSMika Westerberg 
561dc87c98eSGrant Likely /**
562dc87c98eSGrant Likely  * spi_add_device - Add spi_device allocated with spi_alloc_device
563dc87c98eSGrant Likely  * @spi: spi_device to register
564dc87c98eSGrant Likely  *
565dc87c98eSGrant Likely  * Companion function to spi_alloc_device.  Devices allocated with
566dc87c98eSGrant Likely  * spi_alloc_device can be added onto the spi bus with this function.
567dc87c98eSGrant Likely  *
56897d56dc6SJavier Martinez Canillas  * Return: 0 on success; negative errno on failure
569dc87c98eSGrant Likely  */
570dc87c98eSGrant Likely int spi_add_device(struct spi_device *spi)
571dc87c98eSGrant Likely {
5728caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
5738caab75fSGeert Uytterhoeven 	struct device *dev = ctlr->dev.parent;
574dc87c98eSGrant Likely 	int status;
575dc87c98eSGrant Likely 
576dc87c98eSGrant Likely 	/* Chipselects are numbered 0..max; validate. */
5778caab75fSGeert Uytterhoeven 	if (spi->chip_select >= ctlr->num_chipselect) {
5788caab75fSGeert Uytterhoeven 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
5798caab75fSGeert Uytterhoeven 			ctlr->num_chipselect);
580dc87c98eSGrant Likely 		return -EINVAL;
581dc87c98eSGrant Likely 	}
582dc87c98eSGrant Likely 
583dc87c98eSGrant Likely 	/* Set the bus ID string */
584e13ac47bSJarkko Nikula 	spi_dev_set_name(spi);
585e48880e0SDavid Brownell 
586e48880e0SDavid Brownell 	/* We need to make sure there's no other device with this
587e48880e0SDavid Brownell 	 * chipselect **BEFORE** we call setup(), else we'll trash
588e48880e0SDavid Brownell 	 * its configuration.  Lock against concurrent add() calls.
589e48880e0SDavid Brownell 	 */
590e48880e0SDavid Brownell 	mutex_lock(&spi_add_lock);
591e48880e0SDavid Brownell 
592b6fb8d3aSMika Westerberg 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
593b6fb8d3aSMika Westerberg 	if (status) {
594e48880e0SDavid Brownell 		dev_err(dev, "chipselect %d already in use\n",
595e48880e0SDavid Brownell 				spi->chip_select);
596e48880e0SDavid Brownell 		goto done;
597e48880e0SDavid Brownell 	}
598e48880e0SDavid Brownell 
599ddf75be4SLukas Wunner 	/* Controller may unregister concurrently */
600ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
601ddf75be4SLukas Wunner 	    !device_is_registered(&ctlr->dev)) {
602ddf75be4SLukas Wunner 		status = -ENODEV;
603ddf75be4SLukas Wunner 		goto done;
604ddf75be4SLukas Wunner 	}
605ddf75be4SLukas Wunner 
606f3186dd8SLinus Walleij 	/* Descriptors take precedence */
607f3186dd8SLinus Walleij 	if (ctlr->cs_gpiods)
608f3186dd8SLinus Walleij 		spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
609f3186dd8SLinus Walleij 	else if (ctlr->cs_gpios)
6108caab75fSGeert Uytterhoeven 		spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
61174317984SJean-Christophe PLAGNIOL-VILLARD 
612e48880e0SDavid Brownell 	/* Drivers may modify this initial i/o setup, but will
613e48880e0SDavid Brownell 	 * normally rely on the device being setup.  Devices
614e48880e0SDavid Brownell 	 * using SPI_CS_HIGH can't coexist well otherwise...
615e48880e0SDavid Brownell 	 */
6167d077197SDavid Brownell 	status = spi_setup(spi);
617dc87c98eSGrant Likely 	if (status < 0) {
618eb288a1fSLinus Walleij 		dev_err(dev, "can't setup %s, status %d\n",
619eb288a1fSLinus Walleij 				dev_name(&spi->dev), status);
620e48880e0SDavid Brownell 		goto done;
621dc87c98eSGrant Likely 	}
622dc87c98eSGrant Likely 
623e48880e0SDavid Brownell 	/* Device may be bound to an active driver when this returns */
624dc87c98eSGrant Likely 	status = device_add(&spi->dev);
625e48880e0SDavid Brownell 	if (status < 0)
626eb288a1fSLinus Walleij 		dev_err(dev, "can't add %s, status %d\n",
627eb288a1fSLinus Walleij 				dev_name(&spi->dev), status);
628e48880e0SDavid Brownell 	else
62935f74fcaSKay Sievers 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
630e48880e0SDavid Brownell 
631e48880e0SDavid Brownell done:
632e48880e0SDavid Brownell 	mutex_unlock(&spi_add_lock);
633e48880e0SDavid Brownell 	return status;
634dc87c98eSGrant Likely }
635dc87c98eSGrant Likely EXPORT_SYMBOL_GPL(spi_add_device);
6368ae12a0dSDavid Brownell 
63733e34dc6SDavid Brownell /**
63833e34dc6SDavid Brownell  * spi_new_device - instantiate one new SPI device
6398caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
64033e34dc6SDavid Brownell  * @chip: Describes the SPI device
64133e34dc6SDavid Brownell  * Context: can sleep
64233e34dc6SDavid Brownell  *
64333e34dc6SDavid Brownell  * On typical mainboards, this is purely internal; and it's not needed
6448ae12a0dSDavid Brownell  * after board init creates the hard-wired devices.  Some development
6458ae12a0dSDavid Brownell  * platforms may not be able to use spi_register_board_info though, and
6468ae12a0dSDavid Brownell  * this is exported so that for example a USB or parport based adapter
6478ae12a0dSDavid Brownell  * driver could add devices (which it would learn about out-of-band).
648082c8cb4SDavid Brownell  *
64997d56dc6SJavier Martinez Canillas  * Return: the new device, or NULL.
6508ae12a0dSDavid Brownell  */
6518caab75fSGeert Uytterhoeven struct spi_device *spi_new_device(struct spi_controller *ctlr,
652e9d5a461SAdrian Bunk 				  struct spi_board_info *chip)
6538ae12a0dSDavid Brownell {
6548ae12a0dSDavid Brownell 	struct spi_device	*proxy;
6558ae12a0dSDavid Brownell 	int			status;
6568ae12a0dSDavid Brownell 
657082c8cb4SDavid Brownell 	/* NOTE:  caller did any chip->bus_num checks necessary.
658082c8cb4SDavid Brownell 	 *
659082c8cb4SDavid Brownell 	 * Also, unless we change the return value convention to use
660082c8cb4SDavid Brownell 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
661082c8cb4SDavid Brownell 	 * suggests syslogged diagnostics are best here (ugh).
662082c8cb4SDavid Brownell 	 */
663082c8cb4SDavid Brownell 
6648caab75fSGeert Uytterhoeven 	proxy = spi_alloc_device(ctlr);
665dc87c98eSGrant Likely 	if (!proxy)
6668ae12a0dSDavid Brownell 		return NULL;
6678ae12a0dSDavid Brownell 
668102eb975SGrant Likely 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
669102eb975SGrant Likely 
6708ae12a0dSDavid Brownell 	proxy->chip_select = chip->chip_select;
6718ae12a0dSDavid Brownell 	proxy->max_speed_hz = chip->max_speed_hz;
672980a01c9SDavid Brownell 	proxy->mode = chip->mode;
6738ae12a0dSDavid Brownell 	proxy->irq = chip->irq;
674102eb975SGrant Likely 	strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
6758ae12a0dSDavid Brownell 	proxy->dev.platform_data = (void *) chip->platform_data;
6768ae12a0dSDavid Brownell 	proxy->controller_data = chip->controller_data;
6778ae12a0dSDavid Brownell 	proxy->controller_state = NULL;
6788ae12a0dSDavid Brownell 
679826cf175SDmitry Torokhov 	if (chip->properties) {
680826cf175SDmitry Torokhov 		status = device_add_properties(&proxy->dev, chip->properties);
681826cf175SDmitry Torokhov 		if (status) {
6828caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev,
683826cf175SDmitry Torokhov 				"failed to add properties to '%s': %d\n",
684826cf175SDmitry Torokhov 				chip->modalias, status);
685826cf175SDmitry Torokhov 			goto err_dev_put;
686826cf175SDmitry Torokhov 		}
6878ae12a0dSDavid Brownell 	}
688dc87c98eSGrant Likely 
689*47afc77bSHeikki Krogerus 	if (chip->swnode) {
690*47afc77bSHeikki Krogerus 		status = device_add_software_node(&proxy->dev, chip->swnode);
691*47afc77bSHeikki Krogerus 		if (status) {
692*47afc77bSHeikki Krogerus 			dev_err(&ctlr->dev, "failed to add softwade node to '%s': %d\n",
693*47afc77bSHeikki Krogerus 				chip->modalias, status);
694*47afc77bSHeikki Krogerus 			goto err_remove_props;
695*47afc77bSHeikki Krogerus 		}
696*47afc77bSHeikki Krogerus 	}
697*47afc77bSHeikki Krogerus 
698826cf175SDmitry Torokhov 	status = spi_add_device(proxy);
699826cf175SDmitry Torokhov 	if (status < 0)
700826cf175SDmitry Torokhov 		goto err_remove_props;
701826cf175SDmitry Torokhov 
702dc87c98eSGrant Likely 	return proxy;
703826cf175SDmitry Torokhov 
704826cf175SDmitry Torokhov err_remove_props:
705*47afc77bSHeikki Krogerus 	device_remove_software_node(&proxy->dev);
706826cf175SDmitry Torokhov err_dev_put:
707826cf175SDmitry Torokhov 	spi_dev_put(proxy);
708826cf175SDmitry Torokhov 	return NULL;
709dc87c98eSGrant Likely }
7108ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_new_device);
7118ae12a0dSDavid Brownell 
7123b1884c2SGeert Uytterhoeven /**
7133b1884c2SGeert Uytterhoeven  * spi_unregister_device - unregister a single SPI device
7143b1884c2SGeert Uytterhoeven  * @spi: spi_device to unregister
7153b1884c2SGeert Uytterhoeven  *
7163b1884c2SGeert Uytterhoeven  * Start making the passed SPI device vanish. Normally this would be handled
7178caab75fSGeert Uytterhoeven  * by spi_unregister_controller().
7183b1884c2SGeert Uytterhoeven  */
7193b1884c2SGeert Uytterhoeven void spi_unregister_device(struct spi_device *spi)
7203b1884c2SGeert Uytterhoeven {
721bd6c1644SGeert Uytterhoeven 	if (!spi)
722bd6c1644SGeert Uytterhoeven 		return;
723bd6c1644SGeert Uytterhoeven 
7248324147fSJohan Hovold 	if (spi->dev.of_node) {
725bd6c1644SGeert Uytterhoeven 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
7268324147fSJohan Hovold 		of_node_put(spi->dev.of_node);
7278324147fSJohan Hovold 	}
7287f24467fSOctavian Purdila 	if (ACPI_COMPANION(&spi->dev))
7297f24467fSOctavian Purdila 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
730*47afc77bSHeikki Krogerus 	device_remove_software_node(&spi->dev);
7313b1884c2SGeert Uytterhoeven 	device_unregister(&spi->dev);
7323b1884c2SGeert Uytterhoeven }
7333b1884c2SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_device);
7343b1884c2SGeert Uytterhoeven 
7358caab75fSGeert Uytterhoeven static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
7362b9603a0SFeng Tang 					      struct spi_board_info *bi)
7372b9603a0SFeng Tang {
7382b9603a0SFeng Tang 	struct spi_device *dev;
7392b9603a0SFeng Tang 
7408caab75fSGeert Uytterhoeven 	if (ctlr->bus_num != bi->bus_num)
7412b9603a0SFeng Tang 		return;
7422b9603a0SFeng Tang 
7438caab75fSGeert Uytterhoeven 	dev = spi_new_device(ctlr, bi);
7442b9603a0SFeng Tang 	if (!dev)
7458caab75fSGeert Uytterhoeven 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
7462b9603a0SFeng Tang 			bi->modalias);
7472b9603a0SFeng Tang }
7482b9603a0SFeng Tang 
74933e34dc6SDavid Brownell /**
75033e34dc6SDavid Brownell  * spi_register_board_info - register SPI devices for a given board
75133e34dc6SDavid Brownell  * @info: array of chip descriptors
75233e34dc6SDavid Brownell  * @n: how many descriptors are provided
75333e34dc6SDavid Brownell  * Context: can sleep
75433e34dc6SDavid Brownell  *
7558ae12a0dSDavid Brownell  * Board-specific early init code calls this (probably during arch_initcall)
7568ae12a0dSDavid Brownell  * with segments of the SPI device table.  Any device nodes are created later,
7578ae12a0dSDavid Brownell  * after the relevant parent SPI controller (bus_num) is defined.  We keep
7588ae12a0dSDavid Brownell  * this table of devices forever, so that reloading a controller driver will
7598ae12a0dSDavid Brownell  * not make Linux forget about these hard-wired devices.
7608ae12a0dSDavid Brownell  *
7618ae12a0dSDavid Brownell  * Other code can also call this, e.g. a particular add-on board might provide
7628ae12a0dSDavid Brownell  * SPI devices through its expansion connector, so code initializing that board
7638ae12a0dSDavid Brownell  * would naturally declare its SPI devices.
7648ae12a0dSDavid Brownell  *
7658ae12a0dSDavid Brownell  * The board info passed can safely be __initdata ... but be careful of
7668ae12a0dSDavid Brownell  * any embedded pointers (platform_data, etc), they're copied as-is.
767826cf175SDmitry Torokhov  * Device properties are deep-copied though.
76897d56dc6SJavier Martinez Canillas  *
76997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
7708ae12a0dSDavid Brownell  */
771fd4a319bSGrant Likely int spi_register_board_info(struct spi_board_info const *info, unsigned n)
7728ae12a0dSDavid Brownell {
7738ae12a0dSDavid Brownell 	struct boardinfo *bi;
7742b9603a0SFeng Tang 	int i;
7758ae12a0dSDavid Brownell 
776c7908a37SXiubo Li 	if (!n)
777f974cf57SDmitry Torokhov 		return 0;
778c7908a37SXiubo Li 
779f9bdb7fdSMarkus Elfring 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
7808ae12a0dSDavid Brownell 	if (!bi)
7818ae12a0dSDavid Brownell 		return -ENOMEM;
7828ae12a0dSDavid Brownell 
7832b9603a0SFeng Tang 	for (i = 0; i < n; i++, bi++, info++) {
7848caab75fSGeert Uytterhoeven 		struct spi_controller *ctlr;
7852b9603a0SFeng Tang 
7862b9603a0SFeng Tang 		memcpy(&bi->board_info, info, sizeof(*info));
787826cf175SDmitry Torokhov 		if (info->properties) {
788826cf175SDmitry Torokhov 			bi->board_info.properties =
789826cf175SDmitry Torokhov 					property_entries_dup(info->properties);
790826cf175SDmitry Torokhov 			if (IS_ERR(bi->board_info.properties))
791826cf175SDmitry Torokhov 				return PTR_ERR(bi->board_info.properties);
792826cf175SDmitry Torokhov 		}
793826cf175SDmitry Torokhov 
79494040828SMatthias Kaehlcke 		mutex_lock(&board_lock);
7958ae12a0dSDavid Brownell 		list_add_tail(&bi->list, &board_list);
7968caab75fSGeert Uytterhoeven 		list_for_each_entry(ctlr, &spi_controller_list, list)
7978caab75fSGeert Uytterhoeven 			spi_match_controller_to_boardinfo(ctlr,
7988caab75fSGeert Uytterhoeven 							  &bi->board_info);
79994040828SMatthias Kaehlcke 		mutex_unlock(&board_lock);
8002b9603a0SFeng Tang 	}
8012b9603a0SFeng Tang 
8028ae12a0dSDavid Brownell 	return 0;
8038ae12a0dSDavid Brownell }
8048ae12a0dSDavid Brownell 
8058ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
8068ae12a0dSDavid Brownell 
807b158935fSMark Brown static void spi_set_cs(struct spi_device *spi, bool enable)
808b158935fSMark Brown {
80925093bdeSAlexandru Ardelean 	bool enable1 = enable;
81025093bdeSAlexandru Ardelean 
811d40f0b6fSDouglas Anderson 	/*
812d40f0b6fSDouglas Anderson 	 * Avoid calling into the driver (or doing delays) if the chip select
813d40f0b6fSDouglas Anderson 	 * isn't actually changing from the last time this was called.
814d40f0b6fSDouglas Anderson 	 */
815d40f0b6fSDouglas Anderson 	if ((spi->controller->last_cs_enable == enable) &&
816d40f0b6fSDouglas Anderson 	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
817d40f0b6fSDouglas Anderson 		return;
818d40f0b6fSDouglas Anderson 
819d40f0b6fSDouglas Anderson 	spi->controller->last_cs_enable = enable;
820d40f0b6fSDouglas Anderson 	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
821d40f0b6fSDouglas Anderson 
8220486d9f9Sleilk.liu 	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
8230486d9f9Sleilk.liu 	    !spi->controller->set_cs_timing) {
82425093bdeSAlexandru Ardelean 		if (enable1)
82525093bdeSAlexandru Ardelean 			spi_delay_exec(&spi->controller->cs_setup, NULL);
82625093bdeSAlexandru Ardelean 		else
82725093bdeSAlexandru Ardelean 			spi_delay_exec(&spi->controller->cs_hold, NULL);
82825093bdeSAlexandru Ardelean 	}
82925093bdeSAlexandru Ardelean 
830b158935fSMark Brown 	if (spi->mode & SPI_CS_HIGH)
831b158935fSMark Brown 		enable = !enable;
832b158935fSMark Brown 
833f3186dd8SLinus Walleij 	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
834f3186dd8SLinus Walleij 		if (!(spi->mode & SPI_NO_CS)) {
835f3186dd8SLinus Walleij 			if (spi->cs_gpiod)
836766c6b63SSven Van Asbroeck 				/* polarity handled by gpiolib */
83728f7604fSFelix Fietkau 				gpiod_set_value_cansleep(spi->cs_gpiod,
838766c6b63SSven Van Asbroeck 							 enable1);
839f3186dd8SLinus Walleij 			else
840766c6b63SSven Van Asbroeck 				/*
841766c6b63SSven Van Asbroeck 				 * invert the enable line, as active low is
842766c6b63SSven Van Asbroeck 				 * default for SPI.
843766c6b63SSven Van Asbroeck 				 */
84428f7604fSFelix Fietkau 				gpio_set_value_cansleep(spi->cs_gpio, !enable);
845f3186dd8SLinus Walleij 		}
8468eee6b9dSThor Thayer 		/* Some SPI masters need both GPIO CS & slave_select */
8478caab75fSGeert Uytterhoeven 		if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
8488caab75fSGeert Uytterhoeven 		    spi->controller->set_cs)
8498caab75fSGeert Uytterhoeven 			spi->controller->set_cs(spi, !enable);
8508caab75fSGeert Uytterhoeven 	} else if (spi->controller->set_cs) {
8518caab75fSGeert Uytterhoeven 		spi->controller->set_cs(spi, !enable);
8528eee6b9dSThor Thayer 	}
85325093bdeSAlexandru Ardelean 
8540486d9f9Sleilk.liu 	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio) ||
8550486d9f9Sleilk.liu 	    !spi->controller->set_cs_timing) {
85625093bdeSAlexandru Ardelean 		if (!enable1)
85725093bdeSAlexandru Ardelean 			spi_delay_exec(&spi->controller->cs_inactive, NULL);
85825093bdeSAlexandru Ardelean 	}
859b158935fSMark Brown }
860b158935fSMark Brown 
8612de440f5SGeert Uytterhoeven #ifdef CONFIG_HAS_DMA
86246336966SBoris Brezillon int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
8636ad45a27SMark Brown 		struct sg_table *sgt, void *buf, size_t len,
8646ad45a27SMark Brown 		enum dma_data_direction dir)
8656ad45a27SMark Brown {
8666ad45a27SMark Brown 	const bool vmalloced_buf = is_vmalloc_addr(buf);
867df88e91bSAndy Shevchenko 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
868b1b8153cSVignesh R #ifdef CONFIG_HIGHMEM
869b1b8153cSVignesh R 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
870b1b8153cSVignesh R 				(unsigned long)buf < (PKMAP_BASE +
871b1b8153cSVignesh R 					(LAST_PKMAP * PAGE_SIZE)));
872b1b8153cSVignesh R #else
873b1b8153cSVignesh R 	const bool kmap_buf = false;
874b1b8153cSVignesh R #endif
87565598c13SAndrew Gabbasov 	int desc_len;
87665598c13SAndrew Gabbasov 	int sgs;
8776ad45a27SMark Brown 	struct page *vm_page;
8788dd4a016SJuan Gutierrez 	struct scatterlist *sg;
8796ad45a27SMark Brown 	void *sg_buf;
8806ad45a27SMark Brown 	size_t min;
8816ad45a27SMark Brown 	int i, ret;
8826ad45a27SMark Brown 
883b1b8153cSVignesh R 	if (vmalloced_buf || kmap_buf) {
884df88e91bSAndy Shevchenko 		desc_len = min_t(int, max_seg_size, PAGE_SIZE);
88565598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
8860569a88fSVignesh R 	} else if (virt_addr_valid(buf)) {
8878caab75fSGeert Uytterhoeven 		desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
88865598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len, desc_len);
8890569a88fSVignesh R 	} else {
8900569a88fSVignesh R 		return -EINVAL;
89165598c13SAndrew Gabbasov 	}
89265598c13SAndrew Gabbasov 
8936ad45a27SMark Brown 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
8946ad45a27SMark Brown 	if (ret != 0)
8956ad45a27SMark Brown 		return ret;
8966ad45a27SMark Brown 
8978dd4a016SJuan Gutierrez 	sg = &sgt->sgl[0];
8986ad45a27SMark Brown 	for (i = 0; i < sgs; i++) {
8996ad45a27SMark Brown 
900b1b8153cSVignesh R 		if (vmalloced_buf || kmap_buf) {
901ce99319aSMaxime Chevallier 			/*
902ce99319aSMaxime Chevallier 			 * Next scatterlist entry size is the minimum between
903ce99319aSMaxime Chevallier 			 * the desc_len and the remaining buffer length that
904ce99319aSMaxime Chevallier 			 * fits in a page.
905ce99319aSMaxime Chevallier 			 */
906ce99319aSMaxime Chevallier 			min = min_t(size_t, desc_len,
907ce99319aSMaxime Chevallier 				    min_t(size_t, len,
908ce99319aSMaxime Chevallier 					  PAGE_SIZE - offset_in_page(buf)));
909b1b8153cSVignesh R 			if (vmalloced_buf)
9106ad45a27SMark Brown 				vm_page = vmalloc_to_page(buf);
911b1b8153cSVignesh R 			else
912b1b8153cSVignesh R 				vm_page = kmap_to_page(buf);
9136ad45a27SMark Brown 			if (!vm_page) {
9146ad45a27SMark Brown 				sg_free_table(sgt);
9156ad45a27SMark Brown 				return -ENOMEM;
9166ad45a27SMark Brown 			}
9178dd4a016SJuan Gutierrez 			sg_set_page(sg, vm_page,
918c1aefbddSCharles Keepax 				    min, offset_in_page(buf));
9196ad45a27SMark Brown 		} else {
92065598c13SAndrew Gabbasov 			min = min_t(size_t, len, desc_len);
9216ad45a27SMark Brown 			sg_buf = buf;
9228dd4a016SJuan Gutierrez 			sg_set_buf(sg, sg_buf, min);
9236ad45a27SMark Brown 		}
9246ad45a27SMark Brown 
9256ad45a27SMark Brown 		buf += min;
9266ad45a27SMark Brown 		len -= min;
9278dd4a016SJuan Gutierrez 		sg = sg_next(sg);
9286ad45a27SMark Brown 	}
9296ad45a27SMark Brown 
9306ad45a27SMark Brown 	ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
93189e4b66aSGeert Uytterhoeven 	if (!ret)
93289e4b66aSGeert Uytterhoeven 		ret = -ENOMEM;
9336ad45a27SMark Brown 	if (ret < 0) {
9346ad45a27SMark Brown 		sg_free_table(sgt);
9356ad45a27SMark Brown 		return ret;
9366ad45a27SMark Brown 	}
9376ad45a27SMark Brown 
9386ad45a27SMark Brown 	sgt->nents = ret;
9396ad45a27SMark Brown 
9406ad45a27SMark Brown 	return 0;
9416ad45a27SMark Brown }
9426ad45a27SMark Brown 
94346336966SBoris Brezillon void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
9446ad45a27SMark Brown 		   struct sg_table *sgt, enum dma_data_direction dir)
9456ad45a27SMark Brown {
9466ad45a27SMark Brown 	if (sgt->orig_nents) {
9476ad45a27SMark Brown 		dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
9486ad45a27SMark Brown 		sg_free_table(sgt);
9496ad45a27SMark Brown 	}
9506ad45a27SMark Brown }
9516ad45a27SMark Brown 
9528caab75fSGeert Uytterhoeven static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
95399adef31SMark Brown {
95499adef31SMark Brown 	struct device *tx_dev, *rx_dev;
95599adef31SMark Brown 	struct spi_transfer *xfer;
9566ad45a27SMark Brown 	int ret;
9573a2eba9bSMark Brown 
9588caab75fSGeert Uytterhoeven 	if (!ctlr->can_dma)
95999adef31SMark Brown 		return 0;
96099adef31SMark Brown 
9618caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
9628caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
963c37f45b5SLeilk Liu 	else
9648caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
965c37f45b5SLeilk Liu 
9668caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
9678caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
968c37f45b5SLeilk Liu 	else
9698caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
97099adef31SMark Brown 
97199adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
9728caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
97399adef31SMark Brown 			continue;
97499adef31SMark Brown 
97599adef31SMark Brown 		if (xfer->tx_buf != NULL) {
9768caab75fSGeert Uytterhoeven 			ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
9776ad45a27SMark Brown 					  (void *)xfer->tx_buf, xfer->len,
97899adef31SMark Brown 					  DMA_TO_DEVICE);
9796ad45a27SMark Brown 			if (ret != 0)
9806ad45a27SMark Brown 				return ret;
98199adef31SMark Brown 		}
98299adef31SMark Brown 
98399adef31SMark Brown 		if (xfer->rx_buf != NULL) {
9848caab75fSGeert Uytterhoeven 			ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
98599adef31SMark Brown 					  xfer->rx_buf, xfer->len,
98699adef31SMark Brown 					  DMA_FROM_DEVICE);
9876ad45a27SMark Brown 			if (ret != 0) {
9888caab75fSGeert Uytterhoeven 				spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
9896ad45a27SMark Brown 					      DMA_TO_DEVICE);
9906ad45a27SMark Brown 				return ret;
99199adef31SMark Brown 			}
99299adef31SMark Brown 		}
99399adef31SMark Brown 	}
99499adef31SMark Brown 
9958caab75fSGeert Uytterhoeven 	ctlr->cur_msg_mapped = true;
99699adef31SMark Brown 
99799adef31SMark Brown 	return 0;
99899adef31SMark Brown }
99999adef31SMark Brown 
10008caab75fSGeert Uytterhoeven static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
100199adef31SMark Brown {
100299adef31SMark Brown 	struct spi_transfer *xfer;
100399adef31SMark Brown 	struct device *tx_dev, *rx_dev;
100499adef31SMark Brown 
10058caab75fSGeert Uytterhoeven 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
100699adef31SMark Brown 		return 0;
100799adef31SMark Brown 
10088caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
10098caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
1010c37f45b5SLeilk Liu 	else
10118caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
1012c37f45b5SLeilk Liu 
10138caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
10148caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
1015c37f45b5SLeilk Liu 	else
10168caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
101799adef31SMark Brown 
101899adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
10198caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
102099adef31SMark Brown 			continue;
102199adef31SMark Brown 
10228caab75fSGeert Uytterhoeven 		spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
10238caab75fSGeert Uytterhoeven 		spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
102499adef31SMark Brown 	}
102599adef31SMark Brown 
1026809b1b04SRobin Gong 	ctlr->cur_msg_mapped = false;
1027809b1b04SRobin Gong 
102899adef31SMark Brown 	return 0;
102999adef31SMark Brown }
10302de440f5SGeert Uytterhoeven #else /* !CONFIG_HAS_DMA */
10318caab75fSGeert Uytterhoeven static inline int __spi_map_msg(struct spi_controller *ctlr,
10322de440f5SGeert Uytterhoeven 				struct spi_message *msg)
10332de440f5SGeert Uytterhoeven {
10342de440f5SGeert Uytterhoeven 	return 0;
10352de440f5SGeert Uytterhoeven }
10362de440f5SGeert Uytterhoeven 
10378caab75fSGeert Uytterhoeven static inline int __spi_unmap_msg(struct spi_controller *ctlr,
10382de440f5SGeert Uytterhoeven 				  struct spi_message *msg)
10392de440f5SGeert Uytterhoeven {
10402de440f5SGeert Uytterhoeven 	return 0;
10412de440f5SGeert Uytterhoeven }
10422de440f5SGeert Uytterhoeven #endif /* !CONFIG_HAS_DMA */
10432de440f5SGeert Uytterhoeven 
10448caab75fSGeert Uytterhoeven static inline int spi_unmap_msg(struct spi_controller *ctlr,
10454b786458SMartin Sperl 				struct spi_message *msg)
10464b786458SMartin Sperl {
10474b786458SMartin Sperl 	struct spi_transfer *xfer;
10484b786458SMartin Sperl 
10494b786458SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
10504b786458SMartin Sperl 		/*
10514b786458SMartin Sperl 		 * Restore the original value of tx_buf or rx_buf if they are
10524b786458SMartin Sperl 		 * NULL.
10534b786458SMartin Sperl 		 */
10548caab75fSGeert Uytterhoeven 		if (xfer->tx_buf == ctlr->dummy_tx)
10554b786458SMartin Sperl 			xfer->tx_buf = NULL;
10568caab75fSGeert Uytterhoeven 		if (xfer->rx_buf == ctlr->dummy_rx)
10574b786458SMartin Sperl 			xfer->rx_buf = NULL;
10584b786458SMartin Sperl 	}
10594b786458SMartin Sperl 
10608caab75fSGeert Uytterhoeven 	return __spi_unmap_msg(ctlr, msg);
10614b786458SMartin Sperl }
10624b786458SMartin Sperl 
10638caab75fSGeert Uytterhoeven static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
10642de440f5SGeert Uytterhoeven {
10652de440f5SGeert Uytterhoeven 	struct spi_transfer *xfer;
10662de440f5SGeert Uytterhoeven 	void *tmp;
10672de440f5SGeert Uytterhoeven 	unsigned int max_tx, max_rx;
10682de440f5SGeert Uytterhoeven 
1069aee67fe8Sdillon min 	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1070aee67fe8Sdillon min 		&& !(msg->spi->mode & SPI_3WIRE)) {
10712de440f5SGeert Uytterhoeven 		max_tx = 0;
10722de440f5SGeert Uytterhoeven 		max_rx = 0;
10732de440f5SGeert Uytterhoeven 
10742de440f5SGeert Uytterhoeven 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
10758caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
10762de440f5SGeert Uytterhoeven 			    !xfer->tx_buf)
10772de440f5SGeert Uytterhoeven 				max_tx = max(xfer->len, max_tx);
10788caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
10792de440f5SGeert Uytterhoeven 			    !xfer->rx_buf)
10802de440f5SGeert Uytterhoeven 				max_rx = max(xfer->len, max_rx);
10812de440f5SGeert Uytterhoeven 		}
10822de440f5SGeert Uytterhoeven 
10832de440f5SGeert Uytterhoeven 		if (max_tx) {
10848caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_tx, max_tx,
10852de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
10862de440f5SGeert Uytterhoeven 			if (!tmp)
10872de440f5SGeert Uytterhoeven 				return -ENOMEM;
10888caab75fSGeert Uytterhoeven 			ctlr->dummy_tx = tmp;
10892de440f5SGeert Uytterhoeven 			memset(tmp, 0, max_tx);
10902de440f5SGeert Uytterhoeven 		}
10912de440f5SGeert Uytterhoeven 
10922de440f5SGeert Uytterhoeven 		if (max_rx) {
10938caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_rx, max_rx,
10942de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
10952de440f5SGeert Uytterhoeven 			if (!tmp)
10962de440f5SGeert Uytterhoeven 				return -ENOMEM;
10978caab75fSGeert Uytterhoeven 			ctlr->dummy_rx = tmp;
10982de440f5SGeert Uytterhoeven 		}
10992de440f5SGeert Uytterhoeven 
11002de440f5SGeert Uytterhoeven 		if (max_tx || max_rx) {
11012de440f5SGeert Uytterhoeven 			list_for_each_entry(xfer, &msg->transfers,
11022de440f5SGeert Uytterhoeven 					    transfer_list) {
11035442dcaaSChris Lesiak 				if (!xfer->len)
11045442dcaaSChris Lesiak 					continue;
11052de440f5SGeert Uytterhoeven 				if (!xfer->tx_buf)
11068caab75fSGeert Uytterhoeven 					xfer->tx_buf = ctlr->dummy_tx;
11072de440f5SGeert Uytterhoeven 				if (!xfer->rx_buf)
11088caab75fSGeert Uytterhoeven 					xfer->rx_buf = ctlr->dummy_rx;
11092de440f5SGeert Uytterhoeven 			}
11102de440f5SGeert Uytterhoeven 		}
11112de440f5SGeert Uytterhoeven 	}
11122de440f5SGeert Uytterhoeven 
11138caab75fSGeert Uytterhoeven 	return __spi_map_msg(ctlr, msg);
11142de440f5SGeert Uytterhoeven }
111599adef31SMark Brown 
1116810923f3SLubomir Rintel static int spi_transfer_wait(struct spi_controller *ctlr,
1117810923f3SLubomir Rintel 			     struct spi_message *msg,
1118810923f3SLubomir Rintel 			     struct spi_transfer *xfer)
1119810923f3SLubomir Rintel {
1120810923f3SLubomir Rintel 	struct spi_statistics *statm = &ctlr->statistics;
1121810923f3SLubomir Rintel 	struct spi_statistics *stats = &msg->spi->statistics;
11226170d077SXu Yilun 	u32 speed_hz = xfer->speed_hz;
112349686df5SColin Ian King 	unsigned long long ms;
1124810923f3SLubomir Rintel 
1125810923f3SLubomir Rintel 	if (spi_controller_is_slave(ctlr)) {
1126810923f3SLubomir Rintel 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1127810923f3SLubomir Rintel 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1128810923f3SLubomir Rintel 			return -EINTR;
1129810923f3SLubomir Rintel 		}
1130810923f3SLubomir Rintel 	} else {
11316170d077SXu Yilun 		if (!speed_hz)
11326170d077SXu Yilun 			speed_hz = 100000;
11336170d077SXu Yilun 
1134810923f3SLubomir Rintel 		ms = 8LL * 1000LL * xfer->len;
11356170d077SXu Yilun 		do_div(ms, speed_hz);
1136810923f3SLubomir Rintel 		ms += ms + 200; /* some tolerance */
1137810923f3SLubomir Rintel 
1138810923f3SLubomir Rintel 		if (ms > UINT_MAX)
1139810923f3SLubomir Rintel 			ms = UINT_MAX;
1140810923f3SLubomir Rintel 
1141810923f3SLubomir Rintel 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1142810923f3SLubomir Rintel 						 msecs_to_jiffies(ms));
1143810923f3SLubomir Rintel 
1144810923f3SLubomir Rintel 		if (ms == 0) {
1145810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1146810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1147810923f3SLubomir Rintel 			dev_err(&msg->spi->dev,
1148810923f3SLubomir Rintel 				"SPI transfer timed out\n");
1149810923f3SLubomir Rintel 			return -ETIMEDOUT;
1150810923f3SLubomir Rintel 		}
1151810923f3SLubomir Rintel 	}
1152810923f3SLubomir Rintel 
1153810923f3SLubomir Rintel 	return 0;
1154810923f3SLubomir Rintel }
1155810923f3SLubomir Rintel 
11560ff2de8bSMartin Sperl static void _spi_transfer_delay_ns(u32 ns)
11570ff2de8bSMartin Sperl {
11580ff2de8bSMartin Sperl 	if (!ns)
11590ff2de8bSMartin Sperl 		return;
11600ff2de8bSMartin Sperl 	if (ns <= 1000) {
11610ff2de8bSMartin Sperl 		ndelay(ns);
11620ff2de8bSMartin Sperl 	} else {
11630ff2de8bSMartin Sperl 		u32 us = DIV_ROUND_UP(ns, 1000);
11640ff2de8bSMartin Sperl 
11650ff2de8bSMartin Sperl 		if (us <= 10)
11660ff2de8bSMartin Sperl 			udelay(us);
11670ff2de8bSMartin Sperl 		else
11680ff2de8bSMartin Sperl 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
11690ff2de8bSMartin Sperl 	}
11700ff2de8bSMartin Sperl }
11710ff2de8bSMartin Sperl 
11723984d39bSAlexandru Ardelean int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
11730ff2de8bSMartin Sperl {
1174b2c98153SAlexandru Ardelean 	u32 delay = _delay->value;
1175b2c98153SAlexandru Ardelean 	u32 unit = _delay->unit;
1176d5864e5bSMartin Sperl 	u32 hz;
11770ff2de8bSMartin Sperl 
1178b2c98153SAlexandru Ardelean 	if (!delay)
1179b2c98153SAlexandru Ardelean 		return 0;
11800ff2de8bSMartin Sperl 
11810ff2de8bSMartin Sperl 	switch (unit) {
11820ff2de8bSMartin Sperl 	case SPI_DELAY_UNIT_USECS:
11830ff2de8bSMartin Sperl 		delay *= 1000;
11840ff2de8bSMartin Sperl 		break;
11850ff2de8bSMartin Sperl 	case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
11860ff2de8bSMartin Sperl 		break;
1187d5864e5bSMartin Sperl 	case SPI_DELAY_UNIT_SCK:
1188b2c98153SAlexandru Ardelean 		/* clock cycles need to be obtained from spi_transfer */
1189b2c98153SAlexandru Ardelean 		if (!xfer)
1190b2c98153SAlexandru Ardelean 			return -EINVAL;
1191d5864e5bSMartin Sperl 		/* if there is no effective speed know, then approximate
1192d5864e5bSMartin Sperl 		 * by underestimating with half the requested hz
1193d5864e5bSMartin Sperl 		 */
1194d5864e5bSMartin Sperl 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1195b2c98153SAlexandru Ardelean 		if (!hz)
1196b2c98153SAlexandru Ardelean 			return -EINVAL;
1197d5864e5bSMartin Sperl 		delay *= DIV_ROUND_UP(1000000000, hz);
1198d5864e5bSMartin Sperl 		break;
11990ff2de8bSMartin Sperl 	default:
1200b2c98153SAlexandru Ardelean 		return -EINVAL;
1201b2c98153SAlexandru Ardelean 	}
1202b2c98153SAlexandru Ardelean 
1203b2c98153SAlexandru Ardelean 	return delay;
1204b2c98153SAlexandru Ardelean }
12053984d39bSAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1206b2c98153SAlexandru Ardelean 
1207b2c98153SAlexandru Ardelean int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1208b2c98153SAlexandru Ardelean {
1209b2c98153SAlexandru Ardelean 	int delay;
1210b2c98153SAlexandru Ardelean 
12118fede89fSMark Brown 	might_sleep();
12128fede89fSMark Brown 
1213b2c98153SAlexandru Ardelean 	if (!_delay)
1214b2c98153SAlexandru Ardelean 		return -EINVAL;
1215b2c98153SAlexandru Ardelean 
12163984d39bSAlexandru Ardelean 	delay = spi_delay_to_ns(_delay, xfer);
1217b2c98153SAlexandru Ardelean 	if (delay < 0)
1218b2c98153SAlexandru Ardelean 		return delay;
1219b2c98153SAlexandru Ardelean 
1220b2c98153SAlexandru Ardelean 	_spi_transfer_delay_ns(delay);
1221b2c98153SAlexandru Ardelean 
1222b2c98153SAlexandru Ardelean 	return 0;
1223b2c98153SAlexandru Ardelean }
1224b2c98153SAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_exec);
1225b2c98153SAlexandru Ardelean 
12260ff2de8bSMartin Sperl static void _spi_transfer_cs_change_delay(struct spi_message *msg,
12270ff2de8bSMartin Sperl 					  struct spi_transfer *xfer)
12280ff2de8bSMartin Sperl {
1229329f0dacSAlexandru Ardelean 	u32 delay = xfer->cs_change_delay.value;
1230329f0dacSAlexandru Ardelean 	u32 unit = xfer->cs_change_delay.unit;
1231329f0dacSAlexandru Ardelean 	int ret;
12320ff2de8bSMartin Sperl 
12330ff2de8bSMartin Sperl 	/* return early on "fast" mode - for everything but USECS */
12346b3f236aSAlexandru Ardelean 	if (!delay) {
12356b3f236aSAlexandru Ardelean 		if (unit == SPI_DELAY_UNIT_USECS)
12366b3f236aSAlexandru Ardelean 			_spi_transfer_delay_ns(10000);
12370ff2de8bSMartin Sperl 		return;
12386b3f236aSAlexandru Ardelean 	}
12390ff2de8bSMartin Sperl 
1240329f0dacSAlexandru Ardelean 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1241329f0dacSAlexandru Ardelean 	if (ret) {
12420ff2de8bSMartin Sperl 		dev_err_once(&msg->spi->dev,
12430ff2de8bSMartin Sperl 			     "Use of unsupported delay unit %i, using default of 10us\n",
1244329f0dacSAlexandru Ardelean 			     unit);
1245329f0dacSAlexandru Ardelean 		_spi_transfer_delay_ns(10000);
12460ff2de8bSMartin Sperl 	}
12470ff2de8bSMartin Sperl }
12480ff2de8bSMartin Sperl 
1249b158935fSMark Brown /*
1250b158935fSMark Brown  * spi_transfer_one_message - Default implementation of transfer_one_message()
1251b158935fSMark Brown  *
1252b158935fSMark Brown  * This is a standard implementation of transfer_one_message() for
12538ba811a7SMoritz Fischer  * drivers which implement a transfer_one() operation.  It provides
1254b158935fSMark Brown  * standard handling of delays and chip select management.
1255b158935fSMark Brown  */
12568caab75fSGeert Uytterhoeven static int spi_transfer_one_message(struct spi_controller *ctlr,
1257b158935fSMark Brown 				    struct spi_message *msg)
1258b158935fSMark Brown {
1259b158935fSMark Brown 	struct spi_transfer *xfer;
1260b158935fSMark Brown 	bool keep_cs = false;
1261b158935fSMark Brown 	int ret = 0;
12628caab75fSGeert Uytterhoeven 	struct spi_statistics *statm = &ctlr->statistics;
1263eca2ebc7SMartin Sperl 	struct spi_statistics *stats = &msg->spi->statistics;
1264b158935fSMark Brown 
1265b158935fSMark Brown 	spi_set_cs(msg->spi, true);
1266b158935fSMark Brown 
1267eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1268eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1269eca2ebc7SMartin Sperl 
1270b158935fSMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1271b158935fSMark Brown 		trace_spi_transfer_start(msg, xfer);
1272b158935fSMark Brown 
12738caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
12748caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1275eca2ebc7SMartin Sperl 
1276b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1277b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1278b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1279b42faeeeSVladimir Oltean 		}
1280b42faeeeSVladimir Oltean 
1281b3063203SNicolas Saenz Julienne 		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
12828caab75fSGeert Uytterhoeven 			reinit_completion(&ctlr->xfer_completion);
1283b158935fSMark Brown 
1284809b1b04SRobin Gong fallback_pio:
12858caab75fSGeert Uytterhoeven 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1286b158935fSMark Brown 			if (ret < 0) {
1287809b1b04SRobin Gong 				if (ctlr->cur_msg_mapped &&
1288809b1b04SRobin Gong 				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1289809b1b04SRobin Gong 					__spi_unmap_msg(ctlr, msg);
1290809b1b04SRobin Gong 					ctlr->fallback = true;
1291809b1b04SRobin Gong 					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1292809b1b04SRobin Gong 					goto fallback_pio;
1293809b1b04SRobin Gong 				}
1294809b1b04SRobin Gong 
1295eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1296eca2ebc7SMartin Sperl 							       errors);
1297eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1298eca2ebc7SMartin Sperl 							       errors);
1299b158935fSMark Brown 				dev_err(&msg->spi->dev,
1300b158935fSMark Brown 					"SPI transfer failed: %d\n", ret);
1301b158935fSMark Brown 				goto out;
1302b158935fSMark Brown 			}
1303b158935fSMark Brown 
1304d57e7960SMark Brown 			if (ret > 0) {
1305810923f3SLubomir Rintel 				ret = spi_transfer_wait(ctlr, msg, xfer);
1306810923f3SLubomir Rintel 				if (ret < 0)
1307810923f3SLubomir Rintel 					msg->status = ret;
1308d57e7960SMark Brown 			}
130938ec10f6SMark Brown 		} else {
131038ec10f6SMark Brown 			if (xfer->len)
131138ec10f6SMark Brown 				dev_err(&msg->spi->dev,
131238ec10f6SMark Brown 					"Bufferless transfer has length %u\n",
131338ec10f6SMark Brown 					xfer->len);
131438ec10f6SMark Brown 		}
1315b158935fSMark Brown 
1316b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1317b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1318b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1319b42faeeeSVladimir Oltean 		}
1320b42faeeeSVladimir Oltean 
1321b158935fSMark Brown 		trace_spi_transfer_stop(msg, xfer);
1322b158935fSMark Brown 
1323b158935fSMark Brown 		if (msg->status != -EINPROGRESS)
1324b158935fSMark Brown 			goto out;
1325b158935fSMark Brown 
1326bebcfd27SAlexandru Ardelean 		spi_transfer_delay_exec(xfer);
1327b158935fSMark Brown 
1328b158935fSMark Brown 		if (xfer->cs_change) {
1329b158935fSMark Brown 			if (list_is_last(&xfer->transfer_list,
1330b158935fSMark Brown 					 &msg->transfers)) {
1331b158935fSMark Brown 				keep_cs = true;
1332b158935fSMark Brown 			} else {
13330b73aa63SMark Brown 				spi_set_cs(msg->spi, false);
13340ff2de8bSMartin Sperl 				_spi_transfer_cs_change_delay(msg, xfer);
13350b73aa63SMark Brown 				spi_set_cs(msg->spi, true);
1336b158935fSMark Brown 			}
1337b158935fSMark Brown 		}
1338b158935fSMark Brown 
1339b158935fSMark Brown 		msg->actual_length += xfer->len;
1340b158935fSMark Brown 	}
1341b158935fSMark Brown 
1342b158935fSMark Brown out:
1343b158935fSMark Brown 	if (ret != 0 || !keep_cs)
1344b158935fSMark Brown 		spi_set_cs(msg->spi, false);
1345b158935fSMark Brown 
1346b158935fSMark Brown 	if (msg->status == -EINPROGRESS)
1347b158935fSMark Brown 		msg->status = ret;
1348b158935fSMark Brown 
13498caab75fSGeert Uytterhoeven 	if (msg->status && ctlr->handle_err)
13508caab75fSGeert Uytterhoeven 		ctlr->handle_err(ctlr, msg);
1351b716c4ffSAndy Shevchenko 
13520ed56252SMark Brown 	spi_finalize_current_message(ctlr);
13530ed56252SMark Brown 
1354b158935fSMark Brown 	return ret;
1355b158935fSMark Brown }
1356b158935fSMark Brown 
1357b158935fSMark Brown /**
1358b158935fSMark Brown  * spi_finalize_current_transfer - report completion of a transfer
13598caab75fSGeert Uytterhoeven  * @ctlr: the controller reporting completion
1360b158935fSMark Brown  *
1361b158935fSMark Brown  * Called by SPI drivers using the core transfer_one_message()
1362b158935fSMark Brown  * implementation to notify it that the current interrupt driven
13639e8f4882SGeert Uytterhoeven  * transfer has finished and the next one may be scheduled.
1364b158935fSMark Brown  */
13658caab75fSGeert Uytterhoeven void spi_finalize_current_transfer(struct spi_controller *ctlr)
1366b158935fSMark Brown {
13678caab75fSGeert Uytterhoeven 	complete(&ctlr->xfer_completion);
1368b158935fSMark Brown }
1369b158935fSMark Brown EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1370b158935fSMark Brown 
1371e1268597SMark Brown static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1372e1268597SMark Brown {
1373e1268597SMark Brown 	if (ctlr->auto_runtime_pm) {
1374e1268597SMark Brown 		pm_runtime_mark_last_busy(ctlr->dev.parent);
1375e1268597SMark Brown 		pm_runtime_put_autosuspend(ctlr->dev.parent);
1376e1268597SMark Brown 	}
1377e1268597SMark Brown }
1378e1268597SMark Brown 
1379ffbbdd21SLinus Walleij /**
1380fc9e0f71SMark Brown  * __spi_pump_messages - function which processes spi message queue
13818caab75fSGeert Uytterhoeven  * @ctlr: controller to process queue for
1382fc9e0f71SMark Brown  * @in_kthread: true if we are in the context of the message pump thread
1383ffbbdd21SLinus Walleij  *
1384ffbbdd21SLinus Walleij  * This function checks if there is any spi message in the queue that
1385ffbbdd21SLinus Walleij  * needs processing and if so call out to the driver to initialize hardware
1386ffbbdd21SLinus Walleij  * and transfer each message.
1387ffbbdd21SLinus Walleij  *
13880461a414SMark Brown  * Note that it is called both from the kthread itself and also from
13890461a414SMark Brown  * inside spi_sync(); the queue extraction handling at the top of the
13900461a414SMark Brown  * function should deal with this safely.
1391ffbbdd21SLinus Walleij  */
13928caab75fSGeert Uytterhoeven static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1393ffbbdd21SLinus Walleij {
1394b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
1395d1c44c93SVladimir Oltean 	struct spi_message *msg;
1396ffbbdd21SLinus Walleij 	bool was_busy = false;
1397d1c44c93SVladimir Oltean 	unsigned long flags;
1398ffbbdd21SLinus Walleij 	int ret;
1399ffbbdd21SLinus Walleij 
1400983aee5dSMark Brown 	/* Lock queue */
14018caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1402983aee5dSMark Brown 
1403983aee5dSMark Brown 	/* Make sure we are not already running a message */
14048caab75fSGeert Uytterhoeven 	if (ctlr->cur_msg) {
14058caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1406983aee5dSMark Brown 		return;
1407983aee5dSMark Brown 	}
1408983aee5dSMark Brown 
1409f0125f1aSMark Brown 	/* If another context is idling the device then defer */
14108caab75fSGeert Uytterhoeven 	if (ctlr->idling) {
141160a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
14128caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
14130461a414SMark Brown 		return;
14140461a414SMark Brown 	}
14150461a414SMark Brown 
1416983aee5dSMark Brown 	/* Check if the queue is idle */
14178caab75fSGeert Uytterhoeven 	if (list_empty(&ctlr->queue) || !ctlr->running) {
14188caab75fSGeert Uytterhoeven 		if (!ctlr->busy) {
14198caab75fSGeert Uytterhoeven 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1420ffbbdd21SLinus Walleij 			return;
1421ffbbdd21SLinus Walleij 		}
1422fc9e0f71SMark Brown 
1423e1268597SMark Brown 		/* Defer any non-atomic teardown to the thread */
1424f0125f1aSMark Brown 		if (!in_kthread) {
1425e1268597SMark Brown 			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1426e1268597SMark Brown 			    !ctlr->unprepare_transfer_hardware) {
1427e1268597SMark Brown 				spi_idle_runtime_pm(ctlr);
1428e1268597SMark Brown 				ctlr->busy = false;
1429e1268597SMark Brown 				trace_spi_controller_idle(ctlr);
1430e1268597SMark Brown 			} else {
143160a883d1SMarek Szyprowski 				kthread_queue_work(ctlr->kworker,
1432f0125f1aSMark Brown 						   &ctlr->pump_messages);
1433e1268597SMark Brown 			}
1434f0125f1aSMark Brown 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1435f0125f1aSMark Brown 			return;
1436f0125f1aSMark Brown 		}
1437f0125f1aSMark Brown 
1438f0125f1aSMark Brown 		ctlr->busy = false;
1439f0125f1aSMark Brown 		ctlr->idling = true;
1440f0125f1aSMark Brown 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1441f0125f1aSMark Brown 
1442f0125f1aSMark Brown 		kfree(ctlr->dummy_rx);
1443f0125f1aSMark Brown 		ctlr->dummy_rx = NULL;
1444f0125f1aSMark Brown 		kfree(ctlr->dummy_tx);
1445f0125f1aSMark Brown 		ctlr->dummy_tx = NULL;
1446f0125f1aSMark Brown 		if (ctlr->unprepare_transfer_hardware &&
1447f0125f1aSMark Brown 		    ctlr->unprepare_transfer_hardware(ctlr))
1448f0125f1aSMark Brown 			dev_err(&ctlr->dev,
1449f0125f1aSMark Brown 				"failed to unprepare transfer hardware\n");
1450e1268597SMark Brown 		spi_idle_runtime_pm(ctlr);
1451f0125f1aSMark Brown 		trace_spi_controller_idle(ctlr);
1452f0125f1aSMark Brown 
1453f0125f1aSMark Brown 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1454f0125f1aSMark Brown 		ctlr->idling = false;
14558caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1456ffbbdd21SLinus Walleij 		return;
1457ffbbdd21SLinus Walleij 	}
1458ffbbdd21SLinus Walleij 
1459ffbbdd21SLinus Walleij 	/* Extract head of queue */
1460d1c44c93SVladimir Oltean 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1461d1c44c93SVladimir Oltean 	ctlr->cur_msg = msg;
1462ffbbdd21SLinus Walleij 
1463d1c44c93SVladimir Oltean 	list_del_init(&msg->queue);
14648caab75fSGeert Uytterhoeven 	if (ctlr->busy)
1465ffbbdd21SLinus Walleij 		was_busy = true;
1466ffbbdd21SLinus Walleij 	else
14678caab75fSGeert Uytterhoeven 		ctlr->busy = true;
14688caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1469ffbbdd21SLinus Walleij 
14708caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->io_mutex);
1471ef4d96ecSMark Brown 
14728caab75fSGeert Uytterhoeven 	if (!was_busy && ctlr->auto_runtime_pm) {
14738caab75fSGeert Uytterhoeven 		ret = pm_runtime_get_sync(ctlr->dev.parent);
147449834de2SMark Brown 		if (ret < 0) {
14757e48e23aSTony Lindgren 			pm_runtime_put_noidle(ctlr->dev.parent);
14768caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
147749834de2SMark Brown 				ret);
14788caab75fSGeert Uytterhoeven 			mutex_unlock(&ctlr->io_mutex);
147949834de2SMark Brown 			return;
148049834de2SMark Brown 		}
148149834de2SMark Brown 	}
148249834de2SMark Brown 
148356ec1978SMark Brown 	if (!was_busy)
14848caab75fSGeert Uytterhoeven 		trace_spi_controller_busy(ctlr);
148556ec1978SMark Brown 
14868caab75fSGeert Uytterhoeven 	if (!was_busy && ctlr->prepare_transfer_hardware) {
14878caab75fSGeert Uytterhoeven 		ret = ctlr->prepare_transfer_hardware(ctlr);
1488ffbbdd21SLinus Walleij 		if (ret) {
14898caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev,
1490f3440d9aSSuper Liu 				"failed to prepare transfer hardware: %d\n",
1491f3440d9aSSuper Liu 				ret);
149249834de2SMark Brown 
14938caab75fSGeert Uytterhoeven 			if (ctlr->auto_runtime_pm)
14948caab75fSGeert Uytterhoeven 				pm_runtime_put(ctlr->dev.parent);
1495f3440d9aSSuper Liu 
1496d1c44c93SVladimir Oltean 			msg->status = ret;
1497f3440d9aSSuper Liu 			spi_finalize_current_message(ctlr);
1498f3440d9aSSuper Liu 
14998caab75fSGeert Uytterhoeven 			mutex_unlock(&ctlr->io_mutex);
1500ffbbdd21SLinus Walleij 			return;
1501ffbbdd21SLinus Walleij 		}
1502ffbbdd21SLinus Walleij 	}
1503ffbbdd21SLinus Walleij 
1504d1c44c93SVladimir Oltean 	trace_spi_message_start(msg);
150556ec1978SMark Brown 
15068caab75fSGeert Uytterhoeven 	if (ctlr->prepare_message) {
1507d1c44c93SVladimir Oltean 		ret = ctlr->prepare_message(ctlr, msg);
15082841a5fcSMark Brown 		if (ret) {
15098caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
15108caab75fSGeert Uytterhoeven 				ret);
1511d1c44c93SVladimir Oltean 			msg->status = ret;
15128caab75fSGeert Uytterhoeven 			spi_finalize_current_message(ctlr);
151349023d2eSJon Hunter 			goto out;
15142841a5fcSMark Brown 		}
15158caab75fSGeert Uytterhoeven 		ctlr->cur_msg_prepared = true;
15162841a5fcSMark Brown 	}
15172841a5fcSMark Brown 
1518d1c44c93SVladimir Oltean 	ret = spi_map_msg(ctlr, msg);
151999adef31SMark Brown 	if (ret) {
1520d1c44c93SVladimir Oltean 		msg->status = ret;
15218caab75fSGeert Uytterhoeven 		spi_finalize_current_message(ctlr);
152249023d2eSJon Hunter 		goto out;
152399adef31SMark Brown 	}
152499adef31SMark Brown 
1525b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1526b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1527b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1528b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1529b42faeeeSVladimir Oltean 		}
1530b42faeeeSVladimir Oltean 	}
1531b42faeeeSVladimir Oltean 
1532d1c44c93SVladimir Oltean 	ret = ctlr->transfer_one_message(ctlr, msg);
1533ffbbdd21SLinus Walleij 	if (ret) {
15348caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev,
15351f802f82SGeert Uytterhoeven 			"failed to transfer one message from queue\n");
153649023d2eSJon Hunter 		goto out;
1537ffbbdd21SLinus Walleij 	}
153849023d2eSJon Hunter 
153949023d2eSJon Hunter out:
15408caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->io_mutex);
154162826970SMark Brown 
154262826970SMark Brown 	/* Prod the scheduler in case transfer_one() was busy waiting */
154349023d2eSJon Hunter 	if (!ret)
154462826970SMark Brown 		cond_resched();
1545ffbbdd21SLinus Walleij }
1546ffbbdd21SLinus Walleij 
1547fc9e0f71SMark Brown /**
1548fc9e0f71SMark Brown  * spi_pump_messages - kthread work function which processes spi message queue
15498caab75fSGeert Uytterhoeven  * @work: pointer to kthread work struct contained in the controller struct
1550fc9e0f71SMark Brown  */
1551fc9e0f71SMark Brown static void spi_pump_messages(struct kthread_work *work)
1552fc9e0f71SMark Brown {
15538caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr =
15548caab75fSGeert Uytterhoeven 		container_of(work, struct spi_controller, pump_messages);
1555fc9e0f71SMark Brown 
15568caab75fSGeert Uytterhoeven 	__spi_pump_messages(ctlr, true);
1557fc9e0f71SMark Brown }
1558fc9e0f71SMark Brown 
1559924b5867SDouglas Anderson /**
1560b42faeeeSVladimir Oltean  * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1561b42faeeeSVladimir Oltean  *			    TX timestamp for the requested byte from the SPI
1562b42faeeeSVladimir Oltean  *			    transfer. The frequency with which this function
1563b42faeeeSVladimir Oltean  *			    must be called (once per word, once for the whole
1564b42faeeeSVladimir Oltean  *			    transfer, once per batch of words etc) is arbitrary
1565b42faeeeSVladimir Oltean  *			    as long as the @tx buffer offset is greater than or
1566b42faeeeSVladimir Oltean  *			    equal to the requested byte at the time of the
1567b42faeeeSVladimir Oltean  *			    call. The timestamp is only taken once, at the
1568b42faeeeSVladimir Oltean  *			    first such call. It is assumed that the driver
1569b42faeeeSVladimir Oltean  *			    advances its @tx buffer pointer monotonically.
1570b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1571b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1572862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1573b42faeeeSVladimir Oltean  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1574b42faeeeSVladimir Oltean  *	      transfer, for less jitter in time measurement. Only compatible
1575b42faeeeSVladimir Oltean  *	      with PIO drivers. If true, must follow up with
1576b42faeeeSVladimir Oltean  *	      spi_take_timestamp_post or otherwise system will crash.
1577b42faeeeSVladimir Oltean  *	      WARNING: for fully predictable results, the CPU frequency must
1578b42faeeeSVladimir Oltean  *	      also be under control (governor).
1579b42faeeeSVladimir Oltean  */
1580b42faeeeSVladimir Oltean void spi_take_timestamp_pre(struct spi_controller *ctlr,
1581b42faeeeSVladimir Oltean 			    struct spi_transfer *xfer,
1582862dd2a9SVladimir Oltean 			    size_t progress, bool irqs_off)
1583b42faeeeSVladimir Oltean {
1584b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1585b42faeeeSVladimir Oltean 		return;
1586b42faeeeSVladimir Oltean 
15876a726824SVladimir Oltean 	if (xfer->timestamped)
1588b42faeeeSVladimir Oltean 		return;
1589b42faeeeSVladimir Oltean 
15906a726824SVladimir Oltean 	if (progress > xfer->ptp_sts_word_pre)
1591b42faeeeSVladimir Oltean 		return;
1592b42faeeeSVladimir Oltean 
1593b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1594862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_pre = progress;
1595b42faeeeSVladimir Oltean 
1596b42faeeeSVladimir Oltean 	if (irqs_off) {
1597b42faeeeSVladimir Oltean 		local_irq_save(ctlr->irq_flags);
1598b42faeeeSVladimir Oltean 		preempt_disable();
1599b42faeeeSVladimir Oltean 	}
1600b42faeeeSVladimir Oltean 
1601b42faeeeSVladimir Oltean 	ptp_read_system_prets(xfer->ptp_sts);
1602b42faeeeSVladimir Oltean }
1603b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1604b42faeeeSVladimir Oltean 
1605b42faeeeSVladimir Oltean /**
1606b42faeeeSVladimir Oltean  * spi_take_timestamp_post - helper for drivers to collect the end of the
1607b42faeeeSVladimir Oltean  *			     TX timestamp for the requested byte from the SPI
1608b42faeeeSVladimir Oltean  *			     transfer. Can be called with an arbitrary
1609b42faeeeSVladimir Oltean  *			     frequency: only the first call where @tx exceeds
1610b42faeeeSVladimir Oltean  *			     or is equal to the requested word will be
1611b42faeeeSVladimir Oltean  *			     timestamped.
1612b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1613b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1614862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1615b42faeeeSVladimir Oltean  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1616b42faeeeSVladimir Oltean  */
1617b42faeeeSVladimir Oltean void spi_take_timestamp_post(struct spi_controller *ctlr,
1618b42faeeeSVladimir Oltean 			     struct spi_transfer *xfer,
1619862dd2a9SVladimir Oltean 			     size_t progress, bool irqs_off)
1620b42faeeeSVladimir Oltean {
1621b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1622b42faeeeSVladimir Oltean 		return;
1623b42faeeeSVladimir Oltean 
16246a726824SVladimir Oltean 	if (xfer->timestamped)
1625b42faeeeSVladimir Oltean 		return;
1626b42faeeeSVladimir Oltean 
1627862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_post)
1628b42faeeeSVladimir Oltean 		return;
1629b42faeeeSVladimir Oltean 
1630b42faeeeSVladimir Oltean 	ptp_read_system_postts(xfer->ptp_sts);
1631b42faeeeSVladimir Oltean 
1632b42faeeeSVladimir Oltean 	if (irqs_off) {
1633b42faeeeSVladimir Oltean 		local_irq_restore(ctlr->irq_flags);
1634b42faeeeSVladimir Oltean 		preempt_enable();
1635b42faeeeSVladimir Oltean 	}
1636b42faeeeSVladimir Oltean 
1637b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1638862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_post = progress;
1639b42faeeeSVladimir Oltean 
16406a726824SVladimir Oltean 	xfer->timestamped = true;
1641b42faeeeSVladimir Oltean }
1642b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1643b42faeeeSVladimir Oltean 
1644b42faeeeSVladimir Oltean /**
1645924b5867SDouglas Anderson  * spi_set_thread_rt - set the controller to pump at realtime priority
1646924b5867SDouglas Anderson  * @ctlr: controller to boost priority of
1647924b5867SDouglas Anderson  *
1648924b5867SDouglas Anderson  * This can be called because the controller requested realtime priority
1649924b5867SDouglas Anderson  * (by setting the ->rt value before calling spi_register_controller()) or
1650924b5867SDouglas Anderson  * because a device on the bus said that its transfers needed realtime
1651924b5867SDouglas Anderson  * priority.
1652924b5867SDouglas Anderson  *
1653924b5867SDouglas Anderson  * NOTE: at the moment if any device on a bus says it needs realtime then
1654924b5867SDouglas Anderson  * the thread will be at realtime priority for all transfers on that
1655924b5867SDouglas Anderson  * controller.  If this eventually becomes a problem we may see if we can
1656924b5867SDouglas Anderson  * find a way to boost the priority only temporarily during relevant
1657924b5867SDouglas Anderson  * transfers.
1658924b5867SDouglas Anderson  */
1659924b5867SDouglas Anderson static void spi_set_thread_rt(struct spi_controller *ctlr)
1660ffbbdd21SLinus Walleij {
1661924b5867SDouglas Anderson 	dev_info(&ctlr->dev,
1662924b5867SDouglas Anderson 		"will run message pump with realtime priority\n");
16636d2b84a4SLinus Torvalds 	sched_set_fifo(ctlr->kworker->task);
1664924b5867SDouglas Anderson }
1665924b5867SDouglas Anderson 
1666924b5867SDouglas Anderson static int spi_init_queue(struct spi_controller *ctlr)
1667924b5867SDouglas Anderson {
16688caab75fSGeert Uytterhoeven 	ctlr->running = false;
16698caab75fSGeert Uytterhoeven 	ctlr->busy = false;
1670ffbbdd21SLinus Walleij 
167160a883d1SMarek Szyprowski 	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
167260a883d1SMarek Szyprowski 	if (IS_ERR(ctlr->kworker)) {
167360a883d1SMarek Szyprowski 		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
167460a883d1SMarek Szyprowski 		return PTR_ERR(ctlr->kworker);
1675ffbbdd21SLinus Walleij 	}
167660a883d1SMarek Szyprowski 
16778caab75fSGeert Uytterhoeven 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1678f0125f1aSMark Brown 
1679ffbbdd21SLinus Walleij 	/*
16808caab75fSGeert Uytterhoeven 	 * Controller config will indicate if this controller should run the
1681ffbbdd21SLinus Walleij 	 * message pump with high (realtime) priority to reduce the transfer
1682ffbbdd21SLinus Walleij 	 * latency on the bus by minimising the delay between a transfer
1683ffbbdd21SLinus Walleij 	 * request and the scheduling of the message pump thread. Without this
1684ffbbdd21SLinus Walleij 	 * setting the message pump thread will remain at default priority.
1685ffbbdd21SLinus Walleij 	 */
1686924b5867SDouglas Anderson 	if (ctlr->rt)
1687924b5867SDouglas Anderson 		spi_set_thread_rt(ctlr);
1688ffbbdd21SLinus Walleij 
1689ffbbdd21SLinus Walleij 	return 0;
1690ffbbdd21SLinus Walleij }
1691ffbbdd21SLinus Walleij 
1692ffbbdd21SLinus Walleij /**
1693ffbbdd21SLinus Walleij  * spi_get_next_queued_message() - called by driver to check for queued
1694ffbbdd21SLinus Walleij  * messages
16958caab75fSGeert Uytterhoeven  * @ctlr: the controller to check for queued messages
1696ffbbdd21SLinus Walleij  *
1697ffbbdd21SLinus Walleij  * If there are more messages in the queue, the next message is returned from
1698ffbbdd21SLinus Walleij  * this call.
169997d56dc6SJavier Martinez Canillas  *
170097d56dc6SJavier Martinez Canillas  * Return: the next message in the queue, else NULL if the queue is empty.
1701ffbbdd21SLinus Walleij  */
17028caab75fSGeert Uytterhoeven struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1703ffbbdd21SLinus Walleij {
1704ffbbdd21SLinus Walleij 	struct spi_message *next;
1705ffbbdd21SLinus Walleij 	unsigned long flags;
1706ffbbdd21SLinus Walleij 
1707ffbbdd21SLinus Walleij 	/* get a pointer to the next message, if any */
17088caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
17098caab75fSGeert Uytterhoeven 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
17101cfd97f9SAxel Lin 					queue);
17118caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1712ffbbdd21SLinus Walleij 
1713ffbbdd21SLinus Walleij 	return next;
1714ffbbdd21SLinus Walleij }
1715ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1716ffbbdd21SLinus Walleij 
1717ffbbdd21SLinus Walleij /**
1718ffbbdd21SLinus Walleij  * spi_finalize_current_message() - the current message is complete
17198caab75fSGeert Uytterhoeven  * @ctlr: the controller to return the message to
1720ffbbdd21SLinus Walleij  *
1721ffbbdd21SLinus Walleij  * Called by the driver to notify the core that the message in the front of the
1722ffbbdd21SLinus Walleij  * queue is complete and can be removed from the queue.
1723ffbbdd21SLinus Walleij  */
17248caab75fSGeert Uytterhoeven void spi_finalize_current_message(struct spi_controller *ctlr)
1725ffbbdd21SLinus Walleij {
1726b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
1727ffbbdd21SLinus Walleij 	struct spi_message *mesg;
1728ffbbdd21SLinus Walleij 	unsigned long flags;
17292841a5fcSMark Brown 	int ret;
1730ffbbdd21SLinus Walleij 
17318caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
17328caab75fSGeert Uytterhoeven 	mesg = ctlr->cur_msg;
17338caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1734ffbbdd21SLinus Walleij 
1735b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1736b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1737b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1738b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1739b42faeeeSVladimir Oltean 		}
1740b42faeeeSVladimir Oltean 	}
1741b42faeeeSVladimir Oltean 
17426a726824SVladimir Oltean 	if (unlikely(ctlr->ptp_sts_supported))
17436a726824SVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
17446a726824SVladimir Oltean 			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1745f971a207SVladimir Oltean 
17468caab75fSGeert Uytterhoeven 	spi_unmap_msg(ctlr, mesg);
174799adef31SMark Brown 
1748b59a7ca1SGustav Wiklander 	/* In the prepare_messages callback the spi bus has the opportunity to
1749b59a7ca1SGustav Wiklander 	 * split a transfer to smaller chunks.
1750b59a7ca1SGustav Wiklander 	 * Release splited transfers here since spi_map_msg is done on the
1751b59a7ca1SGustav Wiklander 	 * splited transfers.
1752b59a7ca1SGustav Wiklander 	 */
1753b59a7ca1SGustav Wiklander 	spi_res_release(ctlr, mesg);
1754b59a7ca1SGustav Wiklander 
17558caab75fSGeert Uytterhoeven 	if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
17568caab75fSGeert Uytterhoeven 		ret = ctlr->unprepare_message(ctlr, mesg);
17572841a5fcSMark Brown 		if (ret) {
17588caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
17598caab75fSGeert Uytterhoeven 				ret);
17602841a5fcSMark Brown 		}
17612841a5fcSMark Brown 	}
1762391949b6SUwe Kleine-König 
17638caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
17648caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
17658caab75fSGeert Uytterhoeven 	ctlr->cur_msg_prepared = false;
1766809b1b04SRobin Gong 	ctlr->fallback = false;
176760a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
17688caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
17698e76ef88SMartin Sperl 
17708e76ef88SMartin Sperl 	trace_spi_message_done(mesg);
17712841a5fcSMark Brown 
1772ffbbdd21SLinus Walleij 	mesg->state = NULL;
1773ffbbdd21SLinus Walleij 	if (mesg->complete)
1774ffbbdd21SLinus Walleij 		mesg->complete(mesg->context);
1775ffbbdd21SLinus Walleij }
1776ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1777ffbbdd21SLinus Walleij 
17788caab75fSGeert Uytterhoeven static int spi_start_queue(struct spi_controller *ctlr)
1779ffbbdd21SLinus Walleij {
1780ffbbdd21SLinus Walleij 	unsigned long flags;
1781ffbbdd21SLinus Walleij 
17828caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1783ffbbdd21SLinus Walleij 
17848caab75fSGeert Uytterhoeven 	if (ctlr->running || ctlr->busy) {
17858caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1786ffbbdd21SLinus Walleij 		return -EBUSY;
1787ffbbdd21SLinus Walleij 	}
1788ffbbdd21SLinus Walleij 
17898caab75fSGeert Uytterhoeven 	ctlr->running = true;
17908caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
17918caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1792ffbbdd21SLinus Walleij 
179360a883d1SMarek Szyprowski 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1794ffbbdd21SLinus Walleij 
1795ffbbdd21SLinus Walleij 	return 0;
1796ffbbdd21SLinus Walleij }
1797ffbbdd21SLinus Walleij 
17988caab75fSGeert Uytterhoeven static int spi_stop_queue(struct spi_controller *ctlr)
1799ffbbdd21SLinus Walleij {
1800ffbbdd21SLinus Walleij 	unsigned long flags;
1801ffbbdd21SLinus Walleij 	unsigned limit = 500;
1802ffbbdd21SLinus Walleij 	int ret = 0;
1803ffbbdd21SLinus Walleij 
18048caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1805ffbbdd21SLinus Walleij 
1806ffbbdd21SLinus Walleij 	/*
1807ffbbdd21SLinus Walleij 	 * This is a bit lame, but is optimized for the common execution path.
18088caab75fSGeert Uytterhoeven 	 * A wait_queue on the ctlr->busy could be used, but then the common
1809ffbbdd21SLinus Walleij 	 * execution path (pump_messages) would be required to call wake_up or
1810ffbbdd21SLinus Walleij 	 * friends on every SPI message. Do this instead.
1811ffbbdd21SLinus Walleij 	 */
18128caab75fSGeert Uytterhoeven 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
18138caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1814f97b26b0SAxel Lin 		usleep_range(10000, 11000);
18158caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1816ffbbdd21SLinus Walleij 	}
1817ffbbdd21SLinus Walleij 
18188caab75fSGeert Uytterhoeven 	if (!list_empty(&ctlr->queue) || ctlr->busy)
1819ffbbdd21SLinus Walleij 		ret = -EBUSY;
1820ffbbdd21SLinus Walleij 	else
18218caab75fSGeert Uytterhoeven 		ctlr->running = false;
1822ffbbdd21SLinus Walleij 
18238caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1824ffbbdd21SLinus Walleij 
1825ffbbdd21SLinus Walleij 	if (ret) {
18268caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "could not stop message queue\n");
1827ffbbdd21SLinus Walleij 		return ret;
1828ffbbdd21SLinus Walleij 	}
1829ffbbdd21SLinus Walleij 	return ret;
1830ffbbdd21SLinus Walleij }
1831ffbbdd21SLinus Walleij 
18328caab75fSGeert Uytterhoeven static int spi_destroy_queue(struct spi_controller *ctlr)
1833ffbbdd21SLinus Walleij {
1834ffbbdd21SLinus Walleij 	int ret;
1835ffbbdd21SLinus Walleij 
18368caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
1837ffbbdd21SLinus Walleij 
1838ffbbdd21SLinus Walleij 	/*
18393989144fSPetr Mladek 	 * kthread_flush_worker will block until all work is done.
1840ffbbdd21SLinus Walleij 	 * If the reason that stop_queue timed out is that the work will never
1841ffbbdd21SLinus Walleij 	 * finish, then it does no good to call flush/stop thread, so
1842ffbbdd21SLinus Walleij 	 * return anyway.
1843ffbbdd21SLinus Walleij 	 */
1844ffbbdd21SLinus Walleij 	if (ret) {
18458caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem destroying queue\n");
1846ffbbdd21SLinus Walleij 		return ret;
1847ffbbdd21SLinus Walleij 	}
1848ffbbdd21SLinus Walleij 
184960a883d1SMarek Szyprowski 	kthread_destroy_worker(ctlr->kworker);
1850ffbbdd21SLinus Walleij 
1851ffbbdd21SLinus Walleij 	return 0;
1852ffbbdd21SLinus Walleij }
1853ffbbdd21SLinus Walleij 
18540461a414SMark Brown static int __spi_queued_transfer(struct spi_device *spi,
18550461a414SMark Brown 				 struct spi_message *msg,
18560461a414SMark Brown 				 bool need_pump)
1857ffbbdd21SLinus Walleij {
18588caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
1859ffbbdd21SLinus Walleij 	unsigned long flags;
1860ffbbdd21SLinus Walleij 
18618caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1862ffbbdd21SLinus Walleij 
18638caab75fSGeert Uytterhoeven 	if (!ctlr->running) {
18648caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1865ffbbdd21SLinus Walleij 		return -ESHUTDOWN;
1866ffbbdd21SLinus Walleij 	}
1867ffbbdd21SLinus Walleij 	msg->actual_length = 0;
1868ffbbdd21SLinus Walleij 	msg->status = -EINPROGRESS;
1869ffbbdd21SLinus Walleij 
18708caab75fSGeert Uytterhoeven 	list_add_tail(&msg->queue, &ctlr->queue);
1871f0125f1aSMark Brown 	if (!ctlr->busy && need_pump)
187260a883d1SMarek Szyprowski 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1873ffbbdd21SLinus Walleij 
18748caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1875ffbbdd21SLinus Walleij 	return 0;
1876ffbbdd21SLinus Walleij }
1877ffbbdd21SLinus Walleij 
18780461a414SMark Brown /**
18790461a414SMark Brown  * spi_queued_transfer - transfer function for queued transfers
18800461a414SMark Brown  * @spi: spi device which is requesting transfer
18810461a414SMark Brown  * @msg: spi message which is to handled is queued to driver queue
188297d56dc6SJavier Martinez Canillas  *
188397d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
18840461a414SMark Brown  */
18850461a414SMark Brown static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
18860461a414SMark Brown {
18870461a414SMark Brown 	return __spi_queued_transfer(spi, msg, true);
18880461a414SMark Brown }
18890461a414SMark Brown 
18908caab75fSGeert Uytterhoeven static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1891ffbbdd21SLinus Walleij {
1892ffbbdd21SLinus Walleij 	int ret;
1893ffbbdd21SLinus Walleij 
18948caab75fSGeert Uytterhoeven 	ctlr->transfer = spi_queued_transfer;
18958caab75fSGeert Uytterhoeven 	if (!ctlr->transfer_one_message)
18968caab75fSGeert Uytterhoeven 		ctlr->transfer_one_message = spi_transfer_one_message;
1897ffbbdd21SLinus Walleij 
1898ffbbdd21SLinus Walleij 	/* Initialize and start queue */
18998caab75fSGeert Uytterhoeven 	ret = spi_init_queue(ctlr);
1900ffbbdd21SLinus Walleij 	if (ret) {
19018caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem initializing queue\n");
1902ffbbdd21SLinus Walleij 		goto err_init_queue;
1903ffbbdd21SLinus Walleij 	}
19048caab75fSGeert Uytterhoeven 	ctlr->queued = true;
19058caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
1906ffbbdd21SLinus Walleij 	if (ret) {
19078caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem starting queue\n");
1908ffbbdd21SLinus Walleij 		goto err_start_queue;
1909ffbbdd21SLinus Walleij 	}
1910ffbbdd21SLinus Walleij 
1911ffbbdd21SLinus Walleij 	return 0;
1912ffbbdd21SLinus Walleij 
1913ffbbdd21SLinus Walleij err_start_queue:
19148caab75fSGeert Uytterhoeven 	spi_destroy_queue(ctlr);
1915c3676d5cSMark Brown err_init_queue:
1916ffbbdd21SLinus Walleij 	return ret;
1917ffbbdd21SLinus Walleij }
1918ffbbdd21SLinus Walleij 
1919988f259bSBoris Brezillon /**
1920988f259bSBoris Brezillon  * spi_flush_queue - Send all pending messages in the queue from the callers'
1921988f259bSBoris Brezillon  *		     context
1922988f259bSBoris Brezillon  * @ctlr: controller to process queue for
1923988f259bSBoris Brezillon  *
1924988f259bSBoris Brezillon  * This should be used when one wants to ensure all pending messages have been
1925988f259bSBoris Brezillon  * sent before doing something. Is used by the spi-mem code to make sure SPI
1926988f259bSBoris Brezillon  * memory operations do not preempt regular SPI transfers that have been queued
1927988f259bSBoris Brezillon  * before the spi-mem operation.
1928988f259bSBoris Brezillon  */
1929988f259bSBoris Brezillon void spi_flush_queue(struct spi_controller *ctlr)
1930988f259bSBoris Brezillon {
1931988f259bSBoris Brezillon 	if (ctlr->transfer == spi_queued_transfer)
1932988f259bSBoris Brezillon 		__spi_pump_messages(ctlr, false);
1933988f259bSBoris Brezillon }
1934988f259bSBoris Brezillon 
1935ffbbdd21SLinus Walleij /*-------------------------------------------------------------------------*/
1936ffbbdd21SLinus Walleij 
19377cb94361SAndreas Larsson #if defined(CONFIG_OF)
19388caab75fSGeert Uytterhoeven static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1939c2e51ac3SGeert Uytterhoeven 			   struct device_node *nc)
1940d57a4282SGrant Likely {
194189da4293STrent Piepho 	u32 value;
1942c2e51ac3SGeert Uytterhoeven 	int rc;
1943d57a4282SGrant Likely 
1944d57a4282SGrant Likely 	/* Mode (clock phase/polarity/etc.) */
1945e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpha"))
1946d57a4282SGrant Likely 		spi->mode |= SPI_CPHA;
1947e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpol"))
1948d57a4282SGrant Likely 		spi->mode |= SPI_CPOL;
1949e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-3wire"))
1950c20151dfSLars-Peter Clausen 		spi->mode |= SPI_3WIRE;
1951e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-lsb-first"))
1952cd6339e6SZhao Qiang 		spi->mode |= SPI_LSB_FIRST;
19533e5ec1dbSGregory CLEMENT 	if (of_property_read_bool(nc, "spi-cs-high"))
1954f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
1955f3186dd8SLinus Walleij 
1956f477b7fbSwangyuhang 	/* Device DUAL/QUAD mode */
195789da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
195889da4293STrent Piepho 		switch (value) {
1959d962608cSDragos Bogdan 		case 0:
1960d962608cSDragos Bogdan 			spi->mode |= SPI_NO_TX;
1961d962608cSDragos Bogdan 			break;
196289da4293STrent Piepho 		case 1:
1963f477b7fbSwangyuhang 			break;
196489da4293STrent Piepho 		case 2:
1965f477b7fbSwangyuhang 			spi->mode |= SPI_TX_DUAL;
1966f477b7fbSwangyuhang 			break;
196789da4293STrent Piepho 		case 4:
1968f477b7fbSwangyuhang 			spi->mode |= SPI_TX_QUAD;
1969f477b7fbSwangyuhang 			break;
19706b03061fSYogesh Narayan Gaur 		case 8:
19716b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_TX_OCTAL;
19726b03061fSYogesh Narayan Gaur 			break;
1973f477b7fbSwangyuhang 		default:
19748caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
1975a110f93dSwangyuhang 				"spi-tx-bus-width %d not supported\n",
197689da4293STrent Piepho 				value);
197780874d8cSGeert Uytterhoeven 			break;
1978f477b7fbSwangyuhang 		}
1979a822e99cSMark Brown 	}
1980f477b7fbSwangyuhang 
198189da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
198289da4293STrent Piepho 		switch (value) {
1983d962608cSDragos Bogdan 		case 0:
1984d962608cSDragos Bogdan 			spi->mode |= SPI_NO_RX;
1985d962608cSDragos Bogdan 			break;
198689da4293STrent Piepho 		case 1:
1987f477b7fbSwangyuhang 			break;
198889da4293STrent Piepho 		case 2:
1989f477b7fbSwangyuhang 			spi->mode |= SPI_RX_DUAL;
1990f477b7fbSwangyuhang 			break;
199189da4293STrent Piepho 		case 4:
1992f477b7fbSwangyuhang 			spi->mode |= SPI_RX_QUAD;
1993f477b7fbSwangyuhang 			break;
19946b03061fSYogesh Narayan Gaur 		case 8:
19956b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_RX_OCTAL;
19966b03061fSYogesh Narayan Gaur 			break;
1997f477b7fbSwangyuhang 		default:
19988caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
1999a110f93dSwangyuhang 				"spi-rx-bus-width %d not supported\n",
200089da4293STrent Piepho 				value);
200180874d8cSGeert Uytterhoeven 			break;
2002f477b7fbSwangyuhang 		}
2003a822e99cSMark Brown 	}
2004f477b7fbSwangyuhang 
20058caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr)) {
2006194276b0SRob Herring 		if (!of_node_name_eq(nc, "slave")) {
200725c56c88SRob Herring 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
200825c56c88SRob Herring 				nc);
20096c364062SGeert Uytterhoeven 			return -EINVAL;
20106c364062SGeert Uytterhoeven 		}
20116c364062SGeert Uytterhoeven 		return 0;
20126c364062SGeert Uytterhoeven 	}
20136c364062SGeert Uytterhoeven 
20146c364062SGeert Uytterhoeven 	/* Device address */
20156c364062SGeert Uytterhoeven 	rc = of_property_read_u32(nc, "reg", &value);
20166c364062SGeert Uytterhoeven 	if (rc) {
201725c56c88SRob Herring 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
201825c56c88SRob Herring 			nc, rc);
20196c364062SGeert Uytterhoeven 		return rc;
20206c364062SGeert Uytterhoeven 	}
20216c364062SGeert Uytterhoeven 	spi->chip_select = value;
20226c364062SGeert Uytterhoeven 
2023d57a4282SGrant Likely 	/* Device speed */
2024671c3bf5SChuanhong Guo 	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
202589da4293STrent Piepho 		spi->max_speed_hz = value;
2026d57a4282SGrant Likely 
2027c2e51ac3SGeert Uytterhoeven 	return 0;
2028c2e51ac3SGeert Uytterhoeven }
2029c2e51ac3SGeert Uytterhoeven 
2030c2e51ac3SGeert Uytterhoeven static struct spi_device *
20318caab75fSGeert Uytterhoeven of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2032c2e51ac3SGeert Uytterhoeven {
2033c2e51ac3SGeert Uytterhoeven 	struct spi_device *spi;
2034c2e51ac3SGeert Uytterhoeven 	int rc;
2035c2e51ac3SGeert Uytterhoeven 
2036c2e51ac3SGeert Uytterhoeven 	/* Alloc an spi_device */
20378caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
2038c2e51ac3SGeert Uytterhoeven 	if (!spi) {
203925c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2040c2e51ac3SGeert Uytterhoeven 		rc = -ENOMEM;
2041c2e51ac3SGeert Uytterhoeven 		goto err_out;
2042c2e51ac3SGeert Uytterhoeven 	}
2043c2e51ac3SGeert Uytterhoeven 
2044c2e51ac3SGeert Uytterhoeven 	/* Select device driver */
2045c2e51ac3SGeert Uytterhoeven 	rc = of_modalias_node(nc, spi->modalias,
2046c2e51ac3SGeert Uytterhoeven 				sizeof(spi->modalias));
2047c2e51ac3SGeert Uytterhoeven 	if (rc < 0) {
204825c56c88SRob Herring 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2049c2e51ac3SGeert Uytterhoeven 		goto err_out;
2050c2e51ac3SGeert Uytterhoeven 	}
2051c2e51ac3SGeert Uytterhoeven 
20528caab75fSGeert Uytterhoeven 	rc = of_spi_parse_dt(ctlr, spi, nc);
2053c2e51ac3SGeert Uytterhoeven 	if (rc)
2054c2e51ac3SGeert Uytterhoeven 		goto err_out;
2055c2e51ac3SGeert Uytterhoeven 
2056d57a4282SGrant Likely 	/* Store a pointer to the node in the device structure */
2057d57a4282SGrant Likely 	of_node_get(nc);
2058d57a4282SGrant Likely 	spi->dev.of_node = nc;
2059d57a4282SGrant Likely 
2060d57a4282SGrant Likely 	/* Register the new device */
2061d57a4282SGrant Likely 	rc = spi_add_device(spi);
2062d57a4282SGrant Likely 	if (rc) {
206325c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
20648324147fSJohan Hovold 		goto err_of_node_put;
2065d57a4282SGrant Likely 	}
2066d57a4282SGrant Likely 
2067aff5e3f8SPantelis Antoniou 	return spi;
2068aff5e3f8SPantelis Antoniou 
20698324147fSJohan Hovold err_of_node_put:
20708324147fSJohan Hovold 	of_node_put(nc);
2071aff5e3f8SPantelis Antoniou err_out:
2072aff5e3f8SPantelis Antoniou 	spi_dev_put(spi);
2073aff5e3f8SPantelis Antoniou 	return ERR_PTR(rc);
2074aff5e3f8SPantelis Antoniou }
2075aff5e3f8SPantelis Antoniou 
2076aff5e3f8SPantelis Antoniou /**
2077aff5e3f8SPantelis Antoniou  * of_register_spi_devices() - Register child devices onto the SPI bus
20788caab75fSGeert Uytterhoeven  * @ctlr:	Pointer to spi_controller device
2079aff5e3f8SPantelis Antoniou  *
20806c364062SGeert Uytterhoeven  * Registers an spi_device for each child node of controller node which
20816c364062SGeert Uytterhoeven  * represents a valid SPI slave.
2082aff5e3f8SPantelis Antoniou  */
20838caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr)
2084aff5e3f8SPantelis Antoniou {
2085aff5e3f8SPantelis Antoniou 	struct spi_device *spi;
2086aff5e3f8SPantelis Antoniou 	struct device_node *nc;
2087aff5e3f8SPantelis Antoniou 
20888caab75fSGeert Uytterhoeven 	if (!ctlr->dev.of_node)
2089aff5e3f8SPantelis Antoniou 		return;
2090aff5e3f8SPantelis Antoniou 
20918caab75fSGeert Uytterhoeven 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2092bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2093bd6c1644SGeert Uytterhoeven 			continue;
20948caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, nc);
2095e0af98a7SRalf Ramsauer 		if (IS_ERR(spi)) {
20968caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
209725c56c88SRob Herring 				 "Failed to create SPI device for %pOF\n", nc);
2098e0af98a7SRalf Ramsauer 			of_node_clear_flag(nc, OF_POPULATED);
2099e0af98a7SRalf Ramsauer 		}
2100d57a4282SGrant Likely 	}
2101d57a4282SGrant Likely }
2102d57a4282SGrant Likely #else
21038caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr) { }
2104d57a4282SGrant Likely #endif
2105d57a4282SGrant Likely 
210664bee4d2SMika Westerberg #ifdef CONFIG_ACPI
21074c3c5954SArd Biesheuvel struct acpi_spi_lookup {
21084c3c5954SArd Biesheuvel 	struct spi_controller 	*ctlr;
21094c3c5954SArd Biesheuvel 	u32			max_speed_hz;
21104c3c5954SArd Biesheuvel 	u32			mode;
21114c3c5954SArd Biesheuvel 	int			irq;
21124c3c5954SArd Biesheuvel 	u8			bits_per_word;
21134c3c5954SArd Biesheuvel 	u8			chip_select;
21144c3c5954SArd Biesheuvel };
21154c3c5954SArd Biesheuvel 
21164c3c5954SArd Biesheuvel static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
21174c3c5954SArd Biesheuvel 					    struct acpi_spi_lookup *lookup)
21188a2e487eSLukas Wunner {
21198a2e487eSLukas Wunner 	const union acpi_object *obj;
21208a2e487eSLukas Wunner 
21218a2e487eSLukas Wunner 	if (!x86_apple_machine)
21228a2e487eSLukas Wunner 		return;
21238a2e487eSLukas Wunner 
21248a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
21258a2e487eSLukas Wunner 	    && obj->buffer.length >= 4)
21264c3c5954SArd Biesheuvel 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
21278a2e487eSLukas Wunner 
21288a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
21298a2e487eSLukas Wunner 	    && obj->buffer.length == 8)
21304c3c5954SArd Biesheuvel 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
21318a2e487eSLukas Wunner 
21328a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
21338a2e487eSLukas Wunner 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
21344c3c5954SArd Biesheuvel 		lookup->mode |= SPI_LSB_FIRST;
21358a2e487eSLukas Wunner 
21368a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
21378a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
21384c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPOL;
21398a2e487eSLukas Wunner 
21408a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
21418a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
21424c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPHA;
21438a2e487eSLukas Wunner }
21448a2e487eSLukas Wunner 
214564bee4d2SMika Westerberg static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
214664bee4d2SMika Westerberg {
21474c3c5954SArd Biesheuvel 	struct acpi_spi_lookup *lookup = data;
21484c3c5954SArd Biesheuvel 	struct spi_controller *ctlr = lookup->ctlr;
214964bee4d2SMika Westerberg 
215064bee4d2SMika Westerberg 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
215164bee4d2SMika Westerberg 		struct acpi_resource_spi_serialbus *sb;
21524c3c5954SArd Biesheuvel 		acpi_handle parent_handle;
21534c3c5954SArd Biesheuvel 		acpi_status status;
215464bee4d2SMika Westerberg 
215564bee4d2SMika Westerberg 		sb = &ares->data.spi_serial_bus;
215664bee4d2SMika Westerberg 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
21574c3c5954SArd Biesheuvel 
21584c3c5954SArd Biesheuvel 			status = acpi_get_handle(NULL,
21594c3c5954SArd Biesheuvel 						 sb->resource_source.string_ptr,
21604c3c5954SArd Biesheuvel 						 &parent_handle);
21614c3c5954SArd Biesheuvel 
2162b5e3cf41SArd Biesheuvel 			if (ACPI_FAILURE(status) ||
21634c3c5954SArd Biesheuvel 			    ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
21644c3c5954SArd Biesheuvel 				return -ENODEV;
21654c3c5954SArd Biesheuvel 
2166a0a90718SMika Westerberg 			/*
2167a0a90718SMika Westerberg 			 * ACPI DeviceSelection numbering is handled by the
2168a0a90718SMika Westerberg 			 * host controller driver in Windows and can vary
2169a0a90718SMika Westerberg 			 * from driver to driver. In Linux we always expect
2170a0a90718SMika Westerberg 			 * 0 .. max - 1 so we need to ask the driver to
2171a0a90718SMika Westerberg 			 * translate between the two schemes.
2172a0a90718SMika Westerberg 			 */
21738caab75fSGeert Uytterhoeven 			if (ctlr->fw_translate_cs) {
21748caab75fSGeert Uytterhoeven 				int cs = ctlr->fw_translate_cs(ctlr,
2175a0a90718SMika Westerberg 						sb->device_selection);
2176a0a90718SMika Westerberg 				if (cs < 0)
2177a0a90718SMika Westerberg 					return cs;
21784c3c5954SArd Biesheuvel 				lookup->chip_select = cs;
2179a0a90718SMika Westerberg 			} else {
21804c3c5954SArd Biesheuvel 				lookup->chip_select = sb->device_selection;
2181a0a90718SMika Westerberg 			}
2182a0a90718SMika Westerberg 
21834c3c5954SArd Biesheuvel 			lookup->max_speed_hz = sb->connection_speed;
21840dadde34SAndy Shevchenko 			lookup->bits_per_word = sb->data_bit_length;
218564bee4d2SMika Westerberg 
218664bee4d2SMika Westerberg 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
21874c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPHA;
218864bee4d2SMika Westerberg 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
21894c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPOL;
219064bee4d2SMika Westerberg 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
21914c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CS_HIGH;
219264bee4d2SMika Westerberg 		}
21934c3c5954SArd Biesheuvel 	} else if (lookup->irq < 0) {
219464bee4d2SMika Westerberg 		struct resource r;
219564bee4d2SMika Westerberg 
219664bee4d2SMika Westerberg 		if (acpi_dev_resource_interrupt(ares, 0, &r))
21974c3c5954SArd Biesheuvel 			lookup->irq = r.start;
219864bee4d2SMika Westerberg 	}
219964bee4d2SMika Westerberg 
220064bee4d2SMika Westerberg 	/* Always tell the ACPI core to skip this resource */
220164bee4d2SMika Westerberg 	return 1;
220264bee4d2SMika Westerberg }
220364bee4d2SMika Westerberg 
22048caab75fSGeert Uytterhoeven static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
22057f24467fSOctavian Purdila 					    struct acpi_device *adev)
220664bee4d2SMika Westerberg {
22074c3c5954SArd Biesheuvel 	acpi_handle parent_handle = NULL;
220864bee4d2SMika Westerberg 	struct list_head resource_list;
2209b28944c6SArd Biesheuvel 	struct acpi_spi_lookup lookup = {};
221064bee4d2SMika Westerberg 	struct spi_device *spi;
221164bee4d2SMika Westerberg 	int ret;
221264bee4d2SMika Westerberg 
22137f24467fSOctavian Purdila 	if (acpi_bus_get_status(adev) || !adev->status.present ||
22147f24467fSOctavian Purdila 	    acpi_device_enumerated(adev))
221564bee4d2SMika Westerberg 		return AE_OK;
221664bee4d2SMika Westerberg 
22174c3c5954SArd Biesheuvel 	lookup.ctlr		= ctlr;
22184c3c5954SArd Biesheuvel 	lookup.irq		= -1;
22194c3c5954SArd Biesheuvel 
22204c3c5954SArd Biesheuvel 	INIT_LIST_HEAD(&resource_list);
22214c3c5954SArd Biesheuvel 	ret = acpi_dev_get_resources(adev, &resource_list,
22224c3c5954SArd Biesheuvel 				     acpi_spi_add_resource, &lookup);
22234c3c5954SArd Biesheuvel 	acpi_dev_free_resource_list(&resource_list);
22244c3c5954SArd Biesheuvel 
22254c3c5954SArd Biesheuvel 	if (ret < 0)
22264c3c5954SArd Biesheuvel 		/* found SPI in _CRS but it points to another controller */
22274c3c5954SArd Biesheuvel 		return AE_OK;
22284c3c5954SArd Biesheuvel 
22294c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz &&
223010e92724SBjorn Helgaas 	    ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
22314c3c5954SArd Biesheuvel 	    ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
22324c3c5954SArd Biesheuvel 		/* Apple does not use _CRS but nested devices for SPI slaves */
22334c3c5954SArd Biesheuvel 		acpi_spi_parse_apple_properties(adev, &lookup);
22344c3c5954SArd Biesheuvel 	}
22354c3c5954SArd Biesheuvel 
22364c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz)
22374c3c5954SArd Biesheuvel 		return AE_OK;
22384c3c5954SArd Biesheuvel 
22398caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
224064bee4d2SMika Westerberg 	if (!spi) {
22418caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
224264bee4d2SMika Westerberg 			dev_name(&adev->dev));
224364bee4d2SMika Westerberg 		return AE_NO_MEMORY;
224464bee4d2SMika Westerberg 	}
224564bee4d2SMika Westerberg 
2246ea235786SJohn Garry 
22477b199811SRafael J. Wysocki 	ACPI_COMPANION_SET(&spi->dev, adev);
22484c3c5954SArd Biesheuvel 	spi->max_speed_hz	= lookup.max_speed_hz;
2249ea235786SJohn Garry 	spi->mode		|= lookup.mode;
22504c3c5954SArd Biesheuvel 	spi->irq		= lookup.irq;
22514c3c5954SArd Biesheuvel 	spi->bits_per_word	= lookup.bits_per_word;
22524c3c5954SArd Biesheuvel 	spi->chip_select	= lookup.chip_select;
225364bee4d2SMika Westerberg 
22540c6543f6SDan O'Donovan 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
22550c6543f6SDan O'Donovan 			  sizeof(spi->modalias));
22560c6543f6SDan O'Donovan 
225733ada67dSChristophe RICARD 	if (spi->irq < 0)
225833ada67dSChristophe RICARD 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
225933ada67dSChristophe RICARD 
22607f24467fSOctavian Purdila 	acpi_device_set_enumerated(adev);
22617f24467fSOctavian Purdila 
226233cf00e5SMika Westerberg 	adev->power.flags.ignore_parent = true;
226364bee4d2SMika Westerberg 	if (spi_add_device(spi)) {
226433cf00e5SMika Westerberg 		adev->power.flags.ignore_parent = false;
22658caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
226664bee4d2SMika Westerberg 			dev_name(&adev->dev));
226764bee4d2SMika Westerberg 		spi_dev_put(spi);
226864bee4d2SMika Westerberg 	}
226964bee4d2SMika Westerberg 
227064bee4d2SMika Westerberg 	return AE_OK;
227164bee4d2SMika Westerberg }
227264bee4d2SMika Westerberg 
22737f24467fSOctavian Purdila static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
22747f24467fSOctavian Purdila 				       void *data, void **return_value)
22757f24467fSOctavian Purdila {
22768caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = data;
22777f24467fSOctavian Purdila 	struct acpi_device *adev;
22787f24467fSOctavian Purdila 
22797f24467fSOctavian Purdila 	if (acpi_bus_get_device(handle, &adev))
22807f24467fSOctavian Purdila 		return AE_OK;
22817f24467fSOctavian Purdila 
22828caab75fSGeert Uytterhoeven 	return acpi_register_spi_device(ctlr, adev);
22837f24467fSOctavian Purdila }
22847f24467fSOctavian Purdila 
22854c3c5954SArd Biesheuvel #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
22864c3c5954SArd Biesheuvel 
22878caab75fSGeert Uytterhoeven static void acpi_register_spi_devices(struct spi_controller *ctlr)
228864bee4d2SMika Westerberg {
228964bee4d2SMika Westerberg 	acpi_status status;
229064bee4d2SMika Westerberg 	acpi_handle handle;
229164bee4d2SMika Westerberg 
22928caab75fSGeert Uytterhoeven 	handle = ACPI_HANDLE(ctlr->dev.parent);
229364bee4d2SMika Westerberg 	if (!handle)
229464bee4d2SMika Westerberg 		return;
229564bee4d2SMika Westerberg 
22964c3c5954SArd Biesheuvel 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
22974c3c5954SArd Biesheuvel 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
22988caab75fSGeert Uytterhoeven 				     acpi_spi_add_device, NULL, ctlr, NULL);
229964bee4d2SMika Westerberg 	if (ACPI_FAILURE(status))
23008caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
230164bee4d2SMika Westerberg }
230264bee4d2SMika Westerberg #else
23038caab75fSGeert Uytterhoeven static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
230464bee4d2SMika Westerberg #endif /* CONFIG_ACPI */
230564bee4d2SMika Westerberg 
23068caab75fSGeert Uytterhoeven static void spi_controller_release(struct device *dev)
23078ae12a0dSDavid Brownell {
23088caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
23098ae12a0dSDavid Brownell 
23108caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
23118caab75fSGeert Uytterhoeven 	kfree(ctlr);
23128ae12a0dSDavid Brownell }
23138ae12a0dSDavid Brownell 
23148ae12a0dSDavid Brownell static struct class spi_master_class = {
23158ae12a0dSDavid Brownell 	.name		= "spi_master",
23168ae12a0dSDavid Brownell 	.owner		= THIS_MODULE,
23178caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
2318eca2ebc7SMartin Sperl 	.dev_groups	= spi_master_groups,
23198ae12a0dSDavid Brownell };
23208ae12a0dSDavid Brownell 
23216c364062SGeert Uytterhoeven #ifdef CONFIG_SPI_SLAVE
23226c364062SGeert Uytterhoeven /**
23236c364062SGeert Uytterhoeven  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
23246c364062SGeert Uytterhoeven  *		     controller
23256c364062SGeert Uytterhoeven  * @spi: device used for the current transfer
23266c364062SGeert Uytterhoeven  */
23276c364062SGeert Uytterhoeven int spi_slave_abort(struct spi_device *spi)
23286c364062SGeert Uytterhoeven {
23298caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
23306c364062SGeert Uytterhoeven 
23318caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
23328caab75fSGeert Uytterhoeven 		return ctlr->slave_abort(ctlr);
23336c364062SGeert Uytterhoeven 
23346c364062SGeert Uytterhoeven 	return -ENOTSUPP;
23356c364062SGeert Uytterhoeven }
23366c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_slave_abort);
23376c364062SGeert Uytterhoeven 
23386c364062SGeert Uytterhoeven static int match_true(struct device *dev, void *data)
23396c364062SGeert Uytterhoeven {
23406c364062SGeert Uytterhoeven 	return 1;
23416c364062SGeert Uytterhoeven }
23426c364062SGeert Uytterhoeven 
2343cc8b4659SGeert Uytterhoeven static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2344cc8b4659SGeert Uytterhoeven 			  char *buf)
23456c364062SGeert Uytterhoeven {
23468caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
23478caab75fSGeert Uytterhoeven 						   dev);
23486c364062SGeert Uytterhoeven 	struct device *child;
23496c364062SGeert Uytterhoeven 
23506c364062SGeert Uytterhoeven 	child = device_find_child(&ctlr->dev, NULL, match_true);
23516c364062SGeert Uytterhoeven 	return sprintf(buf, "%s\n",
23526c364062SGeert Uytterhoeven 		       child ? to_spi_device(child)->modalias : NULL);
23536c364062SGeert Uytterhoeven }
23546c364062SGeert Uytterhoeven 
2355cc8b4659SGeert Uytterhoeven static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2356cc8b4659SGeert Uytterhoeven 			   const char *buf, size_t count)
23576c364062SGeert Uytterhoeven {
23588caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
23598caab75fSGeert Uytterhoeven 						   dev);
23606c364062SGeert Uytterhoeven 	struct spi_device *spi;
23616c364062SGeert Uytterhoeven 	struct device *child;
23626c364062SGeert Uytterhoeven 	char name[32];
23636c364062SGeert Uytterhoeven 	int rc;
23646c364062SGeert Uytterhoeven 
23656c364062SGeert Uytterhoeven 	rc = sscanf(buf, "%31s", name);
23666c364062SGeert Uytterhoeven 	if (rc != 1 || !name[0])
23676c364062SGeert Uytterhoeven 		return -EINVAL;
23686c364062SGeert Uytterhoeven 
23696c364062SGeert Uytterhoeven 	child = device_find_child(&ctlr->dev, NULL, match_true);
23706c364062SGeert Uytterhoeven 	if (child) {
23716c364062SGeert Uytterhoeven 		/* Remove registered slave */
23726c364062SGeert Uytterhoeven 		device_unregister(child);
23736c364062SGeert Uytterhoeven 		put_device(child);
23746c364062SGeert Uytterhoeven 	}
23756c364062SGeert Uytterhoeven 
23766c364062SGeert Uytterhoeven 	if (strcmp(name, "(null)")) {
23776c364062SGeert Uytterhoeven 		/* Register new slave */
23786c364062SGeert Uytterhoeven 		spi = spi_alloc_device(ctlr);
23796c364062SGeert Uytterhoeven 		if (!spi)
23806c364062SGeert Uytterhoeven 			return -ENOMEM;
23816c364062SGeert Uytterhoeven 
23826c364062SGeert Uytterhoeven 		strlcpy(spi->modalias, name, sizeof(spi->modalias));
23836c364062SGeert Uytterhoeven 
23846c364062SGeert Uytterhoeven 		rc = spi_add_device(spi);
23856c364062SGeert Uytterhoeven 		if (rc) {
23866c364062SGeert Uytterhoeven 			spi_dev_put(spi);
23876c364062SGeert Uytterhoeven 			return rc;
23886c364062SGeert Uytterhoeven 		}
23896c364062SGeert Uytterhoeven 	}
23906c364062SGeert Uytterhoeven 
23916c364062SGeert Uytterhoeven 	return count;
23926c364062SGeert Uytterhoeven }
23936c364062SGeert Uytterhoeven 
2394cc8b4659SGeert Uytterhoeven static DEVICE_ATTR_RW(slave);
23956c364062SGeert Uytterhoeven 
23966c364062SGeert Uytterhoeven static struct attribute *spi_slave_attrs[] = {
23976c364062SGeert Uytterhoeven 	&dev_attr_slave.attr,
23986c364062SGeert Uytterhoeven 	NULL,
23996c364062SGeert Uytterhoeven };
24006c364062SGeert Uytterhoeven 
24016c364062SGeert Uytterhoeven static const struct attribute_group spi_slave_group = {
24026c364062SGeert Uytterhoeven 	.attrs = spi_slave_attrs,
24036c364062SGeert Uytterhoeven };
24046c364062SGeert Uytterhoeven 
24056c364062SGeert Uytterhoeven static const struct attribute_group *spi_slave_groups[] = {
24068caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
24076c364062SGeert Uytterhoeven 	&spi_slave_group,
24086c364062SGeert Uytterhoeven 	NULL,
24096c364062SGeert Uytterhoeven };
24106c364062SGeert Uytterhoeven 
24116c364062SGeert Uytterhoeven static struct class spi_slave_class = {
24126c364062SGeert Uytterhoeven 	.name		= "spi_slave",
24136c364062SGeert Uytterhoeven 	.owner		= THIS_MODULE,
24148caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
24156c364062SGeert Uytterhoeven 	.dev_groups	= spi_slave_groups,
24166c364062SGeert Uytterhoeven };
24176c364062SGeert Uytterhoeven #else
24186c364062SGeert Uytterhoeven extern struct class spi_slave_class;	/* dummy */
24196c364062SGeert Uytterhoeven #endif
24208ae12a0dSDavid Brownell 
24218ae12a0dSDavid Brownell /**
24226c364062SGeert Uytterhoeven  * __spi_alloc_controller - allocate an SPI master or slave controller
24238ae12a0dSDavid Brownell  * @dev: the controller, possibly using the platform_bus
242433e34dc6SDavid Brownell  * @size: how much zeroed driver-private data to allocate; the pointer to this
2425229e6af1SLukas Wunner  *	memory is in the driver_data field of the returned device, accessible
2426229e6af1SLukas Wunner  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2427229e6af1SLukas Wunner  *	drivers granting DMA access to portions of their private data need to
2428229e6af1SLukas Wunner  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
24296c364062SGeert Uytterhoeven  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
24306c364062SGeert Uytterhoeven  *	slave (true) controller
243133e34dc6SDavid Brownell  * Context: can sleep
24328ae12a0dSDavid Brownell  *
24336c364062SGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
24348ae12a0dSDavid Brownell  * only ones directly touching chip registers.  It's how they allocate
24358caab75fSGeert Uytterhoeven  * an spi_controller structure, prior to calling spi_register_controller().
24368ae12a0dSDavid Brownell  *
243797d56dc6SJavier Martinez Canillas  * This must be called from context that can sleep.
24388ae12a0dSDavid Brownell  *
24396c364062SGeert Uytterhoeven  * The caller is responsible for assigning the bus number and initializing the
24408caab75fSGeert Uytterhoeven  * controller's methods before calling spi_register_controller(); and (after
24418caab75fSGeert Uytterhoeven  * errors adding the device) calling spi_controller_put() to prevent a memory
24428caab75fSGeert Uytterhoeven  * leak.
244397d56dc6SJavier Martinez Canillas  *
24446c364062SGeert Uytterhoeven  * Return: the SPI controller structure on success, else NULL.
24458ae12a0dSDavid Brownell  */
24468caab75fSGeert Uytterhoeven struct spi_controller *__spi_alloc_controller(struct device *dev,
24476c364062SGeert Uytterhoeven 					      unsigned int size, bool slave)
24488ae12a0dSDavid Brownell {
24498caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr;
2450229e6af1SLukas Wunner 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
24518ae12a0dSDavid Brownell 
24520c868461SDavid Brownell 	if (!dev)
24530c868461SDavid Brownell 		return NULL;
24540c868461SDavid Brownell 
2455229e6af1SLukas Wunner 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
24568caab75fSGeert Uytterhoeven 	if (!ctlr)
24578ae12a0dSDavid Brownell 		return NULL;
24588ae12a0dSDavid Brownell 
24598caab75fSGeert Uytterhoeven 	device_initialize(&ctlr->dev);
24608caab75fSGeert Uytterhoeven 	ctlr->bus_num = -1;
24618caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = 1;
24628caab75fSGeert Uytterhoeven 	ctlr->slave = slave;
24636c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
24648caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_slave_class;
24656c364062SGeert Uytterhoeven 	else
24668caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_master_class;
24678caab75fSGeert Uytterhoeven 	ctlr->dev.parent = dev;
24688caab75fSGeert Uytterhoeven 	pm_suspend_ignore_children(&ctlr->dev, true);
2469229e6af1SLukas Wunner 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
24708ae12a0dSDavid Brownell 
24718caab75fSGeert Uytterhoeven 	return ctlr;
24728ae12a0dSDavid Brownell }
24736c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(__spi_alloc_controller);
24748ae12a0dSDavid Brownell 
24755e844cc3SLukas Wunner static void devm_spi_release_controller(struct device *dev, void *ctlr)
24765e844cc3SLukas Wunner {
24775e844cc3SLukas Wunner 	spi_controller_put(*(struct spi_controller **)ctlr);
24785e844cc3SLukas Wunner }
24795e844cc3SLukas Wunner 
24805e844cc3SLukas Wunner /**
24815e844cc3SLukas Wunner  * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
24825e844cc3SLukas Wunner  * @dev: physical device of SPI controller
24835e844cc3SLukas Wunner  * @size: how much zeroed driver-private data to allocate
24845e844cc3SLukas Wunner  * @slave: whether to allocate an SPI master (false) or SPI slave (true)
24855e844cc3SLukas Wunner  * Context: can sleep
24865e844cc3SLukas Wunner  *
24875e844cc3SLukas Wunner  * Allocate an SPI controller and automatically release a reference on it
24885e844cc3SLukas Wunner  * when @dev is unbound from its driver.  Drivers are thus relieved from
24895e844cc3SLukas Wunner  * having to call spi_controller_put().
24905e844cc3SLukas Wunner  *
24915e844cc3SLukas Wunner  * The arguments to this function are identical to __spi_alloc_controller().
24925e844cc3SLukas Wunner  *
24935e844cc3SLukas Wunner  * Return: the SPI controller structure on success, else NULL.
24945e844cc3SLukas Wunner  */
24955e844cc3SLukas Wunner struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
24965e844cc3SLukas Wunner 						   unsigned int size,
24975e844cc3SLukas Wunner 						   bool slave)
24985e844cc3SLukas Wunner {
24995e844cc3SLukas Wunner 	struct spi_controller **ptr, *ctlr;
25005e844cc3SLukas Wunner 
25015e844cc3SLukas Wunner 	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
25025e844cc3SLukas Wunner 			   GFP_KERNEL);
25035e844cc3SLukas Wunner 	if (!ptr)
25045e844cc3SLukas Wunner 		return NULL;
25055e844cc3SLukas Wunner 
25065e844cc3SLukas Wunner 	ctlr = __spi_alloc_controller(dev, size, slave);
25075e844cc3SLukas Wunner 	if (ctlr) {
25085e844cc3SLukas Wunner 		*ptr = ctlr;
25095e844cc3SLukas Wunner 		devres_add(dev, ptr);
25105e844cc3SLukas Wunner 	} else {
25115e844cc3SLukas Wunner 		devres_free(ptr);
25125e844cc3SLukas Wunner 	}
25135e844cc3SLukas Wunner 
25145e844cc3SLukas Wunner 	return ctlr;
25155e844cc3SLukas Wunner }
25165e844cc3SLukas Wunner EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
25175e844cc3SLukas Wunner 
251874317984SJean-Christophe PLAGNIOL-VILLARD #ifdef CONFIG_OF
251943004f31SLinus Walleij static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
252074317984SJean-Christophe PLAGNIOL-VILLARD {
2521e80beb27SGrant Likely 	int nb, i, *cs;
25228caab75fSGeert Uytterhoeven 	struct device_node *np = ctlr->dev.of_node;
252374317984SJean-Christophe PLAGNIOL-VILLARD 
252474317984SJean-Christophe PLAGNIOL-VILLARD 	if (!np)
252574317984SJean-Christophe PLAGNIOL-VILLARD 		return 0;
252674317984SJean-Christophe PLAGNIOL-VILLARD 
252774317984SJean-Christophe PLAGNIOL-VILLARD 	nb = of_gpio_named_count(np, "cs-gpios");
25288caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
252974317984SJean-Christophe PLAGNIOL-VILLARD 
25308ec5d84eSAndreas Larsson 	/* Return error only for an incorrectly formed cs-gpios property */
25318ec5d84eSAndreas Larsson 	if (nb == 0 || nb == -ENOENT)
253274317984SJean-Christophe PLAGNIOL-VILLARD 		return 0;
25338ec5d84eSAndreas Larsson 	else if (nb < 0)
25348ec5d84eSAndreas Larsson 		return nb;
253574317984SJean-Christophe PLAGNIOL-VILLARD 
2536a86854d0SKees Cook 	cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
253774317984SJean-Christophe PLAGNIOL-VILLARD 			  GFP_KERNEL);
25388caab75fSGeert Uytterhoeven 	ctlr->cs_gpios = cs;
253974317984SJean-Christophe PLAGNIOL-VILLARD 
25408caab75fSGeert Uytterhoeven 	if (!ctlr->cs_gpios)
254174317984SJean-Christophe PLAGNIOL-VILLARD 		return -ENOMEM;
254274317984SJean-Christophe PLAGNIOL-VILLARD 
25438caab75fSGeert Uytterhoeven 	for (i = 0; i < ctlr->num_chipselect; i++)
2544446411e1SAndreas Larsson 		cs[i] = -ENOENT;
254574317984SJean-Christophe PLAGNIOL-VILLARD 
254674317984SJean-Christophe PLAGNIOL-VILLARD 	for (i = 0; i < nb; i++)
254774317984SJean-Christophe PLAGNIOL-VILLARD 		cs[i] = of_get_named_gpio(np, "cs-gpios", i);
254874317984SJean-Christophe PLAGNIOL-VILLARD 
254974317984SJean-Christophe PLAGNIOL-VILLARD 	return 0;
255074317984SJean-Christophe PLAGNIOL-VILLARD }
255174317984SJean-Christophe PLAGNIOL-VILLARD #else
255243004f31SLinus Walleij static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
255374317984SJean-Christophe PLAGNIOL-VILLARD {
255474317984SJean-Christophe PLAGNIOL-VILLARD 	return 0;
255574317984SJean-Christophe PLAGNIOL-VILLARD }
255674317984SJean-Christophe PLAGNIOL-VILLARD #endif
255774317984SJean-Christophe PLAGNIOL-VILLARD 
2558f3186dd8SLinus Walleij /**
2559f3186dd8SLinus Walleij  * spi_get_gpio_descs() - grab chip select GPIOs for the master
2560f3186dd8SLinus Walleij  * @ctlr: The SPI master to grab GPIO descriptors for
2561f3186dd8SLinus Walleij  */
2562f3186dd8SLinus Walleij static int spi_get_gpio_descs(struct spi_controller *ctlr)
2563f3186dd8SLinus Walleij {
2564f3186dd8SLinus Walleij 	int nb, i;
2565f3186dd8SLinus Walleij 	struct gpio_desc **cs;
2566f3186dd8SLinus Walleij 	struct device *dev = &ctlr->dev;
25677d93aecdSGeert Uytterhoeven 	unsigned long native_cs_mask = 0;
25687d93aecdSGeert Uytterhoeven 	unsigned int num_cs_gpios = 0;
2569f3186dd8SLinus Walleij 
2570f3186dd8SLinus Walleij 	nb = gpiod_count(dev, "cs");
2571f3186dd8SLinus Walleij 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2572f3186dd8SLinus Walleij 
2573f3186dd8SLinus Walleij 	/* No GPIOs at all is fine, else return the error */
2574f3186dd8SLinus Walleij 	if (nb == 0 || nb == -ENOENT)
2575f3186dd8SLinus Walleij 		return 0;
2576f3186dd8SLinus Walleij 	else if (nb < 0)
2577f3186dd8SLinus Walleij 		return nb;
2578f3186dd8SLinus Walleij 
2579f3186dd8SLinus Walleij 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2580f3186dd8SLinus Walleij 			  GFP_KERNEL);
2581f3186dd8SLinus Walleij 	if (!cs)
2582f3186dd8SLinus Walleij 		return -ENOMEM;
2583f3186dd8SLinus Walleij 	ctlr->cs_gpiods = cs;
2584f3186dd8SLinus Walleij 
2585f3186dd8SLinus Walleij 	for (i = 0; i < nb; i++) {
2586f3186dd8SLinus Walleij 		/*
2587f3186dd8SLinus Walleij 		 * Most chipselects are active low, the inverted
2588f3186dd8SLinus Walleij 		 * semantics are handled by special quirks in gpiolib,
2589f3186dd8SLinus Walleij 		 * so initializing them GPIOD_OUT_LOW here means
2590f3186dd8SLinus Walleij 		 * "unasserted", in most cases this will drive the physical
2591f3186dd8SLinus Walleij 		 * line high.
2592f3186dd8SLinus Walleij 		 */
2593f3186dd8SLinus Walleij 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2594f3186dd8SLinus Walleij 						      GPIOD_OUT_LOW);
25951723fdecSGeert Uytterhoeven 		if (IS_ERR(cs[i]))
25961723fdecSGeert Uytterhoeven 			return PTR_ERR(cs[i]);
2597f3186dd8SLinus Walleij 
2598f3186dd8SLinus Walleij 		if (cs[i]) {
2599f3186dd8SLinus Walleij 			/*
2600f3186dd8SLinus Walleij 			 * If we find a CS GPIO, name it after the device and
2601f3186dd8SLinus Walleij 			 * chip select line.
2602f3186dd8SLinus Walleij 			 */
2603f3186dd8SLinus Walleij 			char *gpioname;
2604f3186dd8SLinus Walleij 
2605f3186dd8SLinus Walleij 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2606f3186dd8SLinus Walleij 						  dev_name(dev), i);
2607f3186dd8SLinus Walleij 			if (!gpioname)
2608f3186dd8SLinus Walleij 				return -ENOMEM;
2609f3186dd8SLinus Walleij 			gpiod_set_consumer_name(cs[i], gpioname);
26107d93aecdSGeert Uytterhoeven 			num_cs_gpios++;
26117d93aecdSGeert Uytterhoeven 			continue;
2612f3186dd8SLinus Walleij 		}
26137d93aecdSGeert Uytterhoeven 
26147d93aecdSGeert Uytterhoeven 		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
26157d93aecdSGeert Uytterhoeven 			dev_err(dev, "Invalid native chip select %d\n", i);
26167d93aecdSGeert Uytterhoeven 			return -EINVAL;
26177d93aecdSGeert Uytterhoeven 		}
26187d93aecdSGeert Uytterhoeven 		native_cs_mask |= BIT(i);
26197d93aecdSGeert Uytterhoeven 	}
26207d93aecdSGeert Uytterhoeven 
26217d93aecdSGeert Uytterhoeven 	ctlr->unused_native_cs = ffz(native_cs_mask);
26227d93aecdSGeert Uytterhoeven 	if (num_cs_gpios && ctlr->max_native_cs &&
26237d93aecdSGeert Uytterhoeven 	    ctlr->unused_native_cs >= ctlr->max_native_cs) {
26247d93aecdSGeert Uytterhoeven 		dev_err(dev, "No unused native chip select available\n");
26257d93aecdSGeert Uytterhoeven 		return -EINVAL;
2626f3186dd8SLinus Walleij 	}
2627f3186dd8SLinus Walleij 
2628f3186dd8SLinus Walleij 	return 0;
2629f3186dd8SLinus Walleij }
2630f3186dd8SLinus Walleij 
2631bdf3a3b5SBoris Brezillon static int spi_controller_check_ops(struct spi_controller *ctlr)
2632bdf3a3b5SBoris Brezillon {
2633bdf3a3b5SBoris Brezillon 	/*
2634b5932f5cSBoris Brezillon 	 * The controller may implement only the high-level SPI-memory like
2635b5932f5cSBoris Brezillon 	 * operations if it does not support regular SPI transfers, and this is
2636b5932f5cSBoris Brezillon 	 * valid use case.
2637b5932f5cSBoris Brezillon 	 * If ->mem_ops is NULL, we request that at least one of the
2638b5932f5cSBoris Brezillon 	 * ->transfer_xxx() method be implemented.
2639bdf3a3b5SBoris Brezillon 	 */
2640b5932f5cSBoris Brezillon 	if (ctlr->mem_ops) {
2641b5932f5cSBoris Brezillon 		if (!ctlr->mem_ops->exec_op)
2642bdf3a3b5SBoris Brezillon 			return -EINVAL;
2643b5932f5cSBoris Brezillon 	} else if (!ctlr->transfer && !ctlr->transfer_one &&
2644b5932f5cSBoris Brezillon 		   !ctlr->transfer_one_message) {
2645b5932f5cSBoris Brezillon 		return -EINVAL;
2646b5932f5cSBoris Brezillon 	}
2647bdf3a3b5SBoris Brezillon 
2648bdf3a3b5SBoris Brezillon 	return 0;
2649bdf3a3b5SBoris Brezillon }
2650bdf3a3b5SBoris Brezillon 
26518ae12a0dSDavid Brownell /**
26528caab75fSGeert Uytterhoeven  * spi_register_controller - register SPI master or slave controller
26538caab75fSGeert Uytterhoeven  * @ctlr: initialized master, originally from spi_alloc_master() or
26548caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
265533e34dc6SDavid Brownell  * Context: can sleep
26568ae12a0dSDavid Brownell  *
26578caab75fSGeert Uytterhoeven  * SPI controllers connect to their drivers using some non-SPI bus,
26588ae12a0dSDavid Brownell  * such as the platform bus.  The final stage of probe() in that code
26598caab75fSGeert Uytterhoeven  * includes calling spi_register_controller() to hook up to this SPI bus glue.
26608ae12a0dSDavid Brownell  *
26618ae12a0dSDavid Brownell  * SPI controllers use board specific (often SOC specific) bus numbers,
26628ae12a0dSDavid Brownell  * and board-specific addressing for SPI devices combines those numbers
26638ae12a0dSDavid Brownell  * with chip select numbers.  Since SPI does not directly support dynamic
26648ae12a0dSDavid Brownell  * device identification, boards need configuration tables telling which
26658ae12a0dSDavid Brownell  * chip is at which address.
26668ae12a0dSDavid Brownell  *
26678ae12a0dSDavid Brownell  * This must be called from context that can sleep.  It returns zero on
26688caab75fSGeert Uytterhoeven  * success, else a negative error code (dropping the controller's refcount).
26690c868461SDavid Brownell  * After a successful return, the caller is responsible for calling
26708caab75fSGeert Uytterhoeven  * spi_unregister_controller().
267197d56dc6SJavier Martinez Canillas  *
267297d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
26738ae12a0dSDavid Brownell  */
26748caab75fSGeert Uytterhoeven int spi_register_controller(struct spi_controller *ctlr)
26758ae12a0dSDavid Brownell {
26768caab75fSGeert Uytterhoeven 	struct device		*dev = ctlr->dev.parent;
26772b9603a0SFeng Tang 	struct boardinfo	*bi;
2678b93318a2SSergei Shtylyov 	int			status;
267942bdd706SLucas Stach 	int			id, first_dynamic;
26808ae12a0dSDavid Brownell 
26810c868461SDavid Brownell 	if (!dev)
26820c868461SDavid Brownell 		return -ENODEV;
26830c868461SDavid Brownell 
2684bdf3a3b5SBoris Brezillon 	/*
2685bdf3a3b5SBoris Brezillon 	 * Make sure all necessary hooks are implemented before registering
2686bdf3a3b5SBoris Brezillon 	 * the SPI controller.
2687bdf3a3b5SBoris Brezillon 	 */
2688bdf3a3b5SBoris Brezillon 	status = spi_controller_check_ops(ctlr);
2689bdf3a3b5SBoris Brezillon 	if (status)
2690bdf3a3b5SBoris Brezillon 		return status;
2691bdf3a3b5SBoris Brezillon 
269204b2d03aSGeert Uytterhoeven 	if (ctlr->bus_num >= 0) {
269304b2d03aSGeert Uytterhoeven 		/* devices with a fixed bus num must check-in with the num */
269404b2d03aSGeert Uytterhoeven 		mutex_lock(&board_lock);
269504b2d03aSGeert Uytterhoeven 		id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
269604b2d03aSGeert Uytterhoeven 			ctlr->bus_num + 1, GFP_KERNEL);
269704b2d03aSGeert Uytterhoeven 		mutex_unlock(&board_lock);
269804b2d03aSGeert Uytterhoeven 		if (WARN(id < 0, "couldn't get idr"))
269904b2d03aSGeert Uytterhoeven 			return id == -ENOSPC ? -EBUSY : id;
270004b2d03aSGeert Uytterhoeven 		ctlr->bus_num = id;
270104b2d03aSGeert Uytterhoeven 	} else if (ctlr->dev.of_node) {
27029b61e302SSuniel Mahesh 		/* allocate dynamic bus number using Linux idr */
27039b61e302SSuniel Mahesh 		id = of_alias_get_id(ctlr->dev.of_node, "spi");
27049b61e302SSuniel Mahesh 		if (id >= 0) {
27059b61e302SSuniel Mahesh 			ctlr->bus_num = id;
27069b61e302SSuniel Mahesh 			mutex_lock(&board_lock);
27079b61e302SSuniel Mahesh 			id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
27089b61e302SSuniel Mahesh 				       ctlr->bus_num + 1, GFP_KERNEL);
27099b61e302SSuniel Mahesh 			mutex_unlock(&board_lock);
27109b61e302SSuniel Mahesh 			if (WARN(id < 0, "couldn't get idr"))
27119b61e302SSuniel Mahesh 				return id == -ENOSPC ? -EBUSY : id;
27129b61e302SSuniel Mahesh 		}
27139b61e302SSuniel Mahesh 	}
27148caab75fSGeert Uytterhoeven 	if (ctlr->bus_num < 0) {
271542bdd706SLucas Stach 		first_dynamic = of_alias_get_highest_id("spi");
271642bdd706SLucas Stach 		if (first_dynamic < 0)
271742bdd706SLucas Stach 			first_dynamic = 0;
271842bdd706SLucas Stach 		else
271942bdd706SLucas Stach 			first_dynamic++;
272042bdd706SLucas Stach 
27219b61e302SSuniel Mahesh 		mutex_lock(&board_lock);
272242bdd706SLucas Stach 		id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
272342bdd706SLucas Stach 			       0, GFP_KERNEL);
27249b61e302SSuniel Mahesh 		mutex_unlock(&board_lock);
27259b61e302SSuniel Mahesh 		if (WARN(id < 0, "couldn't get idr"))
27269b61e302SSuniel Mahesh 			return id;
27279b61e302SSuniel Mahesh 		ctlr->bus_num = id;
27288ae12a0dSDavid Brownell 	}
27298caab75fSGeert Uytterhoeven 	INIT_LIST_HEAD(&ctlr->queue);
27308caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->queue_lock);
27318caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->bus_lock_spinlock);
27328caab75fSGeert Uytterhoeven 	mutex_init(&ctlr->bus_lock_mutex);
27338caab75fSGeert Uytterhoeven 	mutex_init(&ctlr->io_mutex);
27348caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
27358caab75fSGeert Uytterhoeven 	init_completion(&ctlr->xfer_completion);
27368caab75fSGeert Uytterhoeven 	if (!ctlr->max_dma_len)
27378caab75fSGeert Uytterhoeven 		ctlr->max_dma_len = INT_MAX;
2738cf32b71eSErnst Schwab 
27398ae12a0dSDavid Brownell 	/* register the device, then userspace will see it.
27408ae12a0dSDavid Brownell 	 * registration fails if the bus ID is in use.
27418ae12a0dSDavid Brownell 	 */
27428caab75fSGeert Uytterhoeven 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
27430a919ae4SAndrey Smirnov 
27440a919ae4SAndrey Smirnov 	if (!spi_controller_is_slave(ctlr)) {
27450a919ae4SAndrey Smirnov 		if (ctlr->use_gpio_descriptors) {
27460a919ae4SAndrey Smirnov 			status = spi_get_gpio_descs(ctlr);
27470a919ae4SAndrey Smirnov 			if (status)
2748f9981d4fSAaro Koskinen 				goto free_bus_id;
27490a919ae4SAndrey Smirnov 			/*
27500a919ae4SAndrey Smirnov 			 * A controller using GPIO descriptors always
27510a919ae4SAndrey Smirnov 			 * supports SPI_CS_HIGH if need be.
27520a919ae4SAndrey Smirnov 			 */
27530a919ae4SAndrey Smirnov 			ctlr->mode_bits |= SPI_CS_HIGH;
27540a919ae4SAndrey Smirnov 		} else {
27550a919ae4SAndrey Smirnov 			/* Legacy code path for GPIOs from DT */
275643004f31SLinus Walleij 			status = of_spi_get_gpio_numbers(ctlr);
27570a919ae4SAndrey Smirnov 			if (status)
2758f9981d4fSAaro Koskinen 				goto free_bus_id;
27590a919ae4SAndrey Smirnov 		}
27600a919ae4SAndrey Smirnov 	}
27610a919ae4SAndrey Smirnov 
2762f9481b08STudor Ambarus 	/*
2763f9481b08STudor Ambarus 	 * Even if it's just one always-selected device, there must
2764f9481b08STudor Ambarus 	 * be at least one chipselect.
2765f9481b08STudor Ambarus 	 */
2766f9981d4fSAaro Koskinen 	if (!ctlr->num_chipselect) {
2767f9981d4fSAaro Koskinen 		status = -EINVAL;
2768f9981d4fSAaro Koskinen 		goto free_bus_id;
2769f9981d4fSAaro Koskinen 	}
2770f9481b08STudor Ambarus 
27718caab75fSGeert Uytterhoeven 	status = device_add(&ctlr->dev);
2772f9981d4fSAaro Koskinen 	if (status < 0)
2773f9981d4fSAaro Koskinen 		goto free_bus_id;
27749b61e302SSuniel Mahesh 	dev_dbg(dev, "registered %s %s\n",
27758caab75fSGeert Uytterhoeven 			spi_controller_is_slave(ctlr) ? "slave" : "master",
27769b61e302SSuniel Mahesh 			dev_name(&ctlr->dev));
27778ae12a0dSDavid Brownell 
2778b5932f5cSBoris Brezillon 	/*
2779b5932f5cSBoris Brezillon 	 * If we're using a queued driver, start the queue. Note that we don't
2780b5932f5cSBoris Brezillon 	 * need the queueing logic if the driver is only supporting high-level
2781b5932f5cSBoris Brezillon 	 * memory operations.
2782b5932f5cSBoris Brezillon 	 */
2783b5932f5cSBoris Brezillon 	if (ctlr->transfer) {
27848caab75fSGeert Uytterhoeven 		dev_info(dev, "controller is unqueued, this is deprecated\n");
2785b5932f5cSBoris Brezillon 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
27868caab75fSGeert Uytterhoeven 		status = spi_controller_initialize_queue(ctlr);
2787ffbbdd21SLinus Walleij 		if (status) {
27888caab75fSGeert Uytterhoeven 			device_del(&ctlr->dev);
2789f9981d4fSAaro Koskinen 			goto free_bus_id;
2790ffbbdd21SLinus Walleij 		}
2791ffbbdd21SLinus Walleij 	}
2792eca2ebc7SMartin Sperl 	/* add statistics */
27938caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->statistics.lock);
2794ffbbdd21SLinus Walleij 
27952b9603a0SFeng Tang 	mutex_lock(&board_lock);
27968caab75fSGeert Uytterhoeven 	list_add_tail(&ctlr->list, &spi_controller_list);
27972b9603a0SFeng Tang 	list_for_each_entry(bi, &board_list, list)
27988caab75fSGeert Uytterhoeven 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
27992b9603a0SFeng Tang 	mutex_unlock(&board_lock);
28002b9603a0SFeng Tang 
280164bee4d2SMika Westerberg 	/* Register devices from the device tree and ACPI */
28028caab75fSGeert Uytterhoeven 	of_register_spi_devices(ctlr);
28038caab75fSGeert Uytterhoeven 	acpi_register_spi_devices(ctlr);
2804f9981d4fSAaro Koskinen 	return status;
2805f9981d4fSAaro Koskinen 
2806f9981d4fSAaro Koskinen free_bus_id:
2807f9981d4fSAaro Koskinen 	mutex_lock(&board_lock);
2808f9981d4fSAaro Koskinen 	idr_remove(&spi_master_idr, ctlr->bus_num);
2809f9981d4fSAaro Koskinen 	mutex_unlock(&board_lock);
28108ae12a0dSDavid Brownell 	return status;
28118ae12a0dSDavid Brownell }
28128caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_register_controller);
28138ae12a0dSDavid Brownell 
2814666d5b4cSMark Brown static void devm_spi_unregister(struct device *dev, void *res)
2815666d5b4cSMark Brown {
28168caab75fSGeert Uytterhoeven 	spi_unregister_controller(*(struct spi_controller **)res);
2817666d5b4cSMark Brown }
2818666d5b4cSMark Brown 
2819666d5b4cSMark Brown /**
28208caab75fSGeert Uytterhoeven  * devm_spi_register_controller - register managed SPI master or slave
28218caab75fSGeert Uytterhoeven  *	controller
28228caab75fSGeert Uytterhoeven  * @dev:    device managing SPI controller
28238caab75fSGeert Uytterhoeven  * @ctlr: initialized controller, originally from spi_alloc_master() or
28248caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
2825666d5b4cSMark Brown  * Context: can sleep
2826666d5b4cSMark Brown  *
28278caab75fSGeert Uytterhoeven  * Register a SPI device as with spi_register_controller() which will
282868b892f1SJohan Hovold  * automatically be unregistered and freed.
282997d56dc6SJavier Martinez Canillas  *
283097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
2831666d5b4cSMark Brown  */
28328caab75fSGeert Uytterhoeven int devm_spi_register_controller(struct device *dev,
28338caab75fSGeert Uytterhoeven 				 struct spi_controller *ctlr)
2834666d5b4cSMark Brown {
28358caab75fSGeert Uytterhoeven 	struct spi_controller **ptr;
2836666d5b4cSMark Brown 	int ret;
2837666d5b4cSMark Brown 
2838666d5b4cSMark Brown 	ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2839666d5b4cSMark Brown 	if (!ptr)
2840666d5b4cSMark Brown 		return -ENOMEM;
2841666d5b4cSMark Brown 
28428caab75fSGeert Uytterhoeven 	ret = spi_register_controller(ctlr);
28434b92894eSStephen Warren 	if (!ret) {
28448caab75fSGeert Uytterhoeven 		*ptr = ctlr;
2845666d5b4cSMark Brown 		devres_add(dev, ptr);
2846666d5b4cSMark Brown 	} else {
2847666d5b4cSMark Brown 		devres_free(ptr);
2848666d5b4cSMark Brown 	}
2849666d5b4cSMark Brown 
2850666d5b4cSMark Brown 	return ret;
2851666d5b4cSMark Brown }
28528caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2853666d5b4cSMark Brown 
28545e844cc3SLukas Wunner static int devm_spi_match_controller(struct device *dev, void *res, void *ctlr)
28555e844cc3SLukas Wunner {
28565e844cc3SLukas Wunner 	return *(struct spi_controller **)res == ctlr;
28575e844cc3SLukas Wunner }
28585e844cc3SLukas Wunner 
285934860089SDavid Lamparter static int __unregister(struct device *dev, void *null)
28608ae12a0dSDavid Brownell {
28610c868461SDavid Brownell 	spi_unregister_device(to_spi_device(dev));
28628ae12a0dSDavid Brownell 	return 0;
28638ae12a0dSDavid Brownell }
28648ae12a0dSDavid Brownell 
28658ae12a0dSDavid Brownell /**
28668caab75fSGeert Uytterhoeven  * spi_unregister_controller - unregister SPI master or slave controller
28678caab75fSGeert Uytterhoeven  * @ctlr: the controller being unregistered
286833e34dc6SDavid Brownell  * Context: can sleep
28698ae12a0dSDavid Brownell  *
28708caab75fSGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
28718ae12a0dSDavid Brownell  * only ones directly touching chip registers.
28728ae12a0dSDavid Brownell  *
28738ae12a0dSDavid Brownell  * This must be called from context that can sleep.
287468b892f1SJohan Hovold  *
287568b892f1SJohan Hovold  * Note that this function also drops a reference to the controller.
28768ae12a0dSDavid Brownell  */
28778caab75fSGeert Uytterhoeven void spi_unregister_controller(struct spi_controller *ctlr)
28788ae12a0dSDavid Brownell {
28799b61e302SSuniel Mahesh 	struct spi_controller *found;
288067f7b278SJohan Hovold 	int id = ctlr->bus_num;
288189fc9a1aSJeff Garzik 
2882ddf75be4SLukas Wunner 	/* Prevent addition of new devices, unregister existing ones */
2883ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2884ddf75be4SLukas Wunner 		mutex_lock(&spi_add_lock);
2885ddf75be4SLukas Wunner 
288684855678SLukas Wunner 	device_for_each_child(&ctlr->dev, NULL, __unregister);
288784855678SLukas Wunner 
28889b61e302SSuniel Mahesh 	/* First make sure that this controller was ever added */
28899b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
289067f7b278SJohan Hovold 	found = idr_find(&spi_master_idr, id);
28919b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
28928caab75fSGeert Uytterhoeven 	if (ctlr->queued) {
28938caab75fSGeert Uytterhoeven 		if (spi_destroy_queue(ctlr))
28948caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue remove failed\n");
2895ffbbdd21SLinus Walleij 	}
28962b9603a0SFeng Tang 	mutex_lock(&board_lock);
28978caab75fSGeert Uytterhoeven 	list_del(&ctlr->list);
28982b9603a0SFeng Tang 	mutex_unlock(&board_lock);
28992b9603a0SFeng Tang 
29005e844cc3SLukas Wunner 	device_del(&ctlr->dev);
29015e844cc3SLukas Wunner 
29025e844cc3SLukas Wunner 	/* Release the last reference on the controller if its driver
29035e844cc3SLukas Wunner 	 * has not yet been converted to devm_spi_alloc_master/slave().
29045e844cc3SLukas Wunner 	 */
29055e844cc3SLukas Wunner 	if (!devres_find(ctlr->dev.parent, devm_spi_release_controller,
29065e844cc3SLukas Wunner 			 devm_spi_match_controller, ctlr))
29075e844cc3SLukas Wunner 		put_device(&ctlr->dev);
29085e844cc3SLukas Wunner 
29099b61e302SSuniel Mahesh 	/* free bus id */
29109b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
2911613bd1eaSJarkko Nikula 	if (found == ctlr)
291267f7b278SJohan Hovold 		idr_remove(&spi_master_idr, id);
29139b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
2914ddf75be4SLukas Wunner 
2915ddf75be4SLukas Wunner 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2916ddf75be4SLukas Wunner 		mutex_unlock(&spi_add_lock);
29178ae12a0dSDavid Brownell }
29188caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_controller);
29198ae12a0dSDavid Brownell 
29208caab75fSGeert Uytterhoeven int spi_controller_suspend(struct spi_controller *ctlr)
2921ffbbdd21SLinus Walleij {
2922ffbbdd21SLinus Walleij 	int ret;
2923ffbbdd21SLinus Walleij 
29248caab75fSGeert Uytterhoeven 	/* Basically no-ops for non-queued controllers */
29258caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
2926ffbbdd21SLinus Walleij 		return 0;
2927ffbbdd21SLinus Walleij 
29288caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
2929ffbbdd21SLinus Walleij 	if (ret)
29308caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue stop failed\n");
2931ffbbdd21SLinus Walleij 
2932ffbbdd21SLinus Walleij 	return ret;
2933ffbbdd21SLinus Walleij }
29348caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_suspend);
2935ffbbdd21SLinus Walleij 
29368caab75fSGeert Uytterhoeven int spi_controller_resume(struct spi_controller *ctlr)
2937ffbbdd21SLinus Walleij {
2938ffbbdd21SLinus Walleij 	int ret;
2939ffbbdd21SLinus Walleij 
29408caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
2941ffbbdd21SLinus Walleij 		return 0;
2942ffbbdd21SLinus Walleij 
29438caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
2944ffbbdd21SLinus Walleij 	if (ret)
29458caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue restart failed\n");
2946ffbbdd21SLinus Walleij 
2947ffbbdd21SLinus Walleij 	return ret;
2948ffbbdd21SLinus Walleij }
29498caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_resume);
2950ffbbdd21SLinus Walleij 
29518caab75fSGeert Uytterhoeven static int __spi_controller_match(struct device *dev, const void *data)
29525ed2c832SDave Young {
29538caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
29549f3b795aSMichał Mirosław 	const u16 *bus_num = data;
29555ed2c832SDave Young 
29568caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
29578caab75fSGeert Uytterhoeven 	return ctlr->bus_num == *bus_num;
29585ed2c832SDave Young }
29595ed2c832SDave Young 
29608ae12a0dSDavid Brownell /**
29618ae12a0dSDavid Brownell  * spi_busnum_to_master - look up master associated with bus_num
29628ae12a0dSDavid Brownell  * @bus_num: the master's bus number
296333e34dc6SDavid Brownell  * Context: can sleep
29648ae12a0dSDavid Brownell  *
29658ae12a0dSDavid Brownell  * This call may be used with devices that are registered after
29668ae12a0dSDavid Brownell  * arch init time.  It returns a refcounted pointer to the relevant
29678caab75fSGeert Uytterhoeven  * spi_controller (which the caller must release), or NULL if there is
29688ae12a0dSDavid Brownell  * no such master registered.
296997d56dc6SJavier Martinez Canillas  *
297097d56dc6SJavier Martinez Canillas  * Return: the SPI master structure on success, else NULL.
29718ae12a0dSDavid Brownell  */
29728caab75fSGeert Uytterhoeven struct spi_controller *spi_busnum_to_master(u16 bus_num)
29738ae12a0dSDavid Brownell {
297449dce689STony Jones 	struct device		*dev;
29758caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr = NULL;
29768ae12a0dSDavid Brownell 
2977695794aeSGreg Kroah-Hartman 	dev = class_find_device(&spi_master_class, NULL, &bus_num,
29788caab75fSGeert Uytterhoeven 				__spi_controller_match);
29795ed2c832SDave Young 	if (dev)
29808caab75fSGeert Uytterhoeven 		ctlr = container_of(dev, struct spi_controller, dev);
29815ed2c832SDave Young 	/* reference got in class_find_device */
29828caab75fSGeert Uytterhoeven 	return ctlr;
29838ae12a0dSDavid Brownell }
29848ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_busnum_to_master);
29858ae12a0dSDavid Brownell 
2986d780c371SMartin Sperl /*-------------------------------------------------------------------------*/
2987d780c371SMartin Sperl 
2988d780c371SMartin Sperl /* Core methods for SPI resource management */
2989d780c371SMartin Sperl 
2990d780c371SMartin Sperl /**
2991d780c371SMartin Sperl  * spi_res_alloc - allocate a spi resource that is life-cycle managed
2992d780c371SMartin Sperl  *                 during the processing of a spi_message while using
2993d780c371SMartin Sperl  *                 spi_transfer_one
2994d780c371SMartin Sperl  * @spi:     the spi device for which we allocate memory
2995d780c371SMartin Sperl  * @release: the release code to execute for this resource
2996d780c371SMartin Sperl  * @size:    size to alloc and return
2997d780c371SMartin Sperl  * @gfp:     GFP allocation flags
2998d780c371SMartin Sperl  *
2999d780c371SMartin Sperl  * Return: the pointer to the allocated data
3000d780c371SMartin Sperl  *
3001d780c371SMartin Sperl  * This may get enhanced in the future to allocate from a memory pool
30028caab75fSGeert Uytterhoeven  * of the @spi_device or @spi_controller to avoid repeated allocations.
3003d780c371SMartin Sperl  */
3004d780c371SMartin Sperl void *spi_res_alloc(struct spi_device *spi,
3005d780c371SMartin Sperl 		    spi_res_release_t release,
3006d780c371SMartin Sperl 		    size_t size, gfp_t gfp)
3007d780c371SMartin Sperl {
3008d780c371SMartin Sperl 	struct spi_res *sres;
3009d780c371SMartin Sperl 
3010d780c371SMartin Sperl 	sres = kzalloc(sizeof(*sres) + size, gfp);
3011d780c371SMartin Sperl 	if (!sres)
3012d780c371SMartin Sperl 		return NULL;
3013d780c371SMartin Sperl 
3014d780c371SMartin Sperl 	INIT_LIST_HEAD(&sres->entry);
3015d780c371SMartin Sperl 	sres->release = release;
3016d780c371SMartin Sperl 
3017d780c371SMartin Sperl 	return sres->data;
3018d780c371SMartin Sperl }
3019d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_alloc);
3020d780c371SMartin Sperl 
3021d780c371SMartin Sperl /**
3022d780c371SMartin Sperl  * spi_res_free - free an spi resource
3023d780c371SMartin Sperl  * @res: pointer to the custom data of a resource
3024d780c371SMartin Sperl  *
3025d780c371SMartin Sperl  */
3026d780c371SMartin Sperl void spi_res_free(void *res)
3027d780c371SMartin Sperl {
3028d780c371SMartin Sperl 	struct spi_res *sres = container_of(res, struct spi_res, data);
3029d780c371SMartin Sperl 
3030d780c371SMartin Sperl 	if (!res)
3031d780c371SMartin Sperl 		return;
3032d780c371SMartin Sperl 
3033d780c371SMartin Sperl 	WARN_ON(!list_empty(&sres->entry));
3034d780c371SMartin Sperl 	kfree(sres);
3035d780c371SMartin Sperl }
3036d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_free);
3037d780c371SMartin Sperl 
3038d780c371SMartin Sperl /**
3039d780c371SMartin Sperl  * spi_res_add - add a spi_res to the spi_message
3040d780c371SMartin Sperl  * @message: the spi message
3041d780c371SMartin Sperl  * @res:     the spi_resource
3042d780c371SMartin Sperl  */
3043d780c371SMartin Sperl void spi_res_add(struct spi_message *message, void *res)
3044d780c371SMartin Sperl {
3045d780c371SMartin Sperl 	struct spi_res *sres = container_of(res, struct spi_res, data);
3046d780c371SMartin Sperl 
3047d780c371SMartin Sperl 	WARN_ON(!list_empty(&sres->entry));
3048d780c371SMartin Sperl 	list_add_tail(&sres->entry, &message->resources);
3049d780c371SMartin Sperl }
3050d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_add);
3051d780c371SMartin Sperl 
3052d780c371SMartin Sperl /**
3053d780c371SMartin Sperl  * spi_res_release - release all spi resources for this message
30548caab75fSGeert Uytterhoeven  * @ctlr:  the @spi_controller
3055d780c371SMartin Sperl  * @message: the @spi_message
3056d780c371SMartin Sperl  */
30578caab75fSGeert Uytterhoeven void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3058d780c371SMartin Sperl {
3059f5694369SVladimir Zapolskiy 	struct spi_res *res, *tmp;
3060d780c371SMartin Sperl 
3061f5694369SVladimir Zapolskiy 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3062d780c371SMartin Sperl 		if (res->release)
30638caab75fSGeert Uytterhoeven 			res->release(ctlr, message, res->data);
3064d780c371SMartin Sperl 
3065d780c371SMartin Sperl 		list_del(&res->entry);
3066d780c371SMartin Sperl 
3067d780c371SMartin Sperl 		kfree(res);
3068d780c371SMartin Sperl 	}
3069d780c371SMartin Sperl }
3070d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_release);
30718ae12a0dSDavid Brownell 
30728ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
30738ae12a0dSDavid Brownell 
3074523baf5aSMartin Sperl /* Core methods for spi_message alterations */
3075523baf5aSMartin Sperl 
30768caab75fSGeert Uytterhoeven static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3077523baf5aSMartin Sperl 					    struct spi_message *msg,
3078523baf5aSMartin Sperl 					    void *res)
3079523baf5aSMartin Sperl {
3080523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer = res;
3081523baf5aSMartin Sperl 	size_t i;
3082523baf5aSMartin Sperl 
3083523baf5aSMartin Sperl 	/* call extra callback if requested */
3084523baf5aSMartin Sperl 	if (rxfer->release)
30858caab75fSGeert Uytterhoeven 		rxfer->release(ctlr, msg, res);
3086523baf5aSMartin Sperl 
3087523baf5aSMartin Sperl 	/* insert replaced transfers back into the message */
3088523baf5aSMartin Sperl 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3089523baf5aSMartin Sperl 
3090523baf5aSMartin Sperl 	/* remove the formerly inserted entries */
3091523baf5aSMartin Sperl 	for (i = 0; i < rxfer->inserted; i++)
3092523baf5aSMartin Sperl 		list_del(&rxfer->inserted_transfers[i].transfer_list);
3093523baf5aSMartin Sperl }
3094523baf5aSMartin Sperl 
3095523baf5aSMartin Sperl /**
3096523baf5aSMartin Sperl  * spi_replace_transfers - replace transfers with several transfers
3097523baf5aSMartin Sperl  *                         and register change with spi_message.resources
3098523baf5aSMartin Sperl  * @msg:           the spi_message we work upon
3099523baf5aSMartin Sperl  * @xfer_first:    the first spi_transfer we want to replace
3100523baf5aSMartin Sperl  * @remove:        number of transfers to remove
3101523baf5aSMartin Sperl  * @insert:        the number of transfers we want to insert instead
3102523baf5aSMartin Sperl  * @release:       extra release code necessary in some circumstances
3103523baf5aSMartin Sperl  * @extradatasize: extra data to allocate (with alignment guarantees
3104523baf5aSMartin Sperl  *                 of struct @spi_transfer)
310505885397SMartin Sperl  * @gfp:           gfp flags
3106523baf5aSMartin Sperl  *
3107523baf5aSMartin Sperl  * Returns: pointer to @spi_replaced_transfers,
3108523baf5aSMartin Sperl  *          PTR_ERR(...) in case of errors.
3109523baf5aSMartin Sperl  */
3110523baf5aSMartin Sperl struct spi_replaced_transfers *spi_replace_transfers(
3111523baf5aSMartin Sperl 	struct spi_message *msg,
3112523baf5aSMartin Sperl 	struct spi_transfer *xfer_first,
3113523baf5aSMartin Sperl 	size_t remove,
3114523baf5aSMartin Sperl 	size_t insert,
3115523baf5aSMartin Sperl 	spi_replaced_release_t release,
3116523baf5aSMartin Sperl 	size_t extradatasize,
3117523baf5aSMartin Sperl 	gfp_t gfp)
3118523baf5aSMartin Sperl {
3119523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer;
3120523baf5aSMartin Sperl 	struct spi_transfer *xfer;
3121523baf5aSMartin Sperl 	size_t i;
3122523baf5aSMartin Sperl 
3123523baf5aSMartin Sperl 	/* allocate the structure using spi_res */
3124523baf5aSMartin Sperl 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3125aef97522SGustavo A. R. Silva 			      struct_size(rxfer, inserted_transfers, insert)
3126523baf5aSMartin Sperl 			      + extradatasize,
3127523baf5aSMartin Sperl 			      gfp);
3128523baf5aSMartin Sperl 	if (!rxfer)
3129523baf5aSMartin Sperl 		return ERR_PTR(-ENOMEM);
3130523baf5aSMartin Sperl 
3131523baf5aSMartin Sperl 	/* the release code to invoke before running the generic release */
3132523baf5aSMartin Sperl 	rxfer->release = release;
3133523baf5aSMartin Sperl 
3134523baf5aSMartin Sperl 	/* assign extradata */
3135523baf5aSMartin Sperl 	if (extradatasize)
3136523baf5aSMartin Sperl 		rxfer->extradata =
3137523baf5aSMartin Sperl 			&rxfer->inserted_transfers[insert];
3138523baf5aSMartin Sperl 
3139523baf5aSMartin Sperl 	/* init the replaced_transfers list */
3140523baf5aSMartin Sperl 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3141523baf5aSMartin Sperl 
3142523baf5aSMartin Sperl 	/* assign the list_entry after which we should reinsert
3143523baf5aSMartin Sperl 	 * the @replaced_transfers - it may be spi_message.messages!
3144523baf5aSMartin Sperl 	 */
3145523baf5aSMartin Sperl 	rxfer->replaced_after = xfer_first->transfer_list.prev;
3146523baf5aSMartin Sperl 
3147523baf5aSMartin Sperl 	/* remove the requested number of transfers */
3148523baf5aSMartin Sperl 	for (i = 0; i < remove; i++) {
3149523baf5aSMartin Sperl 		/* if the entry after replaced_after it is msg->transfers
3150523baf5aSMartin Sperl 		 * then we have been requested to remove more transfers
3151523baf5aSMartin Sperl 		 * than are in the list
3152523baf5aSMartin Sperl 		 */
3153523baf5aSMartin Sperl 		if (rxfer->replaced_after->next == &msg->transfers) {
3154523baf5aSMartin Sperl 			dev_err(&msg->spi->dev,
3155523baf5aSMartin Sperl 				"requested to remove more spi_transfers than are available\n");
3156523baf5aSMartin Sperl 			/* insert replaced transfers back into the message */
3157523baf5aSMartin Sperl 			list_splice(&rxfer->replaced_transfers,
3158523baf5aSMartin Sperl 				    rxfer->replaced_after);
3159523baf5aSMartin Sperl 
3160523baf5aSMartin Sperl 			/* free the spi_replace_transfer structure */
3161523baf5aSMartin Sperl 			spi_res_free(rxfer);
3162523baf5aSMartin Sperl 
3163523baf5aSMartin Sperl 			/* and return with an error */
3164523baf5aSMartin Sperl 			return ERR_PTR(-EINVAL);
3165523baf5aSMartin Sperl 		}
3166523baf5aSMartin Sperl 
3167523baf5aSMartin Sperl 		/* remove the entry after replaced_after from list of
3168523baf5aSMartin Sperl 		 * transfers and add it to list of replaced_transfers
3169523baf5aSMartin Sperl 		 */
3170523baf5aSMartin Sperl 		list_move_tail(rxfer->replaced_after->next,
3171523baf5aSMartin Sperl 			       &rxfer->replaced_transfers);
3172523baf5aSMartin Sperl 	}
3173523baf5aSMartin Sperl 
3174523baf5aSMartin Sperl 	/* create copy of the given xfer with identical settings
3175523baf5aSMartin Sperl 	 * based on the first transfer to get removed
3176523baf5aSMartin Sperl 	 */
3177523baf5aSMartin Sperl 	for (i = 0; i < insert; i++) {
3178523baf5aSMartin Sperl 		/* we need to run in reverse order */
3179523baf5aSMartin Sperl 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3180523baf5aSMartin Sperl 
3181523baf5aSMartin Sperl 		/* copy all spi_transfer data */
3182523baf5aSMartin Sperl 		memcpy(xfer, xfer_first, sizeof(*xfer));
3183523baf5aSMartin Sperl 
3184523baf5aSMartin Sperl 		/* add to list */
3185523baf5aSMartin Sperl 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3186523baf5aSMartin Sperl 
3187bebcfd27SAlexandru Ardelean 		/* clear cs_change and delay for all but the last */
3188523baf5aSMartin Sperl 		if (i) {
3189523baf5aSMartin Sperl 			xfer->cs_change = false;
3190523baf5aSMartin Sperl 			xfer->delay_usecs = 0;
3191bebcfd27SAlexandru Ardelean 			xfer->delay.value = 0;
3192523baf5aSMartin Sperl 		}
3193523baf5aSMartin Sperl 	}
3194523baf5aSMartin Sperl 
3195523baf5aSMartin Sperl 	/* set up inserted */
3196523baf5aSMartin Sperl 	rxfer->inserted = insert;
3197523baf5aSMartin Sperl 
3198523baf5aSMartin Sperl 	/* and register it with spi_res/spi_message */
3199523baf5aSMartin Sperl 	spi_res_add(msg, rxfer);
3200523baf5aSMartin Sperl 
3201523baf5aSMartin Sperl 	return rxfer;
3202523baf5aSMartin Sperl }
3203523baf5aSMartin Sperl EXPORT_SYMBOL_GPL(spi_replace_transfers);
3204523baf5aSMartin Sperl 
32058caab75fSGeert Uytterhoeven static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3206d9f12122SMartin Sperl 					struct spi_message *msg,
3207d9f12122SMartin Sperl 					struct spi_transfer **xferp,
3208d9f12122SMartin Sperl 					size_t maxsize,
3209d9f12122SMartin Sperl 					gfp_t gfp)
3210d9f12122SMartin Sperl {
3211d9f12122SMartin Sperl 	struct spi_transfer *xfer = *xferp, *xfers;
3212d9f12122SMartin Sperl 	struct spi_replaced_transfers *srt;
3213d9f12122SMartin Sperl 	size_t offset;
3214d9f12122SMartin Sperl 	size_t count, i;
3215d9f12122SMartin Sperl 
3216d9f12122SMartin Sperl 	/* calculate how many we have to replace */
3217d9f12122SMartin Sperl 	count = DIV_ROUND_UP(xfer->len, maxsize);
3218d9f12122SMartin Sperl 
3219d9f12122SMartin Sperl 	/* create replacement */
3220d9f12122SMartin Sperl 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3221657d32efSDan Carpenter 	if (IS_ERR(srt))
3222657d32efSDan Carpenter 		return PTR_ERR(srt);
3223d9f12122SMartin Sperl 	xfers = srt->inserted_transfers;
3224d9f12122SMartin Sperl 
3225d9f12122SMartin Sperl 	/* now handle each of those newly inserted spi_transfers
3226d9f12122SMartin Sperl 	 * note that the replacements spi_transfers all are preset
3227d9f12122SMartin Sperl 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3228d9f12122SMartin Sperl 	 * are all identical (as well as most others)
3229d9f12122SMartin Sperl 	 * so we just have to fix up len and the pointers.
3230d9f12122SMartin Sperl 	 *
3231d9f12122SMartin Sperl 	 * this also includes support for the depreciated
3232d9f12122SMartin Sperl 	 * spi_message.is_dma_mapped interface
3233d9f12122SMartin Sperl 	 */
3234d9f12122SMartin Sperl 
3235d9f12122SMartin Sperl 	/* the first transfer just needs the length modified, so we
3236d9f12122SMartin Sperl 	 * run it outside the loop
3237d9f12122SMartin Sperl 	 */
3238c8dab77aSFabio Estevam 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3239d9f12122SMartin Sperl 
3240d9f12122SMartin Sperl 	/* all the others need rx_buf/tx_buf also set */
3241d9f12122SMartin Sperl 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3242d9f12122SMartin Sperl 		/* update rx_buf, tx_buf and dma */
3243d9f12122SMartin Sperl 		if (xfers[i].rx_buf)
3244d9f12122SMartin Sperl 			xfers[i].rx_buf += offset;
3245d9f12122SMartin Sperl 		if (xfers[i].rx_dma)
3246d9f12122SMartin Sperl 			xfers[i].rx_dma += offset;
3247d9f12122SMartin Sperl 		if (xfers[i].tx_buf)
3248d9f12122SMartin Sperl 			xfers[i].tx_buf += offset;
3249d9f12122SMartin Sperl 		if (xfers[i].tx_dma)
3250d9f12122SMartin Sperl 			xfers[i].tx_dma += offset;
3251d9f12122SMartin Sperl 
3252d9f12122SMartin Sperl 		/* update length */
3253d9f12122SMartin Sperl 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3254d9f12122SMartin Sperl 	}
3255d9f12122SMartin Sperl 
3256d9f12122SMartin Sperl 	/* we set up xferp to the last entry we have inserted,
3257d9f12122SMartin Sperl 	 * so that we skip those already split transfers
3258d9f12122SMartin Sperl 	 */
3259d9f12122SMartin Sperl 	*xferp = &xfers[count - 1];
3260d9f12122SMartin Sperl 
3261d9f12122SMartin Sperl 	/* increment statistics counters */
32628caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3263d9f12122SMartin Sperl 				       transfers_split_maxsize);
3264d9f12122SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3265d9f12122SMartin Sperl 				       transfers_split_maxsize);
3266d9f12122SMartin Sperl 
3267d9f12122SMartin Sperl 	return 0;
3268d9f12122SMartin Sperl }
3269d9f12122SMartin Sperl 
3270d9f12122SMartin Sperl /**
3271ce2424d7SMauro Carvalho Chehab  * spi_split_transfers_maxsize - split spi transfers into multiple transfers
3272d9f12122SMartin Sperl  *                               when an individual transfer exceeds a
3273d9f12122SMartin Sperl  *                               certain size
32748caab75fSGeert Uytterhoeven  * @ctlr:    the @spi_controller for this transfer
32753700ce95SMasanari Iida  * @msg:   the @spi_message to transform
32763700ce95SMasanari Iida  * @maxsize:  the maximum when to apply this
327710f11a22SJavier Martinez Canillas  * @gfp: GFP allocation flags
3278d9f12122SMartin Sperl  *
3279d9f12122SMartin Sperl  * Return: status of transformation
3280d9f12122SMartin Sperl  */
32818caab75fSGeert Uytterhoeven int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3282d9f12122SMartin Sperl 				struct spi_message *msg,
3283d9f12122SMartin Sperl 				size_t maxsize,
3284d9f12122SMartin Sperl 				gfp_t gfp)
3285d9f12122SMartin Sperl {
3286d9f12122SMartin Sperl 	struct spi_transfer *xfer;
3287d9f12122SMartin Sperl 	int ret;
3288d9f12122SMartin Sperl 
3289d9f12122SMartin Sperl 	/* iterate over the transfer_list,
3290d9f12122SMartin Sperl 	 * but note that xfer is advanced to the last transfer inserted
3291d9f12122SMartin Sperl 	 * to avoid checking sizes again unnecessarily (also xfer does
3292d9f12122SMartin Sperl 	 * potentiall belong to a different list by the time the
3293d9f12122SMartin Sperl 	 * replacement has happened
3294d9f12122SMartin Sperl 	 */
3295d9f12122SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3296d9f12122SMartin Sperl 		if (xfer->len > maxsize) {
32978caab75fSGeert Uytterhoeven 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
32988caab75fSGeert Uytterhoeven 							   maxsize, gfp);
3299d9f12122SMartin Sperl 			if (ret)
3300d9f12122SMartin Sperl 				return ret;
3301d9f12122SMartin Sperl 		}
3302d9f12122SMartin Sperl 	}
3303d9f12122SMartin Sperl 
3304d9f12122SMartin Sperl 	return 0;
3305d9f12122SMartin Sperl }
3306d9f12122SMartin Sperl EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
33078ae12a0dSDavid Brownell 
33088ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
33098ae12a0dSDavid Brownell 
33108caab75fSGeert Uytterhoeven /* Core methods for SPI controller protocol drivers.  Some of the
33117d077197SDavid Brownell  * other core methods are currently defined as inline functions.
33127d077197SDavid Brownell  */
33137d077197SDavid Brownell 
33148caab75fSGeert Uytterhoeven static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
33158caab75fSGeert Uytterhoeven 					u8 bits_per_word)
331663ab645fSStefan Brüns {
33178caab75fSGeert Uytterhoeven 	if (ctlr->bits_per_word_mask) {
331863ab645fSStefan Brüns 		/* Only 32 bits fit in the mask */
331963ab645fSStefan Brüns 		if (bits_per_word > 32)
332063ab645fSStefan Brüns 			return -EINVAL;
33218caab75fSGeert Uytterhoeven 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
332263ab645fSStefan Brüns 			return -EINVAL;
332363ab645fSStefan Brüns 	}
332463ab645fSStefan Brüns 
332563ab645fSStefan Brüns 	return 0;
332663ab645fSStefan Brüns }
332763ab645fSStefan Brüns 
33287d077197SDavid Brownell /**
33297d077197SDavid Brownell  * spi_setup - setup SPI mode and clock rate
33307d077197SDavid Brownell  * @spi: the device whose settings are being modified
33317d077197SDavid Brownell  * Context: can sleep, and no requests are queued to the device
33327d077197SDavid Brownell  *
33337d077197SDavid Brownell  * SPI protocol drivers may need to update the transfer mode if the
33347d077197SDavid Brownell  * device doesn't work with its default.  They may likewise need
33357d077197SDavid Brownell  * to update clock rates or word sizes from initial values.  This function
33367d077197SDavid Brownell  * changes those settings, and must be called from a context that can sleep.
33377d077197SDavid Brownell  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
33387d077197SDavid Brownell  * effect the next time the device is selected and data is transferred to
33397d077197SDavid Brownell  * or from it.  When this function returns, the spi device is deselected.
33407d077197SDavid Brownell  *
33417d077197SDavid Brownell  * Note that this call will fail if the protocol driver specifies an option
33427d077197SDavid Brownell  * that the underlying controller or its driver does not support.  For
33437d077197SDavid Brownell  * example, not all hardware supports wire transfers using nine bit words,
33447d077197SDavid Brownell  * LSB-first wire encoding, or active-high chipselects.
334597d56dc6SJavier Martinez Canillas  *
334697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
33477d077197SDavid Brownell  */
33487d077197SDavid Brownell int spi_setup(struct spi_device *spi)
33497d077197SDavid Brownell {
335083596fbeSGeert Uytterhoeven 	unsigned	bad_bits, ugly_bits;
33515ab8d262SAndy Shevchenko 	int		status;
33527d077197SDavid Brownell 
3353d962608cSDragos Bogdan 	/*
3354d962608cSDragos Bogdan 	 * check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
3355d962608cSDragos Bogdan 	 * are set at the same time
3356f477b7fbSwangyuhang 	 */
3357d962608cSDragos Bogdan 	if ((hweight_long(spi->mode &
3358d962608cSDragos Bogdan 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
3359d962608cSDragos Bogdan 	    (hweight_long(spi->mode &
3360d962608cSDragos Bogdan 		(SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
3361f477b7fbSwangyuhang 		dev_err(&spi->dev,
3362d962608cSDragos Bogdan 		"setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
3363f477b7fbSwangyuhang 		return -EINVAL;
3364f477b7fbSwangyuhang 	}
3365f477b7fbSwangyuhang 	/* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3366f477b7fbSwangyuhang 	 */
3367f477b7fbSwangyuhang 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
33686b03061fSYogesh Narayan Gaur 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
33696b03061fSYogesh Narayan Gaur 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3370f477b7fbSwangyuhang 		return -EINVAL;
3371e7db06b5SDavid Brownell 	/* help drivers fail *cleanly* when they need options
33728caab75fSGeert Uytterhoeven 	 * that aren't supported with their current controller
3373cbaa62e0SDavid Lechner 	 * SPI_CS_WORD has a fallback software implementation,
3374cbaa62e0SDavid Lechner 	 * so it is ignored here.
3375e7db06b5SDavid Brownell 	 */
3376d962608cSDragos Bogdan 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
3377d962608cSDragos Bogdan 				 SPI_NO_TX | SPI_NO_RX);
3378d61ad23cSSerge Semin 	/* nothing prevents from working with active-high CS in case if it
3379d61ad23cSSerge Semin 	 * is driven by GPIO.
3380d61ad23cSSerge Semin 	 */
3381d61ad23cSSerge Semin 	if (gpio_is_valid(spi->cs_gpio))
3382d61ad23cSSerge Semin 		bad_bits &= ~SPI_CS_HIGH;
338383596fbeSGeert Uytterhoeven 	ugly_bits = bad_bits &
33846b03061fSYogesh Narayan Gaur 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
33856b03061fSYogesh Narayan Gaur 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
338683596fbeSGeert Uytterhoeven 	if (ugly_bits) {
338783596fbeSGeert Uytterhoeven 		dev_warn(&spi->dev,
338883596fbeSGeert Uytterhoeven 			 "setup: ignoring unsupported mode bits %x\n",
338983596fbeSGeert Uytterhoeven 			 ugly_bits);
339083596fbeSGeert Uytterhoeven 		spi->mode &= ~ugly_bits;
339183596fbeSGeert Uytterhoeven 		bad_bits &= ~ugly_bits;
339283596fbeSGeert Uytterhoeven 	}
3393e7db06b5SDavid Brownell 	if (bad_bits) {
3394eb288a1fSLinus Walleij 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3395e7db06b5SDavid Brownell 			bad_bits);
3396e7db06b5SDavid Brownell 		return -EINVAL;
3397e7db06b5SDavid Brownell 	}
3398e7db06b5SDavid Brownell 
33997d077197SDavid Brownell 	if (!spi->bits_per_word)
34007d077197SDavid Brownell 		spi->bits_per_word = 8;
34017d077197SDavid Brownell 
34028caab75fSGeert Uytterhoeven 	status = __spi_validate_bits_per_word(spi->controller,
34038caab75fSGeert Uytterhoeven 					      spi->bits_per_word);
34045ab8d262SAndy Shevchenko 	if (status)
34055ab8d262SAndy Shevchenko 		return status;
340663ab645fSStefan Brüns 
34076820e812STudor Ambarus 	if (spi->controller->max_speed_hz &&
34086820e812STudor Ambarus 	    (!spi->max_speed_hz ||
34096820e812STudor Ambarus 	     spi->max_speed_hz > spi->controller->max_speed_hz))
34108caab75fSGeert Uytterhoeven 		spi->max_speed_hz = spi->controller->max_speed_hz;
3411052eb2d4SAxel Lin 
34124fae3a58SSerge Semin 	mutex_lock(&spi->controller->io_mutex);
34134fae3a58SSerge Semin 
34148caab75fSGeert Uytterhoeven 	if (spi->controller->setup)
34158caab75fSGeert Uytterhoeven 		status = spi->controller->setup(spi);
34167d077197SDavid Brownell 
3417d948e6caSLuhua Xu 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3418d948e6caSLuhua Xu 		status = pm_runtime_get_sync(spi->controller->dev.parent);
3419d948e6caSLuhua Xu 		if (status < 0) {
34204fae3a58SSerge Semin 			mutex_unlock(&spi->controller->io_mutex);
3421d948e6caSLuhua Xu 			pm_runtime_put_noidle(spi->controller->dev.parent);
3422d948e6caSLuhua Xu 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3423d948e6caSLuhua Xu 				status);
3424d948e6caSLuhua Xu 			return status;
3425d948e6caSLuhua Xu 		}
342657a94607STony Lindgren 
342757a94607STony Lindgren 		/*
342857a94607STony Lindgren 		 * We do not want to return positive value from pm_runtime_get,
342957a94607STony Lindgren 		 * there are many instances of devices calling spi_setup() and
343057a94607STony Lindgren 		 * checking for a non-zero return value instead of a negative
343157a94607STony Lindgren 		 * return value.
343257a94607STony Lindgren 		 */
343357a94607STony Lindgren 		status = 0;
343457a94607STony Lindgren 
3435abeedb01SFranklin S Cooper Jr 		spi_set_cs(spi, false);
3436d948e6caSLuhua Xu 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3437d948e6caSLuhua Xu 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3438d948e6caSLuhua Xu 	} else {
3439d948e6caSLuhua Xu 		spi_set_cs(spi, false);
3440d948e6caSLuhua Xu 	}
3441abeedb01SFranklin S Cooper Jr 
34424fae3a58SSerge Semin 	mutex_unlock(&spi->controller->io_mutex);
34434fae3a58SSerge Semin 
3444924b5867SDouglas Anderson 	if (spi->rt && !spi->controller->rt) {
3445924b5867SDouglas Anderson 		spi->controller->rt = true;
3446924b5867SDouglas Anderson 		spi_set_thread_rt(spi->controller);
3447924b5867SDouglas Anderson 	}
3448924b5867SDouglas Anderson 
34495fe5f05eSJingoo Han 	dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
34507d077197SDavid Brownell 			(int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
34517d077197SDavid Brownell 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
34527d077197SDavid Brownell 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
34537d077197SDavid Brownell 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
34547d077197SDavid Brownell 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
34557d077197SDavid Brownell 			spi->bits_per_word, spi->max_speed_hz,
34567d077197SDavid Brownell 			status);
34577d077197SDavid Brownell 
34587d077197SDavid Brownell 	return status;
34597d077197SDavid Brownell }
34607d077197SDavid Brownell EXPORT_SYMBOL_GPL(spi_setup);
34617d077197SDavid Brownell 
3462f1ca9992SSowjanya Komatineni /**
3463f1ca9992SSowjanya Komatineni  * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3464f1ca9992SSowjanya Komatineni  * @spi: the device that requires specific CS timing configuration
346581059366SAlexandru Ardelean  * @setup: CS setup time specified via @spi_delay
346681059366SAlexandru Ardelean  * @hold: CS hold time specified via @spi_delay
346781059366SAlexandru Ardelean  * @inactive: CS inactive delay between transfers specified via @spi_delay
346881059366SAlexandru Ardelean  *
346981059366SAlexandru Ardelean  * Return: zero on success, else a negative error code.
3470f1ca9992SSowjanya Komatineni  */
347181059366SAlexandru Ardelean int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
347281059366SAlexandru Ardelean 		      struct spi_delay *hold, struct spi_delay *inactive)
3473f1ca9992SSowjanya Komatineni {
34744cea6b8cSleilk.liu 	struct device *parent = spi->controller->dev.parent;
347525093bdeSAlexandru Ardelean 	size_t len;
34764cea6b8cSleilk.liu 	int status;
347725093bdeSAlexandru Ardelean 
34780486d9f9Sleilk.liu 	if (spi->controller->set_cs_timing &&
34790486d9f9Sleilk.liu 	    !(spi->cs_gpiod || gpio_is_valid(spi->cs_gpio))) {
34804cea6b8cSleilk.liu 		if (spi->controller->auto_runtime_pm) {
34814cea6b8cSleilk.liu 			status = pm_runtime_get_sync(parent);
34824cea6b8cSleilk.liu 			if (status < 0) {
34834cea6b8cSleilk.liu 				pm_runtime_put_noidle(parent);
34844cea6b8cSleilk.liu 				dev_err(&spi->controller->dev, "Failed to power device: %d\n",
34854cea6b8cSleilk.liu 					status);
34864cea6b8cSleilk.liu 				return status;
34874cea6b8cSleilk.liu 			}
34884cea6b8cSleilk.liu 
34894cea6b8cSleilk.liu 			status = spi->controller->set_cs_timing(spi, setup,
34904cea6b8cSleilk.liu 								hold, inactive);
34914cea6b8cSleilk.liu 			pm_runtime_mark_last_busy(parent);
34924cea6b8cSleilk.liu 			pm_runtime_put_autosuspend(parent);
34934cea6b8cSleilk.liu 			return status;
34944cea6b8cSleilk.liu 		} else {
349581059366SAlexandru Ardelean 			return spi->controller->set_cs_timing(spi, setup, hold,
349681059366SAlexandru Ardelean 							      inactive);
34974cea6b8cSleilk.liu 		}
34984cea6b8cSleilk.liu 	}
349925093bdeSAlexandru Ardelean 
350025093bdeSAlexandru Ardelean 	if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
350125093bdeSAlexandru Ardelean 	    (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
350225093bdeSAlexandru Ardelean 	    (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
350325093bdeSAlexandru Ardelean 		dev_err(&spi->dev,
350425093bdeSAlexandru Ardelean 			"Clock-cycle delays for CS not supported in SW mode\n");
350581059366SAlexandru Ardelean 		return -ENOTSUPP;
3506f1ca9992SSowjanya Komatineni 	}
350725093bdeSAlexandru Ardelean 
350825093bdeSAlexandru Ardelean 	len = sizeof(struct spi_delay);
350925093bdeSAlexandru Ardelean 
351025093bdeSAlexandru Ardelean 	/* copy delays to controller */
351125093bdeSAlexandru Ardelean 	if (setup)
351225093bdeSAlexandru Ardelean 		memcpy(&spi->controller->cs_setup, setup, len);
351325093bdeSAlexandru Ardelean 	else
351425093bdeSAlexandru Ardelean 		memset(&spi->controller->cs_setup, 0, len);
351525093bdeSAlexandru Ardelean 
351625093bdeSAlexandru Ardelean 	if (hold)
351725093bdeSAlexandru Ardelean 		memcpy(&spi->controller->cs_hold, hold, len);
351825093bdeSAlexandru Ardelean 	else
351925093bdeSAlexandru Ardelean 		memset(&spi->controller->cs_hold, 0, len);
352025093bdeSAlexandru Ardelean 
352125093bdeSAlexandru Ardelean 	if (inactive)
352225093bdeSAlexandru Ardelean 		memcpy(&spi->controller->cs_inactive, inactive, len);
352325093bdeSAlexandru Ardelean 	else
352425093bdeSAlexandru Ardelean 		memset(&spi->controller->cs_inactive, 0, len);
352525093bdeSAlexandru Ardelean 
352625093bdeSAlexandru Ardelean 	return 0;
3527f1ca9992SSowjanya Komatineni }
3528f1ca9992SSowjanya Komatineni EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3529f1ca9992SSowjanya Komatineni 
35306c613f68SAlexandru Ardelean static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
35316c613f68SAlexandru Ardelean 				       struct spi_device *spi)
35326c613f68SAlexandru Ardelean {
35336c613f68SAlexandru Ardelean 	int delay1, delay2;
35346c613f68SAlexandru Ardelean 
35353984d39bSAlexandru Ardelean 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
35366c613f68SAlexandru Ardelean 	if (delay1 < 0)
35376c613f68SAlexandru Ardelean 		return delay1;
35386c613f68SAlexandru Ardelean 
35393984d39bSAlexandru Ardelean 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
35406c613f68SAlexandru Ardelean 	if (delay2 < 0)
35416c613f68SAlexandru Ardelean 		return delay2;
35426c613f68SAlexandru Ardelean 
35436c613f68SAlexandru Ardelean 	if (delay1 < delay2)
35446c613f68SAlexandru Ardelean 		memcpy(&xfer->word_delay, &spi->word_delay,
35456c613f68SAlexandru Ardelean 		       sizeof(xfer->word_delay));
35466c613f68SAlexandru Ardelean 
35476c613f68SAlexandru Ardelean 	return 0;
35486c613f68SAlexandru Ardelean }
35496c613f68SAlexandru Ardelean 
355090808738SMark Brown static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3551cf32b71eSErnst Schwab {
35528caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3553e6811d1dSLaxman Dewangan 	struct spi_transfer *xfer;
35546ea31293SAtsushi Nemoto 	int w_size;
3555cf32b71eSErnst Schwab 
355624a0013aSMark Brown 	if (list_empty(&message->transfers))
355724a0013aSMark Brown 		return -EINVAL;
355824a0013aSMark Brown 
3559cbaa62e0SDavid Lechner 	/* If an SPI controller does not support toggling the CS line on each
356071388b21SDavid Lechner 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
356171388b21SDavid Lechner 	 * for the CS line, we can emulate the CS-per-word hardware function by
3562cbaa62e0SDavid Lechner 	 * splitting transfers into one-word transfers and ensuring that
3563cbaa62e0SDavid Lechner 	 * cs_change is set for each transfer.
3564cbaa62e0SDavid Lechner 	 */
356571388b21SDavid Lechner 	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3566f3186dd8SLinus Walleij 					  spi->cs_gpiod ||
356771388b21SDavid Lechner 					  gpio_is_valid(spi->cs_gpio))) {
3568cbaa62e0SDavid Lechner 		size_t maxsize;
3569cbaa62e0SDavid Lechner 		int ret;
3570cbaa62e0SDavid Lechner 
3571cbaa62e0SDavid Lechner 		maxsize = (spi->bits_per_word + 7) / 8;
3572cbaa62e0SDavid Lechner 
3573cbaa62e0SDavid Lechner 		/* spi_split_transfers_maxsize() requires message->spi */
3574cbaa62e0SDavid Lechner 		message->spi = spi;
3575cbaa62e0SDavid Lechner 
3576cbaa62e0SDavid Lechner 		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3577cbaa62e0SDavid Lechner 						  GFP_KERNEL);
3578cbaa62e0SDavid Lechner 		if (ret)
3579cbaa62e0SDavid Lechner 			return ret;
3580cbaa62e0SDavid Lechner 
3581cbaa62e0SDavid Lechner 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3582cbaa62e0SDavid Lechner 			/* don't change cs_change on the last entry in the list */
3583cbaa62e0SDavid Lechner 			if (list_is_last(&xfer->transfer_list, &message->transfers))
3584cbaa62e0SDavid Lechner 				break;
3585cbaa62e0SDavid Lechner 			xfer->cs_change = 1;
3586cbaa62e0SDavid Lechner 		}
3587cbaa62e0SDavid Lechner 	}
3588cbaa62e0SDavid Lechner 
3589cf32b71eSErnst Schwab 	/* Half-duplex links include original MicroWire, and ones with
3590cf32b71eSErnst Schwab 	 * only one data pin like SPI_3WIRE (switches direction) or where
3591cf32b71eSErnst Schwab 	 * either MOSI or MISO is missing.  They can also be caused by
3592cf32b71eSErnst Schwab 	 * software limitations.
3593cf32b71eSErnst Schwab 	 */
35948caab75fSGeert Uytterhoeven 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
35958caab75fSGeert Uytterhoeven 	    (spi->mode & SPI_3WIRE)) {
35968caab75fSGeert Uytterhoeven 		unsigned flags = ctlr->flags;
3597cf32b71eSErnst Schwab 
3598cf32b71eSErnst Schwab 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3599cf32b71eSErnst Schwab 			if (xfer->rx_buf && xfer->tx_buf)
3600cf32b71eSErnst Schwab 				return -EINVAL;
36018caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3602cf32b71eSErnst Schwab 				return -EINVAL;
36038caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3604cf32b71eSErnst Schwab 				return -EINVAL;
3605cf32b71eSErnst Schwab 		}
3606cf32b71eSErnst Schwab 	}
3607cf32b71eSErnst Schwab 
3608e6811d1dSLaxman Dewangan 	/**
3609059b8ffeSLaxman Dewangan 	 * Set transfer bits_per_word and max speed as spi device default if
3610059b8ffeSLaxman Dewangan 	 * it is not set for this transfer.
3611f477b7fbSwangyuhang 	 * Set transfer tx_nbits and rx_nbits as single transfer default
3612f477b7fbSwangyuhang 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3613b7bb367aSJonas Bonn 	 * Ensure transfer word_delay is at least as long as that required by
3614b7bb367aSJonas Bonn 	 * device itself.
3615e6811d1dSLaxman Dewangan 	 */
361677e80588SMartin Sperl 	message->frame_length = 0;
3617e6811d1dSLaxman Dewangan 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
36185d7e2b5eSMartin Sperl 		xfer->effective_speed_hz = 0;
3619078726ceSSourav Poddar 		message->frame_length += xfer->len;
3620e6811d1dSLaxman Dewangan 		if (!xfer->bits_per_word)
3621e6811d1dSLaxman Dewangan 			xfer->bits_per_word = spi->bits_per_word;
3622a6f87fadSAxel Lin 
3623a6f87fadSAxel Lin 		if (!xfer->speed_hz)
3624059b8ffeSLaxman Dewangan 			xfer->speed_hz = spi->max_speed_hz;
3625a6f87fadSAxel Lin 
36268caab75fSGeert Uytterhoeven 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
36278caab75fSGeert Uytterhoeven 			xfer->speed_hz = ctlr->max_speed_hz;
362856ede94aSGabor Juhos 
36298caab75fSGeert Uytterhoeven 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3630543bb255SStephen Warren 			return -EINVAL;
3631a2fd4f9fSMark Brown 
36324d94bd21SIvan T. Ivanov 		/*
36334d94bd21SIvan T. Ivanov 		 * SPI transfer length should be multiple of SPI word size
36344d94bd21SIvan T. Ivanov 		 * where SPI word size should be power-of-two multiple
36354d94bd21SIvan T. Ivanov 		 */
36364d94bd21SIvan T. Ivanov 		if (xfer->bits_per_word <= 8)
36374d94bd21SIvan T. Ivanov 			w_size = 1;
36384d94bd21SIvan T. Ivanov 		else if (xfer->bits_per_word <= 16)
36394d94bd21SIvan T. Ivanov 			w_size = 2;
36404d94bd21SIvan T. Ivanov 		else
36414d94bd21SIvan T. Ivanov 			w_size = 4;
36424d94bd21SIvan T. Ivanov 
36434d94bd21SIvan T. Ivanov 		/* No partial transfers accepted */
36446ea31293SAtsushi Nemoto 		if (xfer->len % w_size)
36454d94bd21SIvan T. Ivanov 			return -EINVAL;
36464d94bd21SIvan T. Ivanov 
36478caab75fSGeert Uytterhoeven 		if (xfer->speed_hz && ctlr->min_speed_hz &&
36488caab75fSGeert Uytterhoeven 		    xfer->speed_hz < ctlr->min_speed_hz)
3649a2fd4f9fSMark Brown 			return -EINVAL;
3650f477b7fbSwangyuhang 
3651f477b7fbSwangyuhang 		if (xfer->tx_buf && !xfer->tx_nbits)
3652f477b7fbSwangyuhang 			xfer->tx_nbits = SPI_NBITS_SINGLE;
3653f477b7fbSwangyuhang 		if (xfer->rx_buf && !xfer->rx_nbits)
3654f477b7fbSwangyuhang 			xfer->rx_nbits = SPI_NBITS_SINGLE;
3655f477b7fbSwangyuhang 		/* check transfer tx/rx_nbits:
36561afd9989SGeert Uytterhoeven 		 * 1. check the value matches one of single, dual and quad
36571afd9989SGeert Uytterhoeven 		 * 2. check tx/rx_nbits match the mode in spi_device
3658f477b7fbSwangyuhang 		 */
3659db90a441SSourav Poddar 		if (xfer->tx_buf) {
3660d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_TX)
3661d962608cSDragos Bogdan 				return -EINVAL;
3662f477b7fbSwangyuhang 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3663f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_DUAL &&
3664f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_QUAD)
3665a2fd4f9fSMark Brown 				return -EINVAL;
3666f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3667f477b7fbSwangyuhang 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3668f477b7fbSwangyuhang 				return -EINVAL;
3669f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3670f477b7fbSwangyuhang 				!(spi->mode & SPI_TX_QUAD))
3671f477b7fbSwangyuhang 				return -EINVAL;
3672db90a441SSourav Poddar 		}
3673f477b7fbSwangyuhang 		/* check transfer rx_nbits */
3674db90a441SSourav Poddar 		if (xfer->rx_buf) {
3675d962608cSDragos Bogdan 			if (spi->mode & SPI_NO_RX)
3676d962608cSDragos Bogdan 				return -EINVAL;
3677f477b7fbSwangyuhang 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3678f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_DUAL &&
3679f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_QUAD)
3680f477b7fbSwangyuhang 				return -EINVAL;
3681f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3682f477b7fbSwangyuhang 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3683f477b7fbSwangyuhang 				return -EINVAL;
3684f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3685f477b7fbSwangyuhang 				!(spi->mode & SPI_RX_QUAD))
3686f477b7fbSwangyuhang 				return -EINVAL;
3687e6811d1dSLaxman Dewangan 		}
3688b7bb367aSJonas Bonn 
36896c613f68SAlexandru Ardelean 		if (_spi_xfer_word_delay_update(xfer, spi))
36906c613f68SAlexandru Ardelean 			return -EINVAL;
3691e6811d1dSLaxman Dewangan 	}
3692e6811d1dSLaxman Dewangan 
3693cf32b71eSErnst Schwab 	message->status = -EINPROGRESS;
369490808738SMark Brown 
369590808738SMark Brown 	return 0;
369690808738SMark Brown }
369790808738SMark Brown 
369890808738SMark Brown static int __spi_async(struct spi_device *spi, struct spi_message *message)
369990808738SMark Brown {
37008caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3701b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
370290808738SMark Brown 
3703b5932f5cSBoris Brezillon 	/*
3704b5932f5cSBoris Brezillon 	 * Some controllers do not support doing regular SPI transfers. Return
3705b5932f5cSBoris Brezillon 	 * ENOTSUPP when this is the case.
3706b5932f5cSBoris Brezillon 	 */
3707b5932f5cSBoris Brezillon 	if (!ctlr->transfer)
3708b5932f5cSBoris Brezillon 		return -ENOTSUPP;
3709b5932f5cSBoris Brezillon 
371090808738SMark Brown 	message->spi = spi;
371190808738SMark Brown 
37128caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3713eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3714eca2ebc7SMartin Sperl 
371590808738SMark Brown 	trace_spi_message_submit(message);
371690808738SMark Brown 
3717b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported) {
3718b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3719b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
3720b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
3721b42faeeeSVladimir Oltean 		}
3722b42faeeeSVladimir Oltean 	}
3723b42faeeeSVladimir Oltean 
37248caab75fSGeert Uytterhoeven 	return ctlr->transfer(spi, message);
3725cf32b71eSErnst Schwab }
3726cf32b71eSErnst Schwab 
3727568d0697SDavid Brownell /**
3728568d0697SDavid Brownell  * spi_async - asynchronous SPI transfer
3729568d0697SDavid Brownell  * @spi: device with which data will be exchanged
3730568d0697SDavid Brownell  * @message: describes the data transfers, including completion callback
3731568d0697SDavid Brownell  * Context: any (irqs may be blocked, etc)
3732568d0697SDavid Brownell  *
3733568d0697SDavid Brownell  * This call may be used in_irq and other contexts which can't sleep,
3734568d0697SDavid Brownell  * as well as from task contexts which can sleep.
3735568d0697SDavid Brownell  *
3736568d0697SDavid Brownell  * The completion callback is invoked in a context which can't sleep.
3737568d0697SDavid Brownell  * Before that invocation, the value of message->status is undefined.
3738568d0697SDavid Brownell  * When the callback is issued, message->status holds either zero (to
3739568d0697SDavid Brownell  * indicate complete success) or a negative error code.  After that
3740568d0697SDavid Brownell  * callback returns, the driver which issued the transfer request may
3741568d0697SDavid Brownell  * deallocate the associated memory; it's no longer in use by any SPI
3742568d0697SDavid Brownell  * core or controller driver code.
3743568d0697SDavid Brownell  *
3744568d0697SDavid Brownell  * Note that although all messages to a spi_device are handled in
3745568d0697SDavid Brownell  * FIFO order, messages may go to different devices in other orders.
3746568d0697SDavid Brownell  * Some device might be higher priority, or have various "hard" access
3747568d0697SDavid Brownell  * time requirements, for example.
3748568d0697SDavid Brownell  *
3749568d0697SDavid Brownell  * On detection of any fault during the transfer, processing of
3750568d0697SDavid Brownell  * the entire message is aborted, and the device is deselected.
3751568d0697SDavid Brownell  * Until returning from the associated message completion callback,
3752568d0697SDavid Brownell  * no other spi_message queued to that device will be processed.
3753568d0697SDavid Brownell  * (This rule applies equally to all the synchronous transfer calls,
3754568d0697SDavid Brownell  * which are wrappers around this core asynchronous primitive.)
375597d56dc6SJavier Martinez Canillas  *
375697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3757568d0697SDavid Brownell  */
3758568d0697SDavid Brownell int spi_async(struct spi_device *spi, struct spi_message *message)
3759568d0697SDavid Brownell {
37608caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3761cf32b71eSErnst Schwab 	int ret;
3762cf32b71eSErnst Schwab 	unsigned long flags;
3763568d0697SDavid Brownell 
376490808738SMark Brown 	ret = __spi_validate(spi, message);
376590808738SMark Brown 	if (ret != 0)
376690808738SMark Brown 		return ret;
376790808738SMark Brown 
37688caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3769568d0697SDavid Brownell 
37708caab75fSGeert Uytterhoeven 	if (ctlr->bus_lock_flag)
3771cf32b71eSErnst Schwab 		ret = -EBUSY;
3772cf32b71eSErnst Schwab 	else
3773cf32b71eSErnst Schwab 		ret = __spi_async(spi, message);
3774568d0697SDavid Brownell 
37758caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3776cf32b71eSErnst Schwab 
3777cf32b71eSErnst Schwab 	return ret;
3778568d0697SDavid Brownell }
3779568d0697SDavid Brownell EXPORT_SYMBOL_GPL(spi_async);
3780568d0697SDavid Brownell 
3781cf32b71eSErnst Schwab /**
3782cf32b71eSErnst Schwab  * spi_async_locked - version of spi_async with exclusive bus usage
3783cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
3784cf32b71eSErnst Schwab  * @message: describes the data transfers, including completion callback
3785cf32b71eSErnst Schwab  * Context: any (irqs may be blocked, etc)
3786cf32b71eSErnst Schwab  *
3787cf32b71eSErnst Schwab  * This call may be used in_irq and other contexts which can't sleep,
3788cf32b71eSErnst Schwab  * as well as from task contexts which can sleep.
3789cf32b71eSErnst Schwab  *
3790cf32b71eSErnst Schwab  * The completion callback is invoked in a context which can't sleep.
3791cf32b71eSErnst Schwab  * Before that invocation, the value of message->status is undefined.
3792cf32b71eSErnst Schwab  * When the callback is issued, message->status holds either zero (to
3793cf32b71eSErnst Schwab  * indicate complete success) or a negative error code.  After that
3794cf32b71eSErnst Schwab  * callback returns, the driver which issued the transfer request may
3795cf32b71eSErnst Schwab  * deallocate the associated memory; it's no longer in use by any SPI
3796cf32b71eSErnst Schwab  * core or controller driver code.
3797cf32b71eSErnst Schwab  *
3798cf32b71eSErnst Schwab  * Note that although all messages to a spi_device are handled in
3799cf32b71eSErnst Schwab  * FIFO order, messages may go to different devices in other orders.
3800cf32b71eSErnst Schwab  * Some device might be higher priority, or have various "hard" access
3801cf32b71eSErnst Schwab  * time requirements, for example.
3802cf32b71eSErnst Schwab  *
3803cf32b71eSErnst Schwab  * On detection of any fault during the transfer, processing of
3804cf32b71eSErnst Schwab  * the entire message is aborted, and the device is deselected.
3805cf32b71eSErnst Schwab  * Until returning from the associated message completion callback,
3806cf32b71eSErnst Schwab  * no other spi_message queued to that device will be processed.
3807cf32b71eSErnst Schwab  * (This rule applies equally to all the synchronous transfer calls,
3808cf32b71eSErnst Schwab  * which are wrappers around this core asynchronous primitive.)
380997d56dc6SJavier Martinez Canillas  *
381097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3811cf32b71eSErnst Schwab  */
3812cf32b71eSErnst Schwab int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3813cf32b71eSErnst Schwab {
38148caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3815cf32b71eSErnst Schwab 	int ret;
3816cf32b71eSErnst Schwab 	unsigned long flags;
3817cf32b71eSErnst Schwab 
381890808738SMark Brown 	ret = __spi_validate(spi, message);
381990808738SMark Brown 	if (ret != 0)
382090808738SMark Brown 		return ret;
382190808738SMark Brown 
38228caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3823cf32b71eSErnst Schwab 
3824cf32b71eSErnst Schwab 	ret = __spi_async(spi, message);
3825cf32b71eSErnst Schwab 
38268caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3827cf32b71eSErnst Schwab 
3828cf32b71eSErnst Schwab 	return ret;
3829cf32b71eSErnst Schwab 
3830cf32b71eSErnst Schwab }
3831cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_async_locked);
3832cf32b71eSErnst Schwab 
38337d077197SDavid Brownell /*-------------------------------------------------------------------------*/
38347d077197SDavid Brownell 
38358caab75fSGeert Uytterhoeven /* Utility methods for SPI protocol drivers, layered on
38367d077197SDavid Brownell  * top of the core.  Some other utility methods are defined as
38377d077197SDavid Brownell  * inline functions.
38387d077197SDavid Brownell  */
38397d077197SDavid Brownell 
38405d870c8eSAndrew Morton static void spi_complete(void *arg)
38415d870c8eSAndrew Morton {
38425d870c8eSAndrew Morton 	complete(arg);
38435d870c8eSAndrew Morton }
38445d870c8eSAndrew Morton 
3845ef4d96ecSMark Brown static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3846cf32b71eSErnst Schwab {
3847cf32b71eSErnst Schwab 	DECLARE_COMPLETION_ONSTACK(done);
3848cf32b71eSErnst Schwab 	int status;
38498caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
38500461a414SMark Brown 	unsigned long flags;
38510461a414SMark Brown 
38520461a414SMark Brown 	status = __spi_validate(spi, message);
38530461a414SMark Brown 	if (status != 0)
38540461a414SMark Brown 		return status;
3855cf32b71eSErnst Schwab 
3856cf32b71eSErnst Schwab 	message->complete = spi_complete;
3857cf32b71eSErnst Schwab 	message->context = &done;
38580461a414SMark Brown 	message->spi = spi;
3859cf32b71eSErnst Schwab 
38608caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3861eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3862eca2ebc7SMartin Sperl 
38630461a414SMark Brown 	/* If we're not using the legacy transfer method then we will
38640461a414SMark Brown 	 * try to transfer in the calling context so special case.
38650461a414SMark Brown 	 * This code would be less tricky if we could remove the
38660461a414SMark Brown 	 * support for driver implemented message queues.
38670461a414SMark Brown 	 */
38688caab75fSGeert Uytterhoeven 	if (ctlr->transfer == spi_queued_transfer) {
38698caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
38700461a414SMark Brown 
38710461a414SMark Brown 		trace_spi_message_submit(message);
38720461a414SMark Brown 
38730461a414SMark Brown 		status = __spi_queued_transfer(spi, message, false);
38740461a414SMark Brown 
38758caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
38760461a414SMark Brown 	} else {
3877cf32b71eSErnst Schwab 		status = spi_async_locked(spi, message);
38780461a414SMark Brown 	}
3879cf32b71eSErnst Schwab 
3880cf32b71eSErnst Schwab 	if (status == 0) {
38810461a414SMark Brown 		/* Push out the messages in the calling context if we
38820461a414SMark Brown 		 * can.
38830461a414SMark Brown 		 */
38848caab75fSGeert Uytterhoeven 		if (ctlr->transfer == spi_queued_transfer) {
38858caab75fSGeert Uytterhoeven 			SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3886eca2ebc7SMartin Sperl 						       spi_sync_immediate);
3887eca2ebc7SMartin Sperl 			SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3888eca2ebc7SMartin Sperl 						       spi_sync_immediate);
38898caab75fSGeert Uytterhoeven 			__spi_pump_messages(ctlr, false);
3890eca2ebc7SMartin Sperl 		}
38910461a414SMark Brown 
3892cf32b71eSErnst Schwab 		wait_for_completion(&done);
3893cf32b71eSErnst Schwab 		status = message->status;
3894cf32b71eSErnst Schwab 	}
3895cf32b71eSErnst Schwab 	message->context = NULL;
3896cf32b71eSErnst Schwab 	return status;
3897cf32b71eSErnst Schwab }
3898cf32b71eSErnst Schwab 
38998ae12a0dSDavid Brownell /**
39008ae12a0dSDavid Brownell  * spi_sync - blocking/synchronous SPI data transfers
39018ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
39028ae12a0dSDavid Brownell  * @message: describes the data transfers
390333e34dc6SDavid Brownell  * Context: can sleep
39048ae12a0dSDavid Brownell  *
39058ae12a0dSDavid Brownell  * This call may only be used from a context that may sleep.  The sleep
39068ae12a0dSDavid Brownell  * is non-interruptible, and has no timeout.  Low-overhead controller
39078ae12a0dSDavid Brownell  * drivers may DMA directly into and out of the message buffers.
39088ae12a0dSDavid Brownell  *
39098ae12a0dSDavid Brownell  * Note that the SPI device's chip select is active during the message,
39108ae12a0dSDavid Brownell  * and then is normally disabled between messages.  Drivers for some
39118ae12a0dSDavid Brownell  * frequently-used devices may want to minimize costs of selecting a chip,
39128ae12a0dSDavid Brownell  * by leaving it selected in anticipation that the next message will go
39138ae12a0dSDavid Brownell  * to the same chip.  (That may increase power usage.)
39148ae12a0dSDavid Brownell  *
39150c868461SDavid Brownell  * Also, the caller is guaranteeing that the memory associated with the
39160c868461SDavid Brownell  * message will not be freed before this call returns.
39170c868461SDavid Brownell  *
391897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
39198ae12a0dSDavid Brownell  */
39208ae12a0dSDavid Brownell int spi_sync(struct spi_device *spi, struct spi_message *message)
39218ae12a0dSDavid Brownell {
3922ef4d96ecSMark Brown 	int ret;
3923ef4d96ecSMark Brown 
39248caab75fSGeert Uytterhoeven 	mutex_lock(&spi->controller->bus_lock_mutex);
3925ef4d96ecSMark Brown 	ret = __spi_sync(spi, message);
39268caab75fSGeert Uytterhoeven 	mutex_unlock(&spi->controller->bus_lock_mutex);
3927ef4d96ecSMark Brown 
3928ef4d96ecSMark Brown 	return ret;
39298ae12a0dSDavid Brownell }
39308ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_sync);
39318ae12a0dSDavid Brownell 
3932cf32b71eSErnst Schwab /**
3933cf32b71eSErnst Schwab  * spi_sync_locked - version of spi_sync with exclusive bus usage
3934cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
3935cf32b71eSErnst Schwab  * @message: describes the data transfers
3936cf32b71eSErnst Schwab  * Context: can sleep
3937cf32b71eSErnst Schwab  *
3938cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3939cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.  Low-overhead controller
3940cf32b71eSErnst Schwab  * drivers may DMA directly into and out of the message buffers.
3941cf32b71eSErnst Schwab  *
3942cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
394325985edcSLucas De Marchi  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3944cf32b71eSErnst Schwab  * be released by a spi_bus_unlock call when the exclusive access is over.
3945cf32b71eSErnst Schwab  *
394697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3947cf32b71eSErnst Schwab  */
3948cf32b71eSErnst Schwab int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3949cf32b71eSErnst Schwab {
3950ef4d96ecSMark Brown 	return __spi_sync(spi, message);
3951cf32b71eSErnst Schwab }
3952cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_sync_locked);
3953cf32b71eSErnst Schwab 
3954cf32b71eSErnst Schwab /**
3955cf32b71eSErnst Schwab  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
39568caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that should be locked for exclusive bus access
3957cf32b71eSErnst Schwab  * Context: can sleep
3958cf32b71eSErnst Schwab  *
3959cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3960cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
3961cf32b71eSErnst Schwab  *
3962cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
3963cf32b71eSErnst Schwab  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3964cf32b71eSErnst Schwab  * exclusive access is over. Data transfer must be done by spi_sync_locked
3965cf32b71eSErnst Schwab  * and spi_async_locked calls when the SPI bus lock is held.
3966cf32b71eSErnst Schwab  *
396797d56dc6SJavier Martinez Canillas  * Return: always zero.
3968cf32b71eSErnst Schwab  */
39698caab75fSGeert Uytterhoeven int spi_bus_lock(struct spi_controller *ctlr)
3970cf32b71eSErnst Schwab {
3971cf32b71eSErnst Schwab 	unsigned long flags;
3972cf32b71eSErnst Schwab 
39738caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->bus_lock_mutex);
3974cf32b71eSErnst Schwab 
39758caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
39768caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 1;
39778caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3978cf32b71eSErnst Schwab 
3979cf32b71eSErnst Schwab 	/* mutex remains locked until spi_bus_unlock is called */
3980cf32b71eSErnst Schwab 
3981cf32b71eSErnst Schwab 	return 0;
3982cf32b71eSErnst Schwab }
3983cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_lock);
3984cf32b71eSErnst Schwab 
3985cf32b71eSErnst Schwab /**
3986cf32b71eSErnst Schwab  * spi_bus_unlock - release the lock for exclusive SPI bus usage
39878caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that was locked for exclusive bus access
3988cf32b71eSErnst Schwab  * Context: can sleep
3989cf32b71eSErnst Schwab  *
3990cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3991cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
3992cf32b71eSErnst Schwab  *
3993cf32b71eSErnst Schwab  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3994cf32b71eSErnst Schwab  * call.
3995cf32b71eSErnst Schwab  *
399697d56dc6SJavier Martinez Canillas  * Return: always zero.
3997cf32b71eSErnst Schwab  */
39988caab75fSGeert Uytterhoeven int spi_bus_unlock(struct spi_controller *ctlr)
3999cf32b71eSErnst Schwab {
40008caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
4001cf32b71eSErnst Schwab 
40028caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->bus_lock_mutex);
4003cf32b71eSErnst Schwab 
4004cf32b71eSErnst Schwab 	return 0;
4005cf32b71eSErnst Schwab }
4006cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_unlock);
4007cf32b71eSErnst Schwab 
4008a9948b61SDavid Brownell /* portable code must never pass more than 32 bytes */
4009a9948b61SDavid Brownell #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
40108ae12a0dSDavid Brownell 
40118ae12a0dSDavid Brownell static u8	*buf;
40128ae12a0dSDavid Brownell 
40138ae12a0dSDavid Brownell /**
40148ae12a0dSDavid Brownell  * spi_write_then_read - SPI synchronous write followed by read
40158ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
40168ae12a0dSDavid Brownell  * @txbuf: data to be written (need not be dma-safe)
40178ae12a0dSDavid Brownell  * @n_tx: size of txbuf, in bytes
401827570497SJiri Pirko  * @rxbuf: buffer into which data will be read (need not be dma-safe)
401927570497SJiri Pirko  * @n_rx: size of rxbuf, in bytes
402033e34dc6SDavid Brownell  * Context: can sleep
40218ae12a0dSDavid Brownell  *
40228ae12a0dSDavid Brownell  * This performs a half duplex MicroWire style transaction with the
40238ae12a0dSDavid Brownell  * device, sending txbuf and then reading rxbuf.  The return value
40248ae12a0dSDavid Brownell  * is zero for success, else a negative errno status code.
4025b885244eSDavid Brownell  * This call may only be used from a context that may sleep.
40268ae12a0dSDavid Brownell  *
4027c373643bSMark Brown  * Parameters to this routine are always copied using a small buffer.
402833e34dc6SDavid Brownell  * Performance-sensitive or bulk transfer code should instead use
40290c868461SDavid Brownell  * spi_{async,sync}() calls with dma-safe buffers.
403097d56dc6SJavier Martinez Canillas  *
403197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
40328ae12a0dSDavid Brownell  */
40338ae12a0dSDavid Brownell int spi_write_then_read(struct spi_device *spi,
40340c4a1590SMark Brown 		const void *txbuf, unsigned n_tx,
40350c4a1590SMark Brown 		void *rxbuf, unsigned n_rx)
40368ae12a0dSDavid Brownell {
4037068f4070SDavid Brownell 	static DEFINE_MUTEX(lock);
40388ae12a0dSDavid Brownell 
40398ae12a0dSDavid Brownell 	int			status;
40408ae12a0dSDavid Brownell 	struct spi_message	message;
4041bdff549eSDavid Brownell 	struct spi_transfer	x[2];
40428ae12a0dSDavid Brownell 	u8			*local_buf;
40438ae12a0dSDavid Brownell 
4044b3a223eeSMark Brown 	/* Use preallocated DMA-safe buffer if we can.  We can't avoid
4045b3a223eeSMark Brown 	 * copying here, (as a pure convenience thing), but we can
4046b3a223eeSMark Brown 	 * keep heap costs out of the hot path unless someone else is
4047b3a223eeSMark Brown 	 * using the pre-allocated buffer or the transfer is too large.
40488ae12a0dSDavid Brownell 	 */
4049b3a223eeSMark Brown 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
40502cd94c8aSMark Brown 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
40512cd94c8aSMark Brown 				    GFP_KERNEL | GFP_DMA);
4052b3a223eeSMark Brown 		if (!local_buf)
4053b3a223eeSMark Brown 			return -ENOMEM;
4054b3a223eeSMark Brown 	} else {
4055b3a223eeSMark Brown 		local_buf = buf;
4056b3a223eeSMark Brown 	}
40578ae12a0dSDavid Brownell 
40588275c642SVitaly Wool 	spi_message_init(&message);
40595fe5f05eSJingoo Han 	memset(x, 0, sizeof(x));
4060bdff549eSDavid Brownell 	if (n_tx) {
4061bdff549eSDavid Brownell 		x[0].len = n_tx;
4062bdff549eSDavid Brownell 		spi_message_add_tail(&x[0], &message);
4063bdff549eSDavid Brownell 	}
4064bdff549eSDavid Brownell 	if (n_rx) {
4065bdff549eSDavid Brownell 		x[1].len = n_rx;
4066bdff549eSDavid Brownell 		spi_message_add_tail(&x[1], &message);
4067bdff549eSDavid Brownell 	}
40688275c642SVitaly Wool 
40698ae12a0dSDavid Brownell 	memcpy(local_buf, txbuf, n_tx);
4070bdff549eSDavid Brownell 	x[0].tx_buf = local_buf;
4071bdff549eSDavid Brownell 	x[1].rx_buf = local_buf + n_tx;
40728ae12a0dSDavid Brownell 
40738ae12a0dSDavid Brownell 	/* do the i/o */
40748ae12a0dSDavid Brownell 	status = spi_sync(spi, &message);
40759b938b74SMarc Pignat 	if (status == 0)
4076bdff549eSDavid Brownell 		memcpy(rxbuf, x[1].rx_buf, n_rx);
40778ae12a0dSDavid Brownell 
4078bdff549eSDavid Brownell 	if (x[0].tx_buf == buf)
4079068f4070SDavid Brownell 		mutex_unlock(&lock);
40808ae12a0dSDavid Brownell 	else
40818ae12a0dSDavid Brownell 		kfree(local_buf);
40828ae12a0dSDavid Brownell 
40838ae12a0dSDavid Brownell 	return status;
40848ae12a0dSDavid Brownell }
40858ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_write_then_read);
40868ae12a0dSDavid Brownell 
40878ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
40888ae12a0dSDavid Brownell 
40895f143af7SMarco Felsch #if IS_ENABLED(CONFIG_OF)
4090ce79d54aSPantelis Antoniou /* must call put_device() when done with returned spi_device device */
40915f143af7SMarco Felsch struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4092ce79d54aSPantelis Antoniou {
4093cfba5de9SSuzuki K Poulose 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4094cfba5de9SSuzuki K Poulose 
4095ce79d54aSPantelis Antoniou 	return dev ? to_spi_device(dev) : NULL;
4096ce79d54aSPantelis Antoniou }
40975f143af7SMarco Felsch EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
40985f143af7SMarco Felsch #endif /* IS_ENABLED(CONFIG_OF) */
4099ce79d54aSPantelis Antoniou 
41005f143af7SMarco Felsch #if IS_ENABLED(CONFIG_OF_DYNAMIC)
41018caab75fSGeert Uytterhoeven /* the spi controllers are not using spi_bus, so we find it with another way */
41028caab75fSGeert Uytterhoeven static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4103ce79d54aSPantelis Antoniou {
4104ce79d54aSPantelis Antoniou 	struct device *dev;
4105ce79d54aSPantelis Antoniou 
4106cfba5de9SSuzuki K Poulose 	dev = class_find_device_by_of_node(&spi_master_class, node);
41076c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4108cfba5de9SSuzuki K Poulose 		dev = class_find_device_by_of_node(&spi_slave_class, node);
4109ce79d54aSPantelis Antoniou 	if (!dev)
4110ce79d54aSPantelis Antoniou 		return NULL;
4111ce79d54aSPantelis Antoniou 
4112ce79d54aSPantelis Antoniou 	/* reference got in class_find_device */
41138caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
4114ce79d54aSPantelis Antoniou }
4115ce79d54aSPantelis Antoniou 
4116ce79d54aSPantelis Antoniou static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4117ce79d54aSPantelis Antoniou 			 void *arg)
4118ce79d54aSPantelis Antoniou {
4119ce79d54aSPantelis Antoniou 	struct of_reconfig_data *rd = arg;
41208caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
4121ce79d54aSPantelis Antoniou 	struct spi_device *spi;
4122ce79d54aSPantelis Antoniou 
4123ce79d54aSPantelis Antoniou 	switch (of_reconfig_get_state_change(action, arg)) {
4124ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_ADD:
41258caab75fSGeert Uytterhoeven 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
41268caab75fSGeert Uytterhoeven 		if (ctlr == NULL)
4127ce79d54aSPantelis Antoniou 			return NOTIFY_OK;	/* not for us */
4128ce79d54aSPantelis Antoniou 
4129bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
41308caab75fSGeert Uytterhoeven 			put_device(&ctlr->dev);
4131bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4132bd6c1644SGeert Uytterhoeven 		}
4133bd6c1644SGeert Uytterhoeven 
41348caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, rd->dn);
41358caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
4136ce79d54aSPantelis Antoniou 
4137ce79d54aSPantelis Antoniou 		if (IS_ERR(spi)) {
413825c56c88SRob Herring 			pr_err("%s: failed to create for '%pOF'\n",
413925c56c88SRob Herring 					__func__, rd->dn);
4140e0af98a7SRalf Ramsauer 			of_node_clear_flag(rd->dn, OF_POPULATED);
4141ce79d54aSPantelis Antoniou 			return notifier_from_errno(PTR_ERR(spi));
4142ce79d54aSPantelis Antoniou 		}
4143ce79d54aSPantelis Antoniou 		break;
4144ce79d54aSPantelis Antoniou 
4145ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_REMOVE:
4146bd6c1644SGeert Uytterhoeven 		/* already depopulated? */
4147bd6c1644SGeert Uytterhoeven 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4148bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
4149bd6c1644SGeert Uytterhoeven 
4150ce79d54aSPantelis Antoniou 		/* find our device by node */
4151ce79d54aSPantelis Antoniou 		spi = of_find_spi_device_by_node(rd->dn);
4152ce79d54aSPantelis Antoniou 		if (spi == NULL)
4153ce79d54aSPantelis Antoniou 			return NOTIFY_OK;	/* no? not meant for us */
4154ce79d54aSPantelis Antoniou 
4155ce79d54aSPantelis Antoniou 		/* unregister takes one ref away */
4156ce79d54aSPantelis Antoniou 		spi_unregister_device(spi);
4157ce79d54aSPantelis Antoniou 
4158ce79d54aSPantelis Antoniou 		/* and put the reference of the find */
4159ce79d54aSPantelis Antoniou 		put_device(&spi->dev);
4160ce79d54aSPantelis Antoniou 		break;
4161ce79d54aSPantelis Antoniou 	}
4162ce79d54aSPantelis Antoniou 
4163ce79d54aSPantelis Antoniou 	return NOTIFY_OK;
4164ce79d54aSPantelis Antoniou }
4165ce79d54aSPantelis Antoniou 
4166ce79d54aSPantelis Antoniou static struct notifier_block spi_of_notifier = {
4167ce79d54aSPantelis Antoniou 	.notifier_call = of_spi_notify,
4168ce79d54aSPantelis Antoniou };
4169ce79d54aSPantelis Antoniou #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4170ce79d54aSPantelis Antoniou extern struct notifier_block spi_of_notifier;
4171ce79d54aSPantelis Antoniou #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4172ce79d54aSPantelis Antoniou 
41737f24467fSOctavian Purdila #if IS_ENABLED(CONFIG_ACPI)
41748caab75fSGeert Uytterhoeven static int spi_acpi_controller_match(struct device *dev, const void *data)
41757f24467fSOctavian Purdila {
41767f24467fSOctavian Purdila 	return ACPI_COMPANION(dev->parent) == data;
41777f24467fSOctavian Purdila }
41787f24467fSOctavian Purdila 
41798caab75fSGeert Uytterhoeven static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
41807f24467fSOctavian Purdila {
41817f24467fSOctavian Purdila 	struct device *dev;
41827f24467fSOctavian Purdila 
41837f24467fSOctavian Purdila 	dev = class_find_device(&spi_master_class, NULL, adev,
41848caab75fSGeert Uytterhoeven 				spi_acpi_controller_match);
41856c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
41866c364062SGeert Uytterhoeven 		dev = class_find_device(&spi_slave_class, NULL, adev,
41878caab75fSGeert Uytterhoeven 					spi_acpi_controller_match);
41887f24467fSOctavian Purdila 	if (!dev)
41897f24467fSOctavian Purdila 		return NULL;
41907f24467fSOctavian Purdila 
41918caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
41927f24467fSOctavian Purdila }
41937f24467fSOctavian Purdila 
41947f24467fSOctavian Purdila static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
41957f24467fSOctavian Purdila {
41967f24467fSOctavian Purdila 	struct device *dev;
41977f24467fSOctavian Purdila 
419800500147SSuzuki K Poulose 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
41995b16668eSWolfram Sang 	return to_spi_device(dev);
42007f24467fSOctavian Purdila }
42017f24467fSOctavian Purdila 
42027f24467fSOctavian Purdila static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
42037f24467fSOctavian Purdila 			   void *arg)
42047f24467fSOctavian Purdila {
42057f24467fSOctavian Purdila 	struct acpi_device *adev = arg;
42068caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
42077f24467fSOctavian Purdila 	struct spi_device *spi;
42087f24467fSOctavian Purdila 
42097f24467fSOctavian Purdila 	switch (value) {
42107f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_ADD:
42118caab75fSGeert Uytterhoeven 		ctlr = acpi_spi_find_controller_by_adev(adev->parent);
42128caab75fSGeert Uytterhoeven 		if (!ctlr)
42137f24467fSOctavian Purdila 			break;
42147f24467fSOctavian Purdila 
42158caab75fSGeert Uytterhoeven 		acpi_register_spi_device(ctlr, adev);
42168caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
42177f24467fSOctavian Purdila 		break;
42187f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_REMOVE:
42197f24467fSOctavian Purdila 		if (!acpi_device_enumerated(adev))
42207f24467fSOctavian Purdila 			break;
42217f24467fSOctavian Purdila 
42227f24467fSOctavian Purdila 		spi = acpi_spi_find_device_by_adev(adev);
42237f24467fSOctavian Purdila 		if (!spi)
42247f24467fSOctavian Purdila 			break;
42257f24467fSOctavian Purdila 
42267f24467fSOctavian Purdila 		spi_unregister_device(spi);
42277f24467fSOctavian Purdila 		put_device(&spi->dev);
42287f24467fSOctavian Purdila 		break;
42297f24467fSOctavian Purdila 	}
42307f24467fSOctavian Purdila 
42317f24467fSOctavian Purdila 	return NOTIFY_OK;
42327f24467fSOctavian Purdila }
42337f24467fSOctavian Purdila 
42347f24467fSOctavian Purdila static struct notifier_block spi_acpi_notifier = {
42357f24467fSOctavian Purdila 	.notifier_call = acpi_spi_notify,
42367f24467fSOctavian Purdila };
42377f24467fSOctavian Purdila #else
42387f24467fSOctavian Purdila extern struct notifier_block spi_acpi_notifier;
42397f24467fSOctavian Purdila #endif
42407f24467fSOctavian Purdila 
42418ae12a0dSDavid Brownell static int __init spi_init(void)
42428ae12a0dSDavid Brownell {
4243b885244eSDavid Brownell 	int	status;
42448ae12a0dSDavid Brownell 
4245e94b1766SChristoph Lameter 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4246b885244eSDavid Brownell 	if (!buf) {
4247b885244eSDavid Brownell 		status = -ENOMEM;
4248b885244eSDavid Brownell 		goto err0;
42498ae12a0dSDavid Brownell 	}
4250b885244eSDavid Brownell 
4251b885244eSDavid Brownell 	status = bus_register(&spi_bus_type);
4252b885244eSDavid Brownell 	if (status < 0)
4253b885244eSDavid Brownell 		goto err1;
4254b885244eSDavid Brownell 
4255b885244eSDavid Brownell 	status = class_register(&spi_master_class);
4256b885244eSDavid Brownell 	if (status < 0)
4257b885244eSDavid Brownell 		goto err2;
4258ce79d54aSPantelis Antoniou 
42596c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
42606c364062SGeert Uytterhoeven 		status = class_register(&spi_slave_class);
42616c364062SGeert Uytterhoeven 		if (status < 0)
42626c364062SGeert Uytterhoeven 			goto err3;
42636c364062SGeert Uytterhoeven 	}
42646c364062SGeert Uytterhoeven 
42655267720eSFabio Estevam 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4266ce79d54aSPantelis Antoniou 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
42677f24467fSOctavian Purdila 	if (IS_ENABLED(CONFIG_ACPI))
42687f24467fSOctavian Purdila 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4269ce79d54aSPantelis Antoniou 
4270b885244eSDavid Brownell 	return 0;
4271b885244eSDavid Brownell 
42726c364062SGeert Uytterhoeven err3:
42736c364062SGeert Uytterhoeven 	class_unregister(&spi_master_class);
4274b885244eSDavid Brownell err2:
4275b885244eSDavid Brownell 	bus_unregister(&spi_bus_type);
4276b885244eSDavid Brownell err1:
4277b885244eSDavid Brownell 	kfree(buf);
4278b885244eSDavid Brownell 	buf = NULL;
4279b885244eSDavid Brownell err0:
4280b885244eSDavid Brownell 	return status;
4281b885244eSDavid Brownell }
4282b885244eSDavid Brownell 
42838ae12a0dSDavid Brownell /* board_info is normally registered in arch_initcall(),
42848ae12a0dSDavid Brownell  * but even essential drivers wait till later
4285b885244eSDavid Brownell  *
4286b885244eSDavid Brownell  * REVISIT only boardinfo really needs static linking. the rest (device and
4287b885244eSDavid Brownell  * driver registration) _could_ be dynamically linked (modular) ... costs
4288b885244eSDavid Brownell  * include needing to have boardinfo data structures be much more public.
42898ae12a0dSDavid Brownell  */
4290673c0c00SDavid Brownell postcore_initcall(spi_init);
4291