xref: /linux/drivers/spi/spi.c (revision 862dd2a946aa1417f013fb748e2aa0f4349b405b)
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 
3778ae12a0dSDavid Brownell struct bus_type spi_bus_type = {
3788ae12a0dSDavid Brownell 	.name		= "spi",
379aa7da564SGreg Kroah-Hartman 	.dev_groups	= spi_dev_groups,
3808ae12a0dSDavid Brownell 	.match		= spi_match_device,
3818ae12a0dSDavid Brownell 	.uevent		= spi_uevent,
3828ae12a0dSDavid Brownell };
3838ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_bus_type);
3848ae12a0dSDavid Brownell 
385b885244eSDavid Brownell 
386b885244eSDavid Brownell static int spi_drv_probe(struct device *dev)
387b885244eSDavid Brownell {
388b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
38944af7927SJon Hunter 	struct spi_device		*spi = to_spi_device(dev);
39033cf00e5SMika Westerberg 	int ret;
391b885244eSDavid Brownell 
39286be408bSSylwester Nawrocki 	ret = of_clk_set_defaults(dev->of_node, false);
39386be408bSSylwester Nawrocki 	if (ret)
39486be408bSSylwester Nawrocki 		return ret;
39586be408bSSylwester Nawrocki 
39644af7927SJon Hunter 	if (dev->of_node) {
39744af7927SJon Hunter 		spi->irq = of_irq_get(dev->of_node, 0);
39844af7927SJon Hunter 		if (spi->irq == -EPROBE_DEFER)
39944af7927SJon Hunter 			return -EPROBE_DEFER;
40044af7927SJon Hunter 		if (spi->irq < 0)
40144af7927SJon Hunter 			spi->irq = 0;
40244af7927SJon Hunter 	}
40344af7927SJon Hunter 
404676e7c25SUlf Hansson 	ret = dev_pm_domain_attach(dev, true);
40571f277a7SUlf Hansson 	if (ret)
40671f277a7SUlf Hansson 		return ret;
40771f277a7SUlf Hansson 
40844af7927SJon Hunter 	ret = sdrv->probe(spi);
40933cf00e5SMika Westerberg 	if (ret)
410676e7c25SUlf Hansson 		dev_pm_domain_detach(dev, true);
41133cf00e5SMika Westerberg 
41233cf00e5SMika Westerberg 	return ret;
413b885244eSDavid Brownell }
414b885244eSDavid Brownell 
415b885244eSDavid Brownell static int spi_drv_remove(struct device *dev)
416b885244eSDavid Brownell {
417b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
41833cf00e5SMika Westerberg 	int ret;
419b885244eSDavid Brownell 
420aec35f4eSJean Delvare 	ret = sdrv->remove(to_spi_device(dev));
421676e7c25SUlf Hansson 	dev_pm_domain_detach(dev, true);
42233cf00e5SMika Westerberg 
42333cf00e5SMika Westerberg 	return ret;
424b885244eSDavid Brownell }
425b885244eSDavid Brownell 
426b885244eSDavid Brownell static void spi_drv_shutdown(struct device *dev)
427b885244eSDavid Brownell {
428b885244eSDavid Brownell 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
429b885244eSDavid Brownell 
430b885244eSDavid Brownell 	sdrv->shutdown(to_spi_device(dev));
431b885244eSDavid Brownell }
432b885244eSDavid Brownell 
43333e34dc6SDavid Brownell /**
434ca5d2485SAndrew F. Davis  * __spi_register_driver - register a SPI driver
43588c9321dSThierry Reding  * @owner: owner module of the driver to register
43633e34dc6SDavid Brownell  * @sdrv: the driver to register
43733e34dc6SDavid Brownell  * Context: can sleep
43897d56dc6SJavier Martinez Canillas  *
43997d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
44033e34dc6SDavid Brownell  */
441ca5d2485SAndrew F. Davis int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
442b885244eSDavid Brownell {
443ca5d2485SAndrew F. Davis 	sdrv->driver.owner = owner;
444b885244eSDavid Brownell 	sdrv->driver.bus = &spi_bus_type;
445b885244eSDavid Brownell 	if (sdrv->probe)
446b885244eSDavid Brownell 		sdrv->driver.probe = spi_drv_probe;
447b885244eSDavid Brownell 	if (sdrv->remove)
448b885244eSDavid Brownell 		sdrv->driver.remove = spi_drv_remove;
449b885244eSDavid Brownell 	if (sdrv->shutdown)
450b885244eSDavid Brownell 		sdrv->driver.shutdown = spi_drv_shutdown;
451b885244eSDavid Brownell 	return driver_register(&sdrv->driver);
452b885244eSDavid Brownell }
453ca5d2485SAndrew F. Davis EXPORT_SYMBOL_GPL(__spi_register_driver);
454b885244eSDavid Brownell 
4558ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
4568ae12a0dSDavid Brownell 
4578ae12a0dSDavid Brownell /* SPI devices should normally not be created by SPI device drivers; that
4588caab75fSGeert Uytterhoeven  * would make them board-specific.  Similarly with SPI controller drivers.
4598ae12a0dSDavid Brownell  * Device registration normally goes into like arch/.../mach.../board-YYY.c
4608ae12a0dSDavid Brownell  * with other readonly (flashable) information about mainboard devices.
4618ae12a0dSDavid Brownell  */
4628ae12a0dSDavid Brownell 
4638ae12a0dSDavid Brownell struct boardinfo {
4648ae12a0dSDavid Brownell 	struct list_head	list;
4652b9603a0SFeng Tang 	struct spi_board_info	board_info;
4668ae12a0dSDavid Brownell };
4678ae12a0dSDavid Brownell 
4688ae12a0dSDavid Brownell static LIST_HEAD(board_list);
4698caab75fSGeert Uytterhoeven static LIST_HEAD(spi_controller_list);
4702b9603a0SFeng Tang 
4712b9603a0SFeng Tang /*
472be73e323SAndy Shevchenko  * Used to protect add/del operation for board_info list and
4738caab75fSGeert Uytterhoeven  * spi_controller list, and their matching process
4749b61e302SSuniel Mahesh  * also used to protect object of type struct idr
4752b9603a0SFeng Tang  */
47694040828SMatthias Kaehlcke static DEFINE_MUTEX(board_lock);
4778ae12a0dSDavid Brownell 
478dc87c98eSGrant Likely /**
479dc87c98eSGrant Likely  * spi_alloc_device - Allocate a new SPI device
4808caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
481dc87c98eSGrant Likely  * Context: can sleep
482dc87c98eSGrant Likely  *
483dc87c98eSGrant Likely  * Allows a driver to allocate and initialize a spi_device without
484dc87c98eSGrant Likely  * registering it immediately.  This allows a driver to directly
485dc87c98eSGrant Likely  * fill the spi_device with device parameters before calling
486dc87c98eSGrant Likely  * spi_add_device() on it.
487dc87c98eSGrant Likely  *
488dc87c98eSGrant Likely  * Caller is responsible to call spi_add_device() on the returned
4898caab75fSGeert Uytterhoeven  * spi_device structure to add it to the SPI controller.  If the caller
490dc87c98eSGrant Likely  * needs to discard the spi_device without adding it, then it should
491dc87c98eSGrant Likely  * call spi_dev_put() on it.
492dc87c98eSGrant Likely  *
49397d56dc6SJavier Martinez Canillas  * Return: a pointer to the new device, or NULL.
494dc87c98eSGrant Likely  */
4958caab75fSGeert Uytterhoeven struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
496dc87c98eSGrant Likely {
497dc87c98eSGrant Likely 	struct spi_device	*spi;
498dc87c98eSGrant Likely 
4998caab75fSGeert Uytterhoeven 	if (!spi_controller_get(ctlr))
500dc87c98eSGrant Likely 		return NULL;
501dc87c98eSGrant Likely 
5025fe5f05eSJingoo Han 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
503dc87c98eSGrant Likely 	if (!spi) {
5048caab75fSGeert Uytterhoeven 		spi_controller_put(ctlr);
505dc87c98eSGrant Likely 		return NULL;
506dc87c98eSGrant Likely 	}
507dc87c98eSGrant Likely 
5088caab75fSGeert Uytterhoeven 	spi->master = spi->controller = ctlr;
5098caab75fSGeert Uytterhoeven 	spi->dev.parent = &ctlr->dev;
510dc87c98eSGrant Likely 	spi->dev.bus = &spi_bus_type;
511dc87c98eSGrant Likely 	spi->dev.release = spidev_release;
512446411e1SAndreas Larsson 	spi->cs_gpio = -ENOENT;
513eca2ebc7SMartin Sperl 
514eca2ebc7SMartin Sperl 	spin_lock_init(&spi->statistics.lock);
515eca2ebc7SMartin Sperl 
516dc87c98eSGrant Likely 	device_initialize(&spi->dev);
517dc87c98eSGrant Likely 	return spi;
518dc87c98eSGrant Likely }
519dc87c98eSGrant Likely EXPORT_SYMBOL_GPL(spi_alloc_device);
520dc87c98eSGrant Likely 
521e13ac47bSJarkko Nikula static void spi_dev_set_name(struct spi_device *spi)
522e13ac47bSJarkko Nikula {
523e13ac47bSJarkko Nikula 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
524e13ac47bSJarkko Nikula 
525e13ac47bSJarkko Nikula 	if (adev) {
526e13ac47bSJarkko Nikula 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
527e13ac47bSJarkko Nikula 		return;
528e13ac47bSJarkko Nikula 	}
529e13ac47bSJarkko Nikula 
5308caab75fSGeert Uytterhoeven 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
531e13ac47bSJarkko Nikula 		     spi->chip_select);
532e13ac47bSJarkko Nikula }
533e13ac47bSJarkko Nikula 
534b6fb8d3aSMika Westerberg static int spi_dev_check(struct device *dev, void *data)
535b6fb8d3aSMika Westerberg {
536b6fb8d3aSMika Westerberg 	struct spi_device *spi = to_spi_device(dev);
537b6fb8d3aSMika Westerberg 	struct spi_device *new_spi = data;
538b6fb8d3aSMika Westerberg 
5398caab75fSGeert Uytterhoeven 	if (spi->controller == new_spi->controller &&
540b6fb8d3aSMika Westerberg 	    spi->chip_select == new_spi->chip_select)
541b6fb8d3aSMika Westerberg 		return -EBUSY;
542b6fb8d3aSMika Westerberg 	return 0;
543b6fb8d3aSMika Westerberg }
544b6fb8d3aSMika Westerberg 
545dc87c98eSGrant Likely /**
546dc87c98eSGrant Likely  * spi_add_device - Add spi_device allocated with spi_alloc_device
547dc87c98eSGrant Likely  * @spi: spi_device to register
548dc87c98eSGrant Likely  *
549dc87c98eSGrant Likely  * Companion function to spi_alloc_device.  Devices allocated with
550dc87c98eSGrant Likely  * spi_alloc_device can be added onto the spi bus with this function.
551dc87c98eSGrant Likely  *
55297d56dc6SJavier Martinez Canillas  * Return: 0 on success; negative errno on failure
553dc87c98eSGrant Likely  */
554dc87c98eSGrant Likely int spi_add_device(struct spi_device *spi)
555dc87c98eSGrant Likely {
556e48880e0SDavid Brownell 	static DEFINE_MUTEX(spi_add_lock);
5578caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
5588caab75fSGeert Uytterhoeven 	struct device *dev = ctlr->dev.parent;
559dc87c98eSGrant Likely 	int status;
560dc87c98eSGrant Likely 
561dc87c98eSGrant Likely 	/* Chipselects are numbered 0..max; validate. */
5628caab75fSGeert Uytterhoeven 	if (spi->chip_select >= ctlr->num_chipselect) {
5638caab75fSGeert Uytterhoeven 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
5648caab75fSGeert Uytterhoeven 			ctlr->num_chipselect);
565dc87c98eSGrant Likely 		return -EINVAL;
566dc87c98eSGrant Likely 	}
567dc87c98eSGrant Likely 
568dc87c98eSGrant Likely 	/* Set the bus ID string */
569e13ac47bSJarkko Nikula 	spi_dev_set_name(spi);
570e48880e0SDavid Brownell 
571e48880e0SDavid Brownell 	/* We need to make sure there's no other device with this
572e48880e0SDavid Brownell 	 * chipselect **BEFORE** we call setup(), else we'll trash
573e48880e0SDavid Brownell 	 * its configuration.  Lock against concurrent add() calls.
574e48880e0SDavid Brownell 	 */
575e48880e0SDavid Brownell 	mutex_lock(&spi_add_lock);
576e48880e0SDavid Brownell 
577b6fb8d3aSMika Westerberg 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
578b6fb8d3aSMika Westerberg 	if (status) {
579e48880e0SDavid Brownell 		dev_err(dev, "chipselect %d already in use\n",
580e48880e0SDavid Brownell 				spi->chip_select);
581e48880e0SDavid Brownell 		goto done;
582e48880e0SDavid Brownell 	}
583e48880e0SDavid Brownell 
584f3186dd8SLinus Walleij 	/* Descriptors take precedence */
585f3186dd8SLinus Walleij 	if (ctlr->cs_gpiods)
586f3186dd8SLinus Walleij 		spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
587f3186dd8SLinus Walleij 	else if (ctlr->cs_gpios)
5888caab75fSGeert Uytterhoeven 		spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
58974317984SJean-Christophe PLAGNIOL-VILLARD 
590e48880e0SDavid Brownell 	/* Drivers may modify this initial i/o setup, but will
591e48880e0SDavid Brownell 	 * normally rely on the device being setup.  Devices
592e48880e0SDavid Brownell 	 * using SPI_CS_HIGH can't coexist well otherwise...
593e48880e0SDavid Brownell 	 */
5947d077197SDavid Brownell 	status = spi_setup(spi);
595dc87c98eSGrant Likely 	if (status < 0) {
596eb288a1fSLinus Walleij 		dev_err(dev, "can't setup %s, status %d\n",
597eb288a1fSLinus Walleij 				dev_name(&spi->dev), status);
598e48880e0SDavid Brownell 		goto done;
599dc87c98eSGrant Likely 	}
600dc87c98eSGrant Likely 
601e48880e0SDavid Brownell 	/* Device may be bound to an active driver when this returns */
602dc87c98eSGrant Likely 	status = device_add(&spi->dev);
603e48880e0SDavid Brownell 	if (status < 0)
604eb288a1fSLinus Walleij 		dev_err(dev, "can't add %s, status %d\n",
605eb288a1fSLinus Walleij 				dev_name(&spi->dev), status);
606e48880e0SDavid Brownell 	else
60735f74fcaSKay Sievers 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
608e48880e0SDavid Brownell 
609e48880e0SDavid Brownell done:
610e48880e0SDavid Brownell 	mutex_unlock(&spi_add_lock);
611e48880e0SDavid Brownell 	return status;
612dc87c98eSGrant Likely }
613dc87c98eSGrant Likely EXPORT_SYMBOL_GPL(spi_add_device);
6148ae12a0dSDavid Brownell 
61533e34dc6SDavid Brownell /**
61633e34dc6SDavid Brownell  * spi_new_device - instantiate one new SPI device
6178caab75fSGeert Uytterhoeven  * @ctlr: Controller to which device is connected
61833e34dc6SDavid Brownell  * @chip: Describes the SPI device
61933e34dc6SDavid Brownell  * Context: can sleep
62033e34dc6SDavid Brownell  *
62133e34dc6SDavid Brownell  * On typical mainboards, this is purely internal; and it's not needed
6228ae12a0dSDavid Brownell  * after board init creates the hard-wired devices.  Some development
6238ae12a0dSDavid Brownell  * platforms may not be able to use spi_register_board_info though, and
6248ae12a0dSDavid Brownell  * this is exported so that for example a USB or parport based adapter
6258ae12a0dSDavid Brownell  * driver could add devices (which it would learn about out-of-band).
626082c8cb4SDavid Brownell  *
62797d56dc6SJavier Martinez Canillas  * Return: the new device, or NULL.
6288ae12a0dSDavid Brownell  */
6298caab75fSGeert Uytterhoeven struct spi_device *spi_new_device(struct spi_controller *ctlr,
630e9d5a461SAdrian Bunk 				  struct spi_board_info *chip)
6318ae12a0dSDavid Brownell {
6328ae12a0dSDavid Brownell 	struct spi_device	*proxy;
6338ae12a0dSDavid Brownell 	int			status;
6348ae12a0dSDavid Brownell 
635082c8cb4SDavid Brownell 	/* NOTE:  caller did any chip->bus_num checks necessary.
636082c8cb4SDavid Brownell 	 *
637082c8cb4SDavid Brownell 	 * Also, unless we change the return value convention to use
638082c8cb4SDavid Brownell 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
639082c8cb4SDavid Brownell 	 * suggests syslogged diagnostics are best here (ugh).
640082c8cb4SDavid Brownell 	 */
641082c8cb4SDavid Brownell 
6428caab75fSGeert Uytterhoeven 	proxy = spi_alloc_device(ctlr);
643dc87c98eSGrant Likely 	if (!proxy)
6448ae12a0dSDavid Brownell 		return NULL;
6458ae12a0dSDavid Brownell 
646102eb975SGrant Likely 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
647102eb975SGrant Likely 
6488ae12a0dSDavid Brownell 	proxy->chip_select = chip->chip_select;
6498ae12a0dSDavid Brownell 	proxy->max_speed_hz = chip->max_speed_hz;
650980a01c9SDavid Brownell 	proxy->mode = chip->mode;
6518ae12a0dSDavid Brownell 	proxy->irq = chip->irq;
652102eb975SGrant Likely 	strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
6538ae12a0dSDavid Brownell 	proxy->dev.platform_data = (void *) chip->platform_data;
6548ae12a0dSDavid Brownell 	proxy->controller_data = chip->controller_data;
6558ae12a0dSDavid Brownell 	proxy->controller_state = NULL;
6568ae12a0dSDavid Brownell 
657826cf175SDmitry Torokhov 	if (chip->properties) {
658826cf175SDmitry Torokhov 		status = device_add_properties(&proxy->dev, chip->properties);
659826cf175SDmitry Torokhov 		if (status) {
6608caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev,
661826cf175SDmitry Torokhov 				"failed to add properties to '%s': %d\n",
662826cf175SDmitry Torokhov 				chip->modalias, status);
663826cf175SDmitry Torokhov 			goto err_dev_put;
664826cf175SDmitry Torokhov 		}
6658ae12a0dSDavid Brownell 	}
666dc87c98eSGrant Likely 
667826cf175SDmitry Torokhov 	status = spi_add_device(proxy);
668826cf175SDmitry Torokhov 	if (status < 0)
669826cf175SDmitry Torokhov 		goto err_remove_props;
670826cf175SDmitry Torokhov 
671dc87c98eSGrant Likely 	return proxy;
672826cf175SDmitry Torokhov 
673826cf175SDmitry Torokhov err_remove_props:
674826cf175SDmitry Torokhov 	if (chip->properties)
675826cf175SDmitry Torokhov 		device_remove_properties(&proxy->dev);
676826cf175SDmitry Torokhov err_dev_put:
677826cf175SDmitry Torokhov 	spi_dev_put(proxy);
678826cf175SDmitry Torokhov 	return NULL;
679dc87c98eSGrant Likely }
6808ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_new_device);
6818ae12a0dSDavid Brownell 
6823b1884c2SGeert Uytterhoeven /**
6833b1884c2SGeert Uytterhoeven  * spi_unregister_device - unregister a single SPI device
6843b1884c2SGeert Uytterhoeven  * @spi: spi_device to unregister
6853b1884c2SGeert Uytterhoeven  *
6863b1884c2SGeert Uytterhoeven  * Start making the passed SPI device vanish. Normally this would be handled
6878caab75fSGeert Uytterhoeven  * by spi_unregister_controller().
6883b1884c2SGeert Uytterhoeven  */
6893b1884c2SGeert Uytterhoeven void spi_unregister_device(struct spi_device *spi)
6903b1884c2SGeert Uytterhoeven {
691bd6c1644SGeert Uytterhoeven 	if (!spi)
692bd6c1644SGeert Uytterhoeven 		return;
693bd6c1644SGeert Uytterhoeven 
6948324147fSJohan Hovold 	if (spi->dev.of_node) {
695bd6c1644SGeert Uytterhoeven 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
6968324147fSJohan Hovold 		of_node_put(spi->dev.of_node);
6978324147fSJohan Hovold 	}
6987f24467fSOctavian Purdila 	if (ACPI_COMPANION(&spi->dev))
6997f24467fSOctavian Purdila 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
7003b1884c2SGeert Uytterhoeven 	device_unregister(&spi->dev);
7013b1884c2SGeert Uytterhoeven }
7023b1884c2SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_device);
7033b1884c2SGeert Uytterhoeven 
7048caab75fSGeert Uytterhoeven static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
7052b9603a0SFeng Tang 					      struct spi_board_info *bi)
7062b9603a0SFeng Tang {
7072b9603a0SFeng Tang 	struct spi_device *dev;
7082b9603a0SFeng Tang 
7098caab75fSGeert Uytterhoeven 	if (ctlr->bus_num != bi->bus_num)
7102b9603a0SFeng Tang 		return;
7112b9603a0SFeng Tang 
7128caab75fSGeert Uytterhoeven 	dev = spi_new_device(ctlr, bi);
7132b9603a0SFeng Tang 	if (!dev)
7148caab75fSGeert Uytterhoeven 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
7152b9603a0SFeng Tang 			bi->modalias);
7162b9603a0SFeng Tang }
7172b9603a0SFeng Tang 
71833e34dc6SDavid Brownell /**
71933e34dc6SDavid Brownell  * spi_register_board_info - register SPI devices for a given board
72033e34dc6SDavid Brownell  * @info: array of chip descriptors
72133e34dc6SDavid Brownell  * @n: how many descriptors are provided
72233e34dc6SDavid Brownell  * Context: can sleep
72333e34dc6SDavid Brownell  *
7248ae12a0dSDavid Brownell  * Board-specific early init code calls this (probably during arch_initcall)
7258ae12a0dSDavid Brownell  * with segments of the SPI device table.  Any device nodes are created later,
7268ae12a0dSDavid Brownell  * after the relevant parent SPI controller (bus_num) is defined.  We keep
7278ae12a0dSDavid Brownell  * this table of devices forever, so that reloading a controller driver will
7288ae12a0dSDavid Brownell  * not make Linux forget about these hard-wired devices.
7298ae12a0dSDavid Brownell  *
7308ae12a0dSDavid Brownell  * Other code can also call this, e.g. a particular add-on board might provide
7318ae12a0dSDavid Brownell  * SPI devices through its expansion connector, so code initializing that board
7328ae12a0dSDavid Brownell  * would naturally declare its SPI devices.
7338ae12a0dSDavid Brownell  *
7348ae12a0dSDavid Brownell  * The board info passed can safely be __initdata ... but be careful of
7358ae12a0dSDavid Brownell  * any embedded pointers (platform_data, etc), they're copied as-is.
736826cf175SDmitry Torokhov  * Device properties are deep-copied though.
73797d56dc6SJavier Martinez Canillas  *
73897d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
7398ae12a0dSDavid Brownell  */
740fd4a319bSGrant Likely int spi_register_board_info(struct spi_board_info const *info, unsigned n)
7418ae12a0dSDavid Brownell {
7428ae12a0dSDavid Brownell 	struct boardinfo *bi;
7432b9603a0SFeng Tang 	int i;
7448ae12a0dSDavid Brownell 
745c7908a37SXiubo Li 	if (!n)
746f974cf57SDmitry Torokhov 		return 0;
747c7908a37SXiubo Li 
748f9bdb7fdSMarkus Elfring 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
7498ae12a0dSDavid Brownell 	if (!bi)
7508ae12a0dSDavid Brownell 		return -ENOMEM;
7518ae12a0dSDavid Brownell 
7522b9603a0SFeng Tang 	for (i = 0; i < n; i++, bi++, info++) {
7538caab75fSGeert Uytterhoeven 		struct spi_controller *ctlr;
7542b9603a0SFeng Tang 
7552b9603a0SFeng Tang 		memcpy(&bi->board_info, info, sizeof(*info));
756826cf175SDmitry Torokhov 		if (info->properties) {
757826cf175SDmitry Torokhov 			bi->board_info.properties =
758826cf175SDmitry Torokhov 					property_entries_dup(info->properties);
759826cf175SDmitry Torokhov 			if (IS_ERR(bi->board_info.properties))
760826cf175SDmitry Torokhov 				return PTR_ERR(bi->board_info.properties);
761826cf175SDmitry Torokhov 		}
762826cf175SDmitry Torokhov 
76394040828SMatthias Kaehlcke 		mutex_lock(&board_lock);
7648ae12a0dSDavid Brownell 		list_add_tail(&bi->list, &board_list);
7658caab75fSGeert Uytterhoeven 		list_for_each_entry(ctlr, &spi_controller_list, list)
7668caab75fSGeert Uytterhoeven 			spi_match_controller_to_boardinfo(ctlr,
7678caab75fSGeert Uytterhoeven 							  &bi->board_info);
76894040828SMatthias Kaehlcke 		mutex_unlock(&board_lock);
7692b9603a0SFeng Tang 	}
7702b9603a0SFeng Tang 
7718ae12a0dSDavid Brownell 	return 0;
7728ae12a0dSDavid Brownell }
7738ae12a0dSDavid Brownell 
7748ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
7758ae12a0dSDavid Brownell 
776b158935fSMark Brown static void spi_set_cs(struct spi_device *spi, bool enable)
777b158935fSMark Brown {
77825093bdeSAlexandru Ardelean 	bool enable1 = enable;
77925093bdeSAlexandru Ardelean 
78025093bdeSAlexandru Ardelean 	if (!spi->controller->set_cs_timing) {
78125093bdeSAlexandru Ardelean 		if (enable1)
78225093bdeSAlexandru Ardelean 			spi_delay_exec(&spi->controller->cs_setup, NULL);
78325093bdeSAlexandru Ardelean 		else
78425093bdeSAlexandru Ardelean 			spi_delay_exec(&spi->controller->cs_hold, NULL);
78525093bdeSAlexandru Ardelean 	}
78625093bdeSAlexandru Ardelean 
787b158935fSMark Brown 	if (spi->mode & SPI_CS_HIGH)
788b158935fSMark Brown 		enable = !enable;
789b158935fSMark Brown 
790f3186dd8SLinus Walleij 	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
791f3186dd8SLinus Walleij 		/*
792f3186dd8SLinus Walleij 		 * Honour the SPI_NO_CS flag and invert the enable line, as
793f3186dd8SLinus Walleij 		 * active low is default for SPI. Execution paths that handle
794f3186dd8SLinus Walleij 		 * polarity inversion in gpiolib (such as device tree) will
795f3186dd8SLinus Walleij 		 * enforce active high using the SPI_CS_HIGH resulting in a
796f3186dd8SLinus Walleij 		 * double inversion through the code above.
797f3186dd8SLinus Walleij 		 */
798f3186dd8SLinus Walleij 		if (!(spi->mode & SPI_NO_CS)) {
799f3186dd8SLinus Walleij 			if (spi->cs_gpiod)
80028f7604fSFelix Fietkau 				gpiod_set_value_cansleep(spi->cs_gpiod,
80128f7604fSFelix Fietkau 							 !enable);
802f3186dd8SLinus Walleij 			else
80328f7604fSFelix Fietkau 				gpio_set_value_cansleep(spi->cs_gpio, !enable);
804f3186dd8SLinus Walleij 		}
8058eee6b9dSThor Thayer 		/* Some SPI masters need both GPIO CS & slave_select */
8068caab75fSGeert Uytterhoeven 		if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
8078caab75fSGeert Uytterhoeven 		    spi->controller->set_cs)
8088caab75fSGeert Uytterhoeven 			spi->controller->set_cs(spi, !enable);
8098caab75fSGeert Uytterhoeven 	} else if (spi->controller->set_cs) {
8108caab75fSGeert Uytterhoeven 		spi->controller->set_cs(spi, !enable);
8118eee6b9dSThor Thayer 	}
81225093bdeSAlexandru Ardelean 
81325093bdeSAlexandru Ardelean 	if (!spi->controller->set_cs_timing) {
81425093bdeSAlexandru Ardelean 		if (!enable1)
81525093bdeSAlexandru Ardelean 			spi_delay_exec(&spi->controller->cs_inactive, NULL);
81625093bdeSAlexandru Ardelean 	}
817b158935fSMark Brown }
818b158935fSMark Brown 
8192de440f5SGeert Uytterhoeven #ifdef CONFIG_HAS_DMA
82046336966SBoris Brezillon int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
8216ad45a27SMark Brown 		struct sg_table *sgt, void *buf, size_t len,
8226ad45a27SMark Brown 		enum dma_data_direction dir)
8236ad45a27SMark Brown {
8246ad45a27SMark Brown 	const bool vmalloced_buf = is_vmalloc_addr(buf);
825df88e91bSAndy Shevchenko 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
826b1b8153cSVignesh R #ifdef CONFIG_HIGHMEM
827b1b8153cSVignesh R 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
828b1b8153cSVignesh R 				(unsigned long)buf < (PKMAP_BASE +
829b1b8153cSVignesh R 					(LAST_PKMAP * PAGE_SIZE)));
830b1b8153cSVignesh R #else
831b1b8153cSVignesh R 	const bool kmap_buf = false;
832b1b8153cSVignesh R #endif
83365598c13SAndrew Gabbasov 	int desc_len;
83465598c13SAndrew Gabbasov 	int sgs;
8356ad45a27SMark Brown 	struct page *vm_page;
8368dd4a016SJuan Gutierrez 	struct scatterlist *sg;
8376ad45a27SMark Brown 	void *sg_buf;
8386ad45a27SMark Brown 	size_t min;
8396ad45a27SMark Brown 	int i, ret;
8406ad45a27SMark Brown 
841b1b8153cSVignesh R 	if (vmalloced_buf || kmap_buf) {
842df88e91bSAndy Shevchenko 		desc_len = min_t(int, max_seg_size, PAGE_SIZE);
84365598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
8440569a88fSVignesh R 	} else if (virt_addr_valid(buf)) {
8458caab75fSGeert Uytterhoeven 		desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
84665598c13SAndrew Gabbasov 		sgs = DIV_ROUND_UP(len, desc_len);
8470569a88fSVignesh R 	} else {
8480569a88fSVignesh R 		return -EINVAL;
84965598c13SAndrew Gabbasov 	}
85065598c13SAndrew Gabbasov 
8516ad45a27SMark Brown 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
8526ad45a27SMark Brown 	if (ret != 0)
8536ad45a27SMark Brown 		return ret;
8546ad45a27SMark Brown 
8558dd4a016SJuan Gutierrez 	sg = &sgt->sgl[0];
8566ad45a27SMark Brown 	for (i = 0; i < sgs; i++) {
8576ad45a27SMark Brown 
858b1b8153cSVignesh R 		if (vmalloced_buf || kmap_buf) {
859ce99319aSMaxime Chevallier 			/*
860ce99319aSMaxime Chevallier 			 * Next scatterlist entry size is the minimum between
861ce99319aSMaxime Chevallier 			 * the desc_len and the remaining buffer length that
862ce99319aSMaxime Chevallier 			 * fits in a page.
863ce99319aSMaxime Chevallier 			 */
864ce99319aSMaxime Chevallier 			min = min_t(size_t, desc_len,
865ce99319aSMaxime Chevallier 				    min_t(size_t, len,
866ce99319aSMaxime Chevallier 					  PAGE_SIZE - offset_in_page(buf)));
867b1b8153cSVignesh R 			if (vmalloced_buf)
8686ad45a27SMark Brown 				vm_page = vmalloc_to_page(buf);
869b1b8153cSVignesh R 			else
870b1b8153cSVignesh R 				vm_page = kmap_to_page(buf);
8716ad45a27SMark Brown 			if (!vm_page) {
8726ad45a27SMark Brown 				sg_free_table(sgt);
8736ad45a27SMark Brown 				return -ENOMEM;
8746ad45a27SMark Brown 			}
8758dd4a016SJuan Gutierrez 			sg_set_page(sg, vm_page,
876c1aefbddSCharles Keepax 				    min, offset_in_page(buf));
8776ad45a27SMark Brown 		} else {
87865598c13SAndrew Gabbasov 			min = min_t(size_t, len, desc_len);
8796ad45a27SMark Brown 			sg_buf = buf;
8808dd4a016SJuan Gutierrez 			sg_set_buf(sg, sg_buf, min);
8816ad45a27SMark Brown 		}
8826ad45a27SMark Brown 
8836ad45a27SMark Brown 		buf += min;
8846ad45a27SMark Brown 		len -= min;
8858dd4a016SJuan Gutierrez 		sg = sg_next(sg);
8866ad45a27SMark Brown 	}
8876ad45a27SMark Brown 
8886ad45a27SMark Brown 	ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
88989e4b66aSGeert Uytterhoeven 	if (!ret)
89089e4b66aSGeert Uytterhoeven 		ret = -ENOMEM;
8916ad45a27SMark Brown 	if (ret < 0) {
8926ad45a27SMark Brown 		sg_free_table(sgt);
8936ad45a27SMark Brown 		return ret;
8946ad45a27SMark Brown 	}
8956ad45a27SMark Brown 
8966ad45a27SMark Brown 	sgt->nents = ret;
8976ad45a27SMark Brown 
8986ad45a27SMark Brown 	return 0;
8996ad45a27SMark Brown }
9006ad45a27SMark Brown 
90146336966SBoris Brezillon void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
9026ad45a27SMark Brown 		   struct sg_table *sgt, enum dma_data_direction dir)
9036ad45a27SMark Brown {
9046ad45a27SMark Brown 	if (sgt->orig_nents) {
9056ad45a27SMark Brown 		dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
9066ad45a27SMark Brown 		sg_free_table(sgt);
9076ad45a27SMark Brown 	}
9086ad45a27SMark Brown }
9096ad45a27SMark Brown 
9108caab75fSGeert Uytterhoeven static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
91199adef31SMark Brown {
91299adef31SMark Brown 	struct device *tx_dev, *rx_dev;
91399adef31SMark Brown 	struct spi_transfer *xfer;
9146ad45a27SMark Brown 	int ret;
9153a2eba9bSMark Brown 
9168caab75fSGeert Uytterhoeven 	if (!ctlr->can_dma)
91799adef31SMark Brown 		return 0;
91899adef31SMark Brown 
9198caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
9208caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
921c37f45b5SLeilk Liu 	else
9228caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
923c37f45b5SLeilk Liu 
9248caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
9258caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
926c37f45b5SLeilk Liu 	else
9278caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
92899adef31SMark Brown 
92999adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
9308caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
93199adef31SMark Brown 			continue;
93299adef31SMark Brown 
93399adef31SMark Brown 		if (xfer->tx_buf != NULL) {
9348caab75fSGeert Uytterhoeven 			ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
9356ad45a27SMark Brown 					  (void *)xfer->tx_buf, xfer->len,
93699adef31SMark Brown 					  DMA_TO_DEVICE);
9376ad45a27SMark Brown 			if (ret != 0)
9386ad45a27SMark Brown 				return ret;
93999adef31SMark Brown 		}
94099adef31SMark Brown 
94199adef31SMark Brown 		if (xfer->rx_buf != NULL) {
9428caab75fSGeert Uytterhoeven 			ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
94399adef31SMark Brown 					  xfer->rx_buf, xfer->len,
94499adef31SMark Brown 					  DMA_FROM_DEVICE);
9456ad45a27SMark Brown 			if (ret != 0) {
9468caab75fSGeert Uytterhoeven 				spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
9476ad45a27SMark Brown 					      DMA_TO_DEVICE);
9486ad45a27SMark Brown 				return ret;
94999adef31SMark Brown 			}
95099adef31SMark Brown 		}
95199adef31SMark Brown 	}
95299adef31SMark Brown 
9538caab75fSGeert Uytterhoeven 	ctlr->cur_msg_mapped = true;
95499adef31SMark Brown 
95599adef31SMark Brown 	return 0;
95699adef31SMark Brown }
95799adef31SMark Brown 
9588caab75fSGeert Uytterhoeven static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
95999adef31SMark Brown {
96099adef31SMark Brown 	struct spi_transfer *xfer;
96199adef31SMark Brown 	struct device *tx_dev, *rx_dev;
96299adef31SMark Brown 
9638caab75fSGeert Uytterhoeven 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
96499adef31SMark Brown 		return 0;
96599adef31SMark Brown 
9668caab75fSGeert Uytterhoeven 	if (ctlr->dma_tx)
9678caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dma_tx->device->dev;
968c37f45b5SLeilk Liu 	else
9698caab75fSGeert Uytterhoeven 		tx_dev = ctlr->dev.parent;
970c37f45b5SLeilk Liu 
9718caab75fSGeert Uytterhoeven 	if (ctlr->dma_rx)
9728caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dma_rx->device->dev;
973c37f45b5SLeilk Liu 	else
9748caab75fSGeert Uytterhoeven 		rx_dev = ctlr->dev.parent;
97599adef31SMark Brown 
97699adef31SMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
9778caab75fSGeert Uytterhoeven 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
97899adef31SMark Brown 			continue;
97999adef31SMark Brown 
9808caab75fSGeert Uytterhoeven 		spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
9818caab75fSGeert Uytterhoeven 		spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
98299adef31SMark Brown 	}
98399adef31SMark Brown 
98499adef31SMark Brown 	return 0;
98599adef31SMark Brown }
9862de440f5SGeert Uytterhoeven #else /* !CONFIG_HAS_DMA */
9878caab75fSGeert Uytterhoeven static inline int __spi_map_msg(struct spi_controller *ctlr,
9882de440f5SGeert Uytterhoeven 				struct spi_message *msg)
9892de440f5SGeert Uytterhoeven {
9902de440f5SGeert Uytterhoeven 	return 0;
9912de440f5SGeert Uytterhoeven }
9922de440f5SGeert Uytterhoeven 
9938caab75fSGeert Uytterhoeven static inline int __spi_unmap_msg(struct spi_controller *ctlr,
9942de440f5SGeert Uytterhoeven 				  struct spi_message *msg)
9952de440f5SGeert Uytterhoeven {
9962de440f5SGeert Uytterhoeven 	return 0;
9972de440f5SGeert Uytterhoeven }
9982de440f5SGeert Uytterhoeven #endif /* !CONFIG_HAS_DMA */
9992de440f5SGeert Uytterhoeven 
10008caab75fSGeert Uytterhoeven static inline int spi_unmap_msg(struct spi_controller *ctlr,
10014b786458SMartin Sperl 				struct spi_message *msg)
10024b786458SMartin Sperl {
10034b786458SMartin Sperl 	struct spi_transfer *xfer;
10044b786458SMartin Sperl 
10054b786458SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
10064b786458SMartin Sperl 		/*
10074b786458SMartin Sperl 		 * Restore the original value of tx_buf or rx_buf if they are
10084b786458SMartin Sperl 		 * NULL.
10094b786458SMartin Sperl 		 */
10108caab75fSGeert Uytterhoeven 		if (xfer->tx_buf == ctlr->dummy_tx)
10114b786458SMartin Sperl 			xfer->tx_buf = NULL;
10128caab75fSGeert Uytterhoeven 		if (xfer->rx_buf == ctlr->dummy_rx)
10134b786458SMartin Sperl 			xfer->rx_buf = NULL;
10144b786458SMartin Sperl 	}
10154b786458SMartin Sperl 
10168caab75fSGeert Uytterhoeven 	return __spi_unmap_msg(ctlr, msg);
10174b786458SMartin Sperl }
10184b786458SMartin Sperl 
10198caab75fSGeert Uytterhoeven static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
10202de440f5SGeert Uytterhoeven {
10212de440f5SGeert Uytterhoeven 	struct spi_transfer *xfer;
10222de440f5SGeert Uytterhoeven 	void *tmp;
10232de440f5SGeert Uytterhoeven 	unsigned int max_tx, max_rx;
10242de440f5SGeert Uytterhoeven 
10258caab75fSGeert Uytterhoeven 	if (ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX)) {
10262de440f5SGeert Uytterhoeven 		max_tx = 0;
10272de440f5SGeert Uytterhoeven 		max_rx = 0;
10282de440f5SGeert Uytterhoeven 
10292de440f5SGeert Uytterhoeven 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
10308caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
10312de440f5SGeert Uytterhoeven 			    !xfer->tx_buf)
10322de440f5SGeert Uytterhoeven 				max_tx = max(xfer->len, max_tx);
10338caab75fSGeert Uytterhoeven 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
10342de440f5SGeert Uytterhoeven 			    !xfer->rx_buf)
10352de440f5SGeert Uytterhoeven 				max_rx = max(xfer->len, max_rx);
10362de440f5SGeert Uytterhoeven 		}
10372de440f5SGeert Uytterhoeven 
10382de440f5SGeert Uytterhoeven 		if (max_tx) {
10398caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_tx, max_tx,
10402de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
10412de440f5SGeert Uytterhoeven 			if (!tmp)
10422de440f5SGeert Uytterhoeven 				return -ENOMEM;
10438caab75fSGeert Uytterhoeven 			ctlr->dummy_tx = tmp;
10442de440f5SGeert Uytterhoeven 			memset(tmp, 0, max_tx);
10452de440f5SGeert Uytterhoeven 		}
10462de440f5SGeert Uytterhoeven 
10472de440f5SGeert Uytterhoeven 		if (max_rx) {
10488caab75fSGeert Uytterhoeven 			tmp = krealloc(ctlr->dummy_rx, max_rx,
10492de440f5SGeert Uytterhoeven 				       GFP_KERNEL | GFP_DMA);
10502de440f5SGeert Uytterhoeven 			if (!tmp)
10512de440f5SGeert Uytterhoeven 				return -ENOMEM;
10528caab75fSGeert Uytterhoeven 			ctlr->dummy_rx = tmp;
10532de440f5SGeert Uytterhoeven 		}
10542de440f5SGeert Uytterhoeven 
10552de440f5SGeert Uytterhoeven 		if (max_tx || max_rx) {
10562de440f5SGeert Uytterhoeven 			list_for_each_entry(xfer, &msg->transfers,
10572de440f5SGeert Uytterhoeven 					    transfer_list) {
10585442dcaaSChris Lesiak 				if (!xfer->len)
10595442dcaaSChris Lesiak 					continue;
10602de440f5SGeert Uytterhoeven 				if (!xfer->tx_buf)
10618caab75fSGeert Uytterhoeven 					xfer->tx_buf = ctlr->dummy_tx;
10622de440f5SGeert Uytterhoeven 				if (!xfer->rx_buf)
10638caab75fSGeert Uytterhoeven 					xfer->rx_buf = ctlr->dummy_rx;
10642de440f5SGeert Uytterhoeven 			}
10652de440f5SGeert Uytterhoeven 		}
10662de440f5SGeert Uytterhoeven 	}
10672de440f5SGeert Uytterhoeven 
10688caab75fSGeert Uytterhoeven 	return __spi_map_msg(ctlr, msg);
10692de440f5SGeert Uytterhoeven }
107099adef31SMark Brown 
1071810923f3SLubomir Rintel static int spi_transfer_wait(struct spi_controller *ctlr,
1072810923f3SLubomir Rintel 			     struct spi_message *msg,
1073810923f3SLubomir Rintel 			     struct spi_transfer *xfer)
1074810923f3SLubomir Rintel {
1075810923f3SLubomir Rintel 	struct spi_statistics *statm = &ctlr->statistics;
1076810923f3SLubomir Rintel 	struct spi_statistics *stats = &msg->spi->statistics;
1077810923f3SLubomir Rintel 	unsigned long long ms = 1;
1078810923f3SLubomir Rintel 
1079810923f3SLubomir Rintel 	if (spi_controller_is_slave(ctlr)) {
1080810923f3SLubomir Rintel 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1081810923f3SLubomir Rintel 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1082810923f3SLubomir Rintel 			return -EINTR;
1083810923f3SLubomir Rintel 		}
1084810923f3SLubomir Rintel 	} else {
1085810923f3SLubomir Rintel 		ms = 8LL * 1000LL * xfer->len;
1086810923f3SLubomir Rintel 		do_div(ms, xfer->speed_hz);
1087810923f3SLubomir Rintel 		ms += ms + 200; /* some tolerance */
1088810923f3SLubomir Rintel 
1089810923f3SLubomir Rintel 		if (ms > UINT_MAX)
1090810923f3SLubomir Rintel 			ms = UINT_MAX;
1091810923f3SLubomir Rintel 
1092810923f3SLubomir Rintel 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1093810923f3SLubomir Rintel 						 msecs_to_jiffies(ms));
1094810923f3SLubomir Rintel 
1095810923f3SLubomir Rintel 		if (ms == 0) {
1096810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1097810923f3SLubomir Rintel 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1098810923f3SLubomir Rintel 			dev_err(&msg->spi->dev,
1099810923f3SLubomir Rintel 				"SPI transfer timed out\n");
1100810923f3SLubomir Rintel 			return -ETIMEDOUT;
1101810923f3SLubomir Rintel 		}
1102810923f3SLubomir Rintel 	}
1103810923f3SLubomir Rintel 
1104810923f3SLubomir Rintel 	return 0;
1105810923f3SLubomir Rintel }
1106810923f3SLubomir Rintel 
11070ff2de8bSMartin Sperl static void _spi_transfer_delay_ns(u32 ns)
11080ff2de8bSMartin Sperl {
11090ff2de8bSMartin Sperl 	if (!ns)
11100ff2de8bSMartin Sperl 		return;
11110ff2de8bSMartin Sperl 	if (ns <= 1000) {
11120ff2de8bSMartin Sperl 		ndelay(ns);
11130ff2de8bSMartin Sperl 	} else {
11140ff2de8bSMartin Sperl 		u32 us = DIV_ROUND_UP(ns, 1000);
11150ff2de8bSMartin Sperl 
11160ff2de8bSMartin Sperl 		if (us <= 10)
11170ff2de8bSMartin Sperl 			udelay(us);
11180ff2de8bSMartin Sperl 		else
11190ff2de8bSMartin Sperl 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
11200ff2de8bSMartin Sperl 	}
11210ff2de8bSMartin Sperl }
11220ff2de8bSMartin Sperl 
11233984d39bSAlexandru Ardelean int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1124b2c98153SAlexandru Ardelean {
1125b2c98153SAlexandru Ardelean 	u32 delay = _delay->value;
1126b2c98153SAlexandru Ardelean 	u32 unit = _delay->unit;
1127b2c98153SAlexandru Ardelean 	u32 hz;
1128b2c98153SAlexandru Ardelean 
1129b2c98153SAlexandru Ardelean 	if (!delay)
1130b2c98153SAlexandru Ardelean 		return 0;
1131b2c98153SAlexandru Ardelean 
1132b2c98153SAlexandru Ardelean 	switch (unit) {
1133b2c98153SAlexandru Ardelean 	case SPI_DELAY_UNIT_USECS:
1134b2c98153SAlexandru Ardelean 		delay *= 1000;
1135b2c98153SAlexandru Ardelean 		break;
1136b2c98153SAlexandru Ardelean 	case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1137b2c98153SAlexandru Ardelean 		break;
1138b2c98153SAlexandru Ardelean 	case SPI_DELAY_UNIT_SCK:
1139b2c98153SAlexandru Ardelean 		/* clock cycles need to be obtained from spi_transfer */
1140b2c98153SAlexandru Ardelean 		if (!xfer)
1141b2c98153SAlexandru Ardelean 			return -EINVAL;
1142b2c98153SAlexandru Ardelean 		/* if there is no effective speed know, then approximate
1143b2c98153SAlexandru Ardelean 		 * by underestimating with half the requested hz
1144b2c98153SAlexandru Ardelean 		 */
1145b2c98153SAlexandru Ardelean 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1146b2c98153SAlexandru Ardelean 		if (!hz)
1147b2c98153SAlexandru Ardelean 			return -EINVAL;
1148b2c98153SAlexandru Ardelean 		delay *= DIV_ROUND_UP(1000000000, hz);
1149b2c98153SAlexandru Ardelean 		break;
1150b2c98153SAlexandru Ardelean 	default:
1151b2c98153SAlexandru Ardelean 		return -EINVAL;
1152b2c98153SAlexandru Ardelean 	}
1153b2c98153SAlexandru Ardelean 
1154b2c98153SAlexandru Ardelean 	return delay;
1155b2c98153SAlexandru Ardelean }
11563984d39bSAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1157b2c98153SAlexandru Ardelean 
1158b2c98153SAlexandru Ardelean int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1159b2c98153SAlexandru Ardelean {
1160b2c98153SAlexandru Ardelean 	int delay;
1161b2c98153SAlexandru Ardelean 
1162b2c98153SAlexandru Ardelean 	if (!_delay)
1163b2c98153SAlexandru Ardelean 		return -EINVAL;
1164b2c98153SAlexandru Ardelean 
11653984d39bSAlexandru Ardelean 	delay = spi_delay_to_ns(_delay, xfer);
1166b2c98153SAlexandru Ardelean 	if (delay < 0)
1167b2c98153SAlexandru Ardelean 		return delay;
1168b2c98153SAlexandru Ardelean 
1169b2c98153SAlexandru Ardelean 	_spi_transfer_delay_ns(delay);
1170b2c98153SAlexandru Ardelean 
1171b2c98153SAlexandru Ardelean 	return 0;
1172b2c98153SAlexandru Ardelean }
1173b2c98153SAlexandru Ardelean EXPORT_SYMBOL_GPL(spi_delay_exec);
1174b2c98153SAlexandru Ardelean 
11750ff2de8bSMartin Sperl static void _spi_transfer_cs_change_delay(struct spi_message *msg,
11760ff2de8bSMartin Sperl 					  struct spi_transfer *xfer)
11770ff2de8bSMartin Sperl {
1178329f0dacSAlexandru Ardelean 	u32 delay = xfer->cs_change_delay.value;
1179329f0dacSAlexandru Ardelean 	u32 unit = xfer->cs_change_delay.unit;
1180329f0dacSAlexandru Ardelean 	int ret;
11810ff2de8bSMartin Sperl 
11820ff2de8bSMartin Sperl 	/* return early on "fast" mode - for everything but USECS */
11836b3f236aSAlexandru Ardelean 	if (!delay) {
11846b3f236aSAlexandru Ardelean 		if (unit == SPI_DELAY_UNIT_USECS)
11856b3f236aSAlexandru Ardelean 			_spi_transfer_delay_ns(10000);
11860ff2de8bSMartin Sperl 		return;
11876b3f236aSAlexandru Ardelean 	}
11880ff2de8bSMartin Sperl 
1189329f0dacSAlexandru Ardelean 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1190329f0dacSAlexandru Ardelean 	if (ret) {
11910ff2de8bSMartin Sperl 		dev_err_once(&msg->spi->dev,
11920ff2de8bSMartin Sperl 			     "Use of unsupported delay unit %i, using default of 10us\n",
1193329f0dacSAlexandru Ardelean 			     unit);
1194329f0dacSAlexandru Ardelean 		_spi_transfer_delay_ns(10000);
11950ff2de8bSMartin Sperl 	}
11960ff2de8bSMartin Sperl }
11970ff2de8bSMartin Sperl 
1198b158935fSMark Brown /*
1199b158935fSMark Brown  * spi_transfer_one_message - Default implementation of transfer_one_message()
1200b158935fSMark Brown  *
1201b158935fSMark Brown  * This is a standard implementation of transfer_one_message() for
12028ba811a7SMoritz Fischer  * drivers which implement a transfer_one() operation.  It provides
1203b158935fSMark Brown  * standard handling of delays and chip select management.
1204b158935fSMark Brown  */
12058caab75fSGeert Uytterhoeven static int spi_transfer_one_message(struct spi_controller *ctlr,
1206b158935fSMark Brown 				    struct spi_message *msg)
1207b158935fSMark Brown {
1208b158935fSMark Brown 	struct spi_transfer *xfer;
1209b158935fSMark Brown 	bool keep_cs = false;
1210b158935fSMark Brown 	int ret = 0;
12118caab75fSGeert Uytterhoeven 	struct spi_statistics *statm = &ctlr->statistics;
1212eca2ebc7SMartin Sperl 	struct spi_statistics *stats = &msg->spi->statistics;
1213b158935fSMark Brown 
1214b158935fSMark Brown 	spi_set_cs(msg->spi, true);
1215b158935fSMark Brown 
1216eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1217eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1218eca2ebc7SMartin Sperl 
1219b158935fSMark Brown 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1220b158935fSMark Brown 		trace_spi_transfer_start(msg, xfer);
1221b158935fSMark Brown 
12228caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
12238caab75fSGeert Uytterhoeven 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1224eca2ebc7SMartin Sperl 
1225b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1226b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1227b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1228b42faeeeSVladimir Oltean 		}
1229b42faeeeSVladimir Oltean 
123038ec10f6SMark Brown 		if (xfer->tx_buf || xfer->rx_buf) {
12318caab75fSGeert Uytterhoeven 			reinit_completion(&ctlr->xfer_completion);
1232b158935fSMark Brown 
12338caab75fSGeert Uytterhoeven 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1234b158935fSMark Brown 			if (ret < 0) {
1235eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1236eca2ebc7SMartin Sperl 							       errors);
1237eca2ebc7SMartin Sperl 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1238eca2ebc7SMartin Sperl 							       errors);
1239b158935fSMark Brown 				dev_err(&msg->spi->dev,
1240b158935fSMark Brown 					"SPI transfer failed: %d\n", ret);
1241b158935fSMark Brown 				goto out;
1242b158935fSMark Brown 			}
1243b158935fSMark Brown 
1244d57e7960SMark Brown 			if (ret > 0) {
1245810923f3SLubomir Rintel 				ret = spi_transfer_wait(ctlr, msg, xfer);
1246810923f3SLubomir Rintel 				if (ret < 0)
1247810923f3SLubomir Rintel 					msg->status = ret;
1248d57e7960SMark Brown 			}
124938ec10f6SMark Brown 		} else {
125038ec10f6SMark Brown 			if (xfer->len)
125138ec10f6SMark Brown 				dev_err(&msg->spi->dev,
125238ec10f6SMark Brown 					"Bufferless transfer has length %u\n",
125338ec10f6SMark Brown 					xfer->len);
125438ec10f6SMark Brown 		}
1255b158935fSMark Brown 
1256b42faeeeSVladimir Oltean 		if (!ctlr->ptp_sts_supported) {
1257b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1258b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1259b42faeeeSVladimir Oltean 		}
1260b42faeeeSVladimir Oltean 
1261b158935fSMark Brown 		trace_spi_transfer_stop(msg, xfer);
1262b158935fSMark Brown 
1263b158935fSMark Brown 		if (msg->status != -EINPROGRESS)
1264b158935fSMark Brown 			goto out;
1265b158935fSMark Brown 
1266bebcfd27SAlexandru Ardelean 		spi_transfer_delay_exec(xfer);
1267b158935fSMark Brown 
1268b158935fSMark Brown 		if (xfer->cs_change) {
1269b158935fSMark Brown 			if (list_is_last(&xfer->transfer_list,
1270b158935fSMark Brown 					 &msg->transfers)) {
1271b158935fSMark Brown 				keep_cs = true;
1272b158935fSMark Brown 			} else {
12730b73aa63SMark Brown 				spi_set_cs(msg->spi, false);
12740ff2de8bSMartin Sperl 				_spi_transfer_cs_change_delay(msg, xfer);
12750b73aa63SMark Brown 				spi_set_cs(msg->spi, true);
1276b158935fSMark Brown 			}
1277b158935fSMark Brown 		}
1278b158935fSMark Brown 
1279b158935fSMark Brown 		msg->actual_length += xfer->len;
1280b158935fSMark Brown 	}
1281b158935fSMark Brown 
1282b158935fSMark Brown out:
1283b158935fSMark Brown 	if (ret != 0 || !keep_cs)
1284b158935fSMark Brown 		spi_set_cs(msg->spi, false);
1285b158935fSMark Brown 
1286b158935fSMark Brown 	if (msg->status == -EINPROGRESS)
1287b158935fSMark Brown 		msg->status = ret;
1288b158935fSMark Brown 
12898caab75fSGeert Uytterhoeven 	if (msg->status && ctlr->handle_err)
12908caab75fSGeert Uytterhoeven 		ctlr->handle_err(ctlr, msg);
1291b716c4ffSAndy Shevchenko 
1292c9ba7a16SNoralf Trønnes 	spi_res_release(ctlr, msg);
1293c9ba7a16SNoralf Trønnes 
12940ed56252SMark Brown 	spi_finalize_current_message(ctlr);
12950ed56252SMark Brown 
1296b158935fSMark Brown 	return ret;
1297b158935fSMark Brown }
1298b158935fSMark Brown 
1299b158935fSMark Brown /**
1300b158935fSMark Brown  * spi_finalize_current_transfer - report completion of a transfer
13018caab75fSGeert Uytterhoeven  * @ctlr: the controller reporting completion
1302b158935fSMark Brown  *
1303b158935fSMark Brown  * Called by SPI drivers using the core transfer_one_message()
1304b158935fSMark Brown  * implementation to notify it that the current interrupt driven
13059e8f4882SGeert Uytterhoeven  * transfer has finished and the next one may be scheduled.
1306b158935fSMark Brown  */
13078caab75fSGeert Uytterhoeven void spi_finalize_current_transfer(struct spi_controller *ctlr)
1308b158935fSMark Brown {
13098caab75fSGeert Uytterhoeven 	complete(&ctlr->xfer_completion);
1310b158935fSMark Brown }
1311b158935fSMark Brown EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1312b158935fSMark Brown 
1313ffbbdd21SLinus Walleij /**
1314fc9e0f71SMark Brown  * __spi_pump_messages - function which processes spi message queue
13158caab75fSGeert Uytterhoeven  * @ctlr: controller to process queue for
1316fc9e0f71SMark Brown  * @in_kthread: true if we are in the context of the message pump thread
1317ffbbdd21SLinus Walleij  *
1318ffbbdd21SLinus Walleij  * This function checks if there is any spi message in the queue that
1319ffbbdd21SLinus Walleij  * needs processing and if so call out to the driver to initialize hardware
1320ffbbdd21SLinus Walleij  * and transfer each message.
1321ffbbdd21SLinus Walleij  *
13220461a414SMark Brown  * Note that it is called both from the kthread itself and also from
13230461a414SMark Brown  * inside spi_sync(); the queue extraction handling at the top of the
13240461a414SMark Brown  * function should deal with this safely.
1325ffbbdd21SLinus Walleij  */
13268caab75fSGeert Uytterhoeven static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1327ffbbdd21SLinus Walleij {
1328b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
1329d1c44c93SVladimir Oltean 	struct spi_message *msg;
1330ffbbdd21SLinus Walleij 	bool was_busy = false;
1331d1c44c93SVladimir Oltean 	unsigned long flags;
1332ffbbdd21SLinus Walleij 	int ret;
1333ffbbdd21SLinus Walleij 
1334983aee5dSMark Brown 	/* Lock queue */
13358caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1336983aee5dSMark Brown 
1337983aee5dSMark Brown 	/* Make sure we are not already running a message */
13388caab75fSGeert Uytterhoeven 	if (ctlr->cur_msg) {
13398caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1340983aee5dSMark Brown 		return;
1341983aee5dSMark Brown 	}
1342983aee5dSMark Brown 
1343f0125f1aSMark Brown 	/* If another context is idling the device then defer */
13448caab75fSGeert Uytterhoeven 	if (ctlr->idling) {
13458caab75fSGeert Uytterhoeven 		kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
13468caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
13470461a414SMark Brown 		return;
13480461a414SMark Brown 	}
13490461a414SMark Brown 
1350983aee5dSMark Brown 	/* Check if the queue is idle */
13518caab75fSGeert Uytterhoeven 	if (list_empty(&ctlr->queue) || !ctlr->running) {
13528caab75fSGeert Uytterhoeven 		if (!ctlr->busy) {
13538caab75fSGeert Uytterhoeven 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1354ffbbdd21SLinus Walleij 			return;
1355ffbbdd21SLinus Walleij 		}
1356fc9e0f71SMark Brown 
1357f0125f1aSMark Brown 		/* Only do teardown in the thread */
1358f0125f1aSMark Brown 		if (!in_kthread) {
1359f0125f1aSMark Brown 			kthread_queue_work(&ctlr->kworker,
1360f0125f1aSMark Brown 					   &ctlr->pump_messages);
1361f0125f1aSMark Brown 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1362f0125f1aSMark Brown 			return;
1363f0125f1aSMark Brown 		}
1364f0125f1aSMark Brown 
1365f0125f1aSMark Brown 		ctlr->busy = false;
1366f0125f1aSMark Brown 		ctlr->idling = true;
1367f0125f1aSMark Brown 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1368f0125f1aSMark Brown 
1369f0125f1aSMark Brown 		kfree(ctlr->dummy_rx);
1370f0125f1aSMark Brown 		ctlr->dummy_rx = NULL;
1371f0125f1aSMark Brown 		kfree(ctlr->dummy_tx);
1372f0125f1aSMark Brown 		ctlr->dummy_tx = NULL;
1373f0125f1aSMark Brown 		if (ctlr->unprepare_transfer_hardware &&
1374f0125f1aSMark Brown 		    ctlr->unprepare_transfer_hardware(ctlr))
1375f0125f1aSMark Brown 			dev_err(&ctlr->dev,
1376f0125f1aSMark Brown 				"failed to unprepare transfer hardware\n");
1377f0125f1aSMark Brown 		if (ctlr->auto_runtime_pm) {
1378f0125f1aSMark Brown 			pm_runtime_mark_last_busy(ctlr->dev.parent);
1379f0125f1aSMark Brown 			pm_runtime_put_autosuspend(ctlr->dev.parent);
1380f0125f1aSMark Brown 		}
1381f0125f1aSMark Brown 		trace_spi_controller_idle(ctlr);
1382f0125f1aSMark Brown 
1383f0125f1aSMark Brown 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1384f0125f1aSMark Brown 		ctlr->idling = false;
13858caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1386ffbbdd21SLinus Walleij 		return;
1387ffbbdd21SLinus Walleij 	}
1388ffbbdd21SLinus Walleij 
1389ffbbdd21SLinus Walleij 	/* Extract head of queue */
1390d1c44c93SVladimir Oltean 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1391d1c44c93SVladimir Oltean 	ctlr->cur_msg = msg;
1392ffbbdd21SLinus Walleij 
1393d1c44c93SVladimir Oltean 	list_del_init(&msg->queue);
13948caab75fSGeert Uytterhoeven 	if (ctlr->busy)
1395ffbbdd21SLinus Walleij 		was_busy = true;
1396ffbbdd21SLinus Walleij 	else
13978caab75fSGeert Uytterhoeven 		ctlr->busy = true;
13988caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1399ffbbdd21SLinus Walleij 
14008caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->io_mutex);
1401ef4d96ecSMark Brown 
14028caab75fSGeert Uytterhoeven 	if (!was_busy && ctlr->auto_runtime_pm) {
14038caab75fSGeert Uytterhoeven 		ret = pm_runtime_get_sync(ctlr->dev.parent);
140449834de2SMark Brown 		if (ret < 0) {
14057e48e23aSTony Lindgren 			pm_runtime_put_noidle(ctlr->dev.parent);
14068caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
140749834de2SMark Brown 				ret);
14088caab75fSGeert Uytterhoeven 			mutex_unlock(&ctlr->io_mutex);
140949834de2SMark Brown 			return;
141049834de2SMark Brown 		}
141149834de2SMark Brown 	}
141249834de2SMark Brown 
141356ec1978SMark Brown 	if (!was_busy)
14148caab75fSGeert Uytterhoeven 		trace_spi_controller_busy(ctlr);
141556ec1978SMark Brown 
14168caab75fSGeert Uytterhoeven 	if (!was_busy && ctlr->prepare_transfer_hardware) {
14178caab75fSGeert Uytterhoeven 		ret = ctlr->prepare_transfer_hardware(ctlr);
1418ffbbdd21SLinus Walleij 		if (ret) {
14198caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev,
1420f3440d9aSSuper Liu 				"failed to prepare transfer hardware: %d\n",
1421f3440d9aSSuper Liu 				ret);
142249834de2SMark Brown 
14238caab75fSGeert Uytterhoeven 			if (ctlr->auto_runtime_pm)
14248caab75fSGeert Uytterhoeven 				pm_runtime_put(ctlr->dev.parent);
1425f3440d9aSSuper Liu 
1426d1c44c93SVladimir Oltean 			msg->status = ret;
1427f3440d9aSSuper Liu 			spi_finalize_current_message(ctlr);
1428f3440d9aSSuper Liu 
14298caab75fSGeert Uytterhoeven 			mutex_unlock(&ctlr->io_mutex);
1430ffbbdd21SLinus Walleij 			return;
1431ffbbdd21SLinus Walleij 		}
1432ffbbdd21SLinus Walleij 	}
1433ffbbdd21SLinus Walleij 
1434d1c44c93SVladimir Oltean 	trace_spi_message_start(msg);
143556ec1978SMark Brown 
14368caab75fSGeert Uytterhoeven 	if (ctlr->prepare_message) {
1437d1c44c93SVladimir Oltean 		ret = ctlr->prepare_message(ctlr, msg);
14382841a5fcSMark Brown 		if (ret) {
14398caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
14408caab75fSGeert Uytterhoeven 				ret);
1441d1c44c93SVladimir Oltean 			msg->status = ret;
14428caab75fSGeert Uytterhoeven 			spi_finalize_current_message(ctlr);
144349023d2eSJon Hunter 			goto out;
14442841a5fcSMark Brown 		}
14458caab75fSGeert Uytterhoeven 		ctlr->cur_msg_prepared = true;
14462841a5fcSMark Brown 	}
14472841a5fcSMark Brown 
1448d1c44c93SVladimir Oltean 	ret = spi_map_msg(ctlr, msg);
144999adef31SMark Brown 	if (ret) {
1450d1c44c93SVladimir Oltean 		msg->status = ret;
14518caab75fSGeert Uytterhoeven 		spi_finalize_current_message(ctlr);
145249023d2eSJon Hunter 		goto out;
145399adef31SMark Brown 	}
145499adef31SMark Brown 
1455b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1456b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1457b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
1458b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
1459b42faeeeSVladimir Oltean 		}
1460b42faeeeSVladimir Oltean 	}
1461b42faeeeSVladimir Oltean 
1462d1c44c93SVladimir Oltean 	ret = ctlr->transfer_one_message(ctlr, msg);
1463ffbbdd21SLinus Walleij 	if (ret) {
14648caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev,
14651f802f82SGeert Uytterhoeven 			"failed to transfer one message from queue\n");
146649023d2eSJon Hunter 		goto out;
1467ffbbdd21SLinus Walleij 	}
146849023d2eSJon Hunter 
146949023d2eSJon Hunter out:
14708caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->io_mutex);
147162826970SMark Brown 
147262826970SMark Brown 	/* Prod the scheduler in case transfer_one() was busy waiting */
147349023d2eSJon Hunter 	if (!ret)
147462826970SMark Brown 		cond_resched();
1475ffbbdd21SLinus Walleij }
1476ffbbdd21SLinus Walleij 
1477fc9e0f71SMark Brown /**
1478fc9e0f71SMark Brown  * spi_pump_messages - kthread work function which processes spi message queue
14798caab75fSGeert Uytterhoeven  * @work: pointer to kthread work struct contained in the controller struct
1480fc9e0f71SMark Brown  */
1481fc9e0f71SMark Brown static void spi_pump_messages(struct kthread_work *work)
1482fc9e0f71SMark Brown {
14838caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr =
14848caab75fSGeert Uytterhoeven 		container_of(work, struct spi_controller, pump_messages);
1485fc9e0f71SMark Brown 
14868caab75fSGeert Uytterhoeven 	__spi_pump_messages(ctlr, true);
1487fc9e0f71SMark Brown }
1488fc9e0f71SMark Brown 
1489924b5867SDouglas Anderson /**
1490b42faeeeSVladimir Oltean  * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1491b42faeeeSVladimir Oltean  *			    TX timestamp for the requested byte from the SPI
1492b42faeeeSVladimir Oltean  *			    transfer. The frequency with which this function
1493b42faeeeSVladimir Oltean  *			    must be called (once per word, once for the whole
1494b42faeeeSVladimir Oltean  *			    transfer, once per batch of words etc) is arbitrary
1495b42faeeeSVladimir Oltean  *			    as long as the @tx buffer offset is greater than or
1496b42faeeeSVladimir Oltean  *			    equal to the requested byte at the time of the
1497b42faeeeSVladimir Oltean  *			    call. The timestamp is only taken once, at the
1498b42faeeeSVladimir Oltean  *			    first such call. It is assumed that the driver
1499b42faeeeSVladimir Oltean  *			    advances its @tx buffer pointer monotonically.
1500b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1501b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1502*862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1503b42faeeeSVladimir Oltean  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1504b42faeeeSVladimir Oltean  *	      transfer, for less jitter in time measurement. Only compatible
1505b42faeeeSVladimir Oltean  *	      with PIO drivers. If true, must follow up with
1506b42faeeeSVladimir Oltean  *	      spi_take_timestamp_post or otherwise system will crash.
1507b42faeeeSVladimir Oltean  *	      WARNING: for fully predictable results, the CPU frequency must
1508b42faeeeSVladimir Oltean  *	      also be under control (governor).
1509b42faeeeSVladimir Oltean  */
1510b42faeeeSVladimir Oltean void spi_take_timestamp_pre(struct spi_controller *ctlr,
1511b42faeeeSVladimir Oltean 			    struct spi_transfer *xfer,
1512*862dd2a9SVladimir Oltean 			    size_t progress, bool irqs_off)
1513b42faeeeSVladimir Oltean {
1514b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1515b42faeeeSVladimir Oltean 		return;
1516b42faeeeSVladimir Oltean 
1517b42faeeeSVladimir Oltean 	if (xfer->timestamped_pre)
1518b42faeeeSVladimir Oltean 		return;
1519b42faeeeSVladimir Oltean 
1520*862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_pre)
1521b42faeeeSVladimir Oltean 		return;
1522b42faeeeSVladimir Oltean 
1523b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1524*862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_pre = progress;
1525b42faeeeSVladimir Oltean 
1526b42faeeeSVladimir Oltean 	xfer->timestamped_pre = true;
1527b42faeeeSVladimir Oltean 
1528b42faeeeSVladimir Oltean 	if (irqs_off) {
1529b42faeeeSVladimir Oltean 		local_irq_save(ctlr->irq_flags);
1530b42faeeeSVladimir Oltean 		preempt_disable();
1531b42faeeeSVladimir Oltean 	}
1532b42faeeeSVladimir Oltean 
1533b42faeeeSVladimir Oltean 	ptp_read_system_prets(xfer->ptp_sts);
1534b42faeeeSVladimir Oltean }
1535b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1536b42faeeeSVladimir Oltean 
1537b42faeeeSVladimir Oltean /**
1538b42faeeeSVladimir Oltean  * spi_take_timestamp_post - helper for drivers to collect the end of the
1539b42faeeeSVladimir Oltean  *			     TX timestamp for the requested byte from the SPI
1540b42faeeeSVladimir Oltean  *			     transfer. Can be called with an arbitrary
1541b42faeeeSVladimir Oltean  *			     frequency: only the first call where @tx exceeds
1542b42faeeeSVladimir Oltean  *			     or is equal to the requested word will be
1543b42faeeeSVladimir Oltean  *			     timestamped.
1544b42faeeeSVladimir Oltean  * @ctlr: Pointer to the spi_controller structure of the driver
1545b42faeeeSVladimir Oltean  * @xfer: Pointer to the transfer being timestamped
1546*862dd2a9SVladimir Oltean  * @progress: How many words (not bytes) have been transferred so far
1547b42faeeeSVladimir Oltean  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1548b42faeeeSVladimir Oltean  */
1549b42faeeeSVladimir Oltean void spi_take_timestamp_post(struct spi_controller *ctlr,
1550b42faeeeSVladimir Oltean 			     struct spi_transfer *xfer,
1551*862dd2a9SVladimir Oltean 			     size_t progress, bool irqs_off)
1552b42faeeeSVladimir Oltean {
1553b42faeeeSVladimir Oltean 	if (!xfer->ptp_sts)
1554b42faeeeSVladimir Oltean 		return;
1555b42faeeeSVladimir Oltean 
1556b42faeeeSVladimir Oltean 	if (xfer->timestamped_post)
1557b42faeeeSVladimir Oltean 		return;
1558b42faeeeSVladimir Oltean 
1559*862dd2a9SVladimir Oltean 	if (progress < xfer->ptp_sts_word_post)
1560b42faeeeSVladimir Oltean 		return;
1561b42faeeeSVladimir Oltean 
1562b42faeeeSVladimir Oltean 	ptp_read_system_postts(xfer->ptp_sts);
1563b42faeeeSVladimir Oltean 
1564b42faeeeSVladimir Oltean 	if (irqs_off) {
1565b42faeeeSVladimir Oltean 		local_irq_restore(ctlr->irq_flags);
1566b42faeeeSVladimir Oltean 		preempt_enable();
1567b42faeeeSVladimir Oltean 	}
1568b42faeeeSVladimir Oltean 
1569b42faeeeSVladimir Oltean 	/* Capture the resolution of the timestamp */
1570*862dd2a9SVladimir Oltean 	xfer->ptp_sts_word_post = progress;
1571b42faeeeSVladimir Oltean 
1572b42faeeeSVladimir Oltean 	xfer->timestamped_post = true;
1573b42faeeeSVladimir Oltean }
1574b42faeeeSVladimir Oltean EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1575b42faeeeSVladimir Oltean 
1576b42faeeeSVladimir Oltean /**
1577924b5867SDouglas Anderson  * spi_set_thread_rt - set the controller to pump at realtime priority
1578924b5867SDouglas Anderson  * @ctlr: controller to boost priority of
1579924b5867SDouglas Anderson  *
1580924b5867SDouglas Anderson  * This can be called because the controller requested realtime priority
1581924b5867SDouglas Anderson  * (by setting the ->rt value before calling spi_register_controller()) or
1582924b5867SDouglas Anderson  * because a device on the bus said that its transfers needed realtime
1583924b5867SDouglas Anderson  * priority.
1584924b5867SDouglas Anderson  *
1585924b5867SDouglas Anderson  * NOTE: at the moment if any device on a bus says it needs realtime then
1586924b5867SDouglas Anderson  * the thread will be at realtime priority for all transfers on that
1587924b5867SDouglas Anderson  * controller.  If this eventually becomes a problem we may see if we can
1588924b5867SDouglas Anderson  * find a way to boost the priority only temporarily during relevant
1589924b5867SDouglas Anderson  * transfers.
1590924b5867SDouglas Anderson  */
1591924b5867SDouglas Anderson static void spi_set_thread_rt(struct spi_controller *ctlr)
1592ffbbdd21SLinus Walleij {
15934ff13d00SPeter Zijlstra 	struct sched_param param = { .sched_priority = MAX_RT_PRIO / 2 };
1594ffbbdd21SLinus Walleij 
1595924b5867SDouglas Anderson 	dev_info(&ctlr->dev,
1596924b5867SDouglas Anderson 		"will run message pump with realtime priority\n");
1597924b5867SDouglas Anderson 	sched_setscheduler(ctlr->kworker_task, SCHED_FIFO, &param);
1598924b5867SDouglas Anderson }
1599924b5867SDouglas Anderson 
1600924b5867SDouglas Anderson static int spi_init_queue(struct spi_controller *ctlr)
1601924b5867SDouglas Anderson {
16028caab75fSGeert Uytterhoeven 	ctlr->running = false;
16038caab75fSGeert Uytterhoeven 	ctlr->busy = false;
1604ffbbdd21SLinus Walleij 
16058caab75fSGeert Uytterhoeven 	kthread_init_worker(&ctlr->kworker);
16068caab75fSGeert Uytterhoeven 	ctlr->kworker_task = kthread_run(kthread_worker_fn, &ctlr->kworker,
16078caab75fSGeert Uytterhoeven 					 "%s", dev_name(&ctlr->dev));
16088caab75fSGeert Uytterhoeven 	if (IS_ERR(ctlr->kworker_task)) {
16098caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to create message pump task\n");
16108caab75fSGeert Uytterhoeven 		return PTR_ERR(ctlr->kworker_task);
1611ffbbdd21SLinus Walleij 	}
16128caab75fSGeert Uytterhoeven 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1613f0125f1aSMark Brown 
1614ffbbdd21SLinus Walleij 	/*
16158caab75fSGeert Uytterhoeven 	 * Controller config will indicate if this controller should run the
1616ffbbdd21SLinus Walleij 	 * message pump with high (realtime) priority to reduce the transfer
1617ffbbdd21SLinus Walleij 	 * latency on the bus by minimising the delay between a transfer
1618ffbbdd21SLinus Walleij 	 * request and the scheduling of the message pump thread. Without this
1619ffbbdd21SLinus Walleij 	 * setting the message pump thread will remain at default priority.
1620ffbbdd21SLinus Walleij 	 */
1621924b5867SDouglas Anderson 	if (ctlr->rt)
1622924b5867SDouglas Anderson 		spi_set_thread_rt(ctlr);
1623ffbbdd21SLinus Walleij 
1624ffbbdd21SLinus Walleij 	return 0;
1625ffbbdd21SLinus Walleij }
1626ffbbdd21SLinus Walleij 
1627ffbbdd21SLinus Walleij /**
1628ffbbdd21SLinus Walleij  * spi_get_next_queued_message() - called by driver to check for queued
1629ffbbdd21SLinus Walleij  * messages
16308caab75fSGeert Uytterhoeven  * @ctlr: the controller to check for queued messages
1631ffbbdd21SLinus Walleij  *
1632ffbbdd21SLinus Walleij  * If there are more messages in the queue, the next message is returned from
1633ffbbdd21SLinus Walleij  * this call.
163497d56dc6SJavier Martinez Canillas  *
163597d56dc6SJavier Martinez Canillas  * Return: the next message in the queue, else NULL if the queue is empty.
1636ffbbdd21SLinus Walleij  */
16378caab75fSGeert Uytterhoeven struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1638ffbbdd21SLinus Walleij {
1639ffbbdd21SLinus Walleij 	struct spi_message *next;
1640ffbbdd21SLinus Walleij 	unsigned long flags;
1641ffbbdd21SLinus Walleij 
1642ffbbdd21SLinus Walleij 	/* get a pointer to the next message, if any */
16438caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
16448caab75fSGeert Uytterhoeven 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
16451cfd97f9SAxel Lin 					queue);
16468caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1647ffbbdd21SLinus Walleij 
1648ffbbdd21SLinus Walleij 	return next;
1649ffbbdd21SLinus Walleij }
1650ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1651ffbbdd21SLinus Walleij 
1652ffbbdd21SLinus Walleij /**
1653ffbbdd21SLinus Walleij  * spi_finalize_current_message() - the current message is complete
16548caab75fSGeert Uytterhoeven  * @ctlr: the controller to return the message to
1655ffbbdd21SLinus Walleij  *
1656ffbbdd21SLinus Walleij  * Called by the driver to notify the core that the message in the front of the
1657ffbbdd21SLinus Walleij  * queue is complete and can be removed from the queue.
1658ffbbdd21SLinus Walleij  */
16598caab75fSGeert Uytterhoeven void spi_finalize_current_message(struct spi_controller *ctlr)
1660ffbbdd21SLinus Walleij {
1661b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
1662ffbbdd21SLinus Walleij 	struct spi_message *mesg;
1663ffbbdd21SLinus Walleij 	unsigned long flags;
16642841a5fcSMark Brown 	int ret;
1665ffbbdd21SLinus Walleij 
16668caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
16678caab75fSGeert Uytterhoeven 	mesg = ctlr->cur_msg;
16688caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1669ffbbdd21SLinus Walleij 
1670b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1671b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1672b42faeeeSVladimir Oltean 			ptp_read_system_postts(xfer->ptp_sts);
1673b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_post = xfer->len;
1674b42faeeeSVladimir Oltean 		}
1675b42faeeeSVladimir Oltean 	}
1676b42faeeeSVladimir Oltean 
16778caab75fSGeert Uytterhoeven 	spi_unmap_msg(ctlr, mesg);
167899adef31SMark Brown 
16798caab75fSGeert Uytterhoeven 	if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
16808caab75fSGeert Uytterhoeven 		ret = ctlr->unprepare_message(ctlr, mesg);
16812841a5fcSMark Brown 		if (ret) {
16828caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
16838caab75fSGeert Uytterhoeven 				ret);
16842841a5fcSMark Brown 		}
16852841a5fcSMark Brown 	}
1686391949b6SUwe Kleine-König 
16878caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
16888caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
16898caab75fSGeert Uytterhoeven 	ctlr->cur_msg_prepared = false;
16908caab75fSGeert Uytterhoeven 	kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
16918caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
16928e76ef88SMartin Sperl 
16938e76ef88SMartin Sperl 	trace_spi_message_done(mesg);
16942841a5fcSMark Brown 
1695ffbbdd21SLinus Walleij 	mesg->state = NULL;
1696ffbbdd21SLinus Walleij 	if (mesg->complete)
1697ffbbdd21SLinus Walleij 		mesg->complete(mesg->context);
1698ffbbdd21SLinus Walleij }
1699ffbbdd21SLinus Walleij EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1700ffbbdd21SLinus Walleij 
17018caab75fSGeert Uytterhoeven static int spi_start_queue(struct spi_controller *ctlr)
1702ffbbdd21SLinus Walleij {
1703ffbbdd21SLinus Walleij 	unsigned long flags;
1704ffbbdd21SLinus Walleij 
17058caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1706ffbbdd21SLinus Walleij 
17078caab75fSGeert Uytterhoeven 	if (ctlr->running || ctlr->busy) {
17088caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1709ffbbdd21SLinus Walleij 		return -EBUSY;
1710ffbbdd21SLinus Walleij 	}
1711ffbbdd21SLinus Walleij 
17128caab75fSGeert Uytterhoeven 	ctlr->running = true;
17138caab75fSGeert Uytterhoeven 	ctlr->cur_msg = NULL;
17148caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1715ffbbdd21SLinus Walleij 
17168caab75fSGeert Uytterhoeven 	kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1717ffbbdd21SLinus Walleij 
1718ffbbdd21SLinus Walleij 	return 0;
1719ffbbdd21SLinus Walleij }
1720ffbbdd21SLinus Walleij 
17218caab75fSGeert Uytterhoeven static int spi_stop_queue(struct spi_controller *ctlr)
1722ffbbdd21SLinus Walleij {
1723ffbbdd21SLinus Walleij 	unsigned long flags;
1724ffbbdd21SLinus Walleij 	unsigned limit = 500;
1725ffbbdd21SLinus Walleij 	int ret = 0;
1726ffbbdd21SLinus Walleij 
17278caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1728ffbbdd21SLinus Walleij 
1729ffbbdd21SLinus Walleij 	/*
1730ffbbdd21SLinus Walleij 	 * This is a bit lame, but is optimized for the common execution path.
17318caab75fSGeert Uytterhoeven 	 * A wait_queue on the ctlr->busy could be used, but then the common
1732ffbbdd21SLinus Walleij 	 * execution path (pump_messages) would be required to call wake_up or
1733ffbbdd21SLinus Walleij 	 * friends on every SPI message. Do this instead.
1734ffbbdd21SLinus Walleij 	 */
17358caab75fSGeert Uytterhoeven 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
17368caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1737f97b26b0SAxel Lin 		usleep_range(10000, 11000);
17388caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1739ffbbdd21SLinus Walleij 	}
1740ffbbdd21SLinus Walleij 
17418caab75fSGeert Uytterhoeven 	if (!list_empty(&ctlr->queue) || ctlr->busy)
1742ffbbdd21SLinus Walleij 		ret = -EBUSY;
1743ffbbdd21SLinus Walleij 	else
17448caab75fSGeert Uytterhoeven 		ctlr->running = false;
1745ffbbdd21SLinus Walleij 
17468caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1747ffbbdd21SLinus Walleij 
1748ffbbdd21SLinus Walleij 	if (ret) {
17498caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "could not stop message queue\n");
1750ffbbdd21SLinus Walleij 		return ret;
1751ffbbdd21SLinus Walleij 	}
1752ffbbdd21SLinus Walleij 	return ret;
1753ffbbdd21SLinus Walleij }
1754ffbbdd21SLinus Walleij 
17558caab75fSGeert Uytterhoeven static int spi_destroy_queue(struct spi_controller *ctlr)
1756ffbbdd21SLinus Walleij {
1757ffbbdd21SLinus Walleij 	int ret;
1758ffbbdd21SLinus Walleij 
17598caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
1760ffbbdd21SLinus Walleij 
1761ffbbdd21SLinus Walleij 	/*
17623989144fSPetr Mladek 	 * kthread_flush_worker will block until all work is done.
1763ffbbdd21SLinus Walleij 	 * If the reason that stop_queue timed out is that the work will never
1764ffbbdd21SLinus Walleij 	 * finish, then it does no good to call flush/stop thread, so
1765ffbbdd21SLinus Walleij 	 * return anyway.
1766ffbbdd21SLinus Walleij 	 */
1767ffbbdd21SLinus Walleij 	if (ret) {
17688caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem destroying queue\n");
1769ffbbdd21SLinus Walleij 		return ret;
1770ffbbdd21SLinus Walleij 	}
1771ffbbdd21SLinus Walleij 
17728caab75fSGeert Uytterhoeven 	kthread_flush_worker(&ctlr->kworker);
17738caab75fSGeert Uytterhoeven 	kthread_stop(ctlr->kworker_task);
1774ffbbdd21SLinus Walleij 
1775ffbbdd21SLinus Walleij 	return 0;
1776ffbbdd21SLinus Walleij }
1777ffbbdd21SLinus Walleij 
17780461a414SMark Brown static int __spi_queued_transfer(struct spi_device *spi,
17790461a414SMark Brown 				 struct spi_message *msg,
17800461a414SMark Brown 				 bool need_pump)
1781ffbbdd21SLinus Walleij {
17828caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
1783ffbbdd21SLinus Walleij 	unsigned long flags;
1784ffbbdd21SLinus Walleij 
17858caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1786ffbbdd21SLinus Walleij 
17878caab75fSGeert Uytterhoeven 	if (!ctlr->running) {
17888caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1789ffbbdd21SLinus Walleij 		return -ESHUTDOWN;
1790ffbbdd21SLinus Walleij 	}
1791ffbbdd21SLinus Walleij 	msg->actual_length = 0;
1792ffbbdd21SLinus Walleij 	msg->status = -EINPROGRESS;
1793ffbbdd21SLinus Walleij 
17948caab75fSGeert Uytterhoeven 	list_add_tail(&msg->queue, &ctlr->queue);
1795f0125f1aSMark Brown 	if (!ctlr->busy && need_pump)
17968caab75fSGeert Uytterhoeven 		kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
1797ffbbdd21SLinus Walleij 
17988caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1799ffbbdd21SLinus Walleij 	return 0;
1800ffbbdd21SLinus Walleij }
1801ffbbdd21SLinus Walleij 
18020461a414SMark Brown /**
18030461a414SMark Brown  * spi_queued_transfer - transfer function for queued transfers
18040461a414SMark Brown  * @spi: spi device which is requesting transfer
18050461a414SMark Brown  * @msg: spi message which is to handled is queued to driver queue
180697d56dc6SJavier Martinez Canillas  *
180797d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
18080461a414SMark Brown  */
18090461a414SMark Brown static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
18100461a414SMark Brown {
18110461a414SMark Brown 	return __spi_queued_transfer(spi, msg, true);
18120461a414SMark Brown }
18130461a414SMark Brown 
18148caab75fSGeert Uytterhoeven static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1815ffbbdd21SLinus Walleij {
1816ffbbdd21SLinus Walleij 	int ret;
1817ffbbdd21SLinus Walleij 
18188caab75fSGeert Uytterhoeven 	ctlr->transfer = spi_queued_transfer;
18198caab75fSGeert Uytterhoeven 	if (!ctlr->transfer_one_message)
18208caab75fSGeert Uytterhoeven 		ctlr->transfer_one_message = spi_transfer_one_message;
1821ffbbdd21SLinus Walleij 
1822ffbbdd21SLinus Walleij 	/* Initialize and start queue */
18238caab75fSGeert Uytterhoeven 	ret = spi_init_queue(ctlr);
1824ffbbdd21SLinus Walleij 	if (ret) {
18258caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem initializing queue\n");
1826ffbbdd21SLinus Walleij 		goto err_init_queue;
1827ffbbdd21SLinus Walleij 	}
18288caab75fSGeert Uytterhoeven 	ctlr->queued = true;
18298caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
1830ffbbdd21SLinus Walleij 	if (ret) {
18318caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "problem starting queue\n");
1832ffbbdd21SLinus Walleij 		goto err_start_queue;
1833ffbbdd21SLinus Walleij 	}
1834ffbbdd21SLinus Walleij 
1835ffbbdd21SLinus Walleij 	return 0;
1836ffbbdd21SLinus Walleij 
1837ffbbdd21SLinus Walleij err_start_queue:
18388caab75fSGeert Uytterhoeven 	spi_destroy_queue(ctlr);
1839c3676d5cSMark Brown err_init_queue:
1840ffbbdd21SLinus Walleij 	return ret;
1841ffbbdd21SLinus Walleij }
1842ffbbdd21SLinus Walleij 
1843988f259bSBoris Brezillon /**
1844988f259bSBoris Brezillon  * spi_flush_queue - Send all pending messages in the queue from the callers'
1845988f259bSBoris Brezillon  *		     context
1846988f259bSBoris Brezillon  * @ctlr: controller to process queue for
1847988f259bSBoris Brezillon  *
1848988f259bSBoris Brezillon  * This should be used when one wants to ensure all pending messages have been
1849988f259bSBoris Brezillon  * sent before doing something. Is used by the spi-mem code to make sure SPI
1850988f259bSBoris Brezillon  * memory operations do not preempt regular SPI transfers that have been queued
1851988f259bSBoris Brezillon  * before the spi-mem operation.
1852988f259bSBoris Brezillon  */
1853988f259bSBoris Brezillon void spi_flush_queue(struct spi_controller *ctlr)
1854988f259bSBoris Brezillon {
1855988f259bSBoris Brezillon 	if (ctlr->transfer == spi_queued_transfer)
1856988f259bSBoris Brezillon 		__spi_pump_messages(ctlr, false);
1857988f259bSBoris Brezillon }
1858988f259bSBoris Brezillon 
1859ffbbdd21SLinus Walleij /*-------------------------------------------------------------------------*/
1860ffbbdd21SLinus Walleij 
18617cb94361SAndreas Larsson #if defined(CONFIG_OF)
18628caab75fSGeert Uytterhoeven static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1863c2e51ac3SGeert Uytterhoeven 			   struct device_node *nc)
1864d57a4282SGrant Likely {
186589da4293STrent Piepho 	u32 value;
1866c2e51ac3SGeert Uytterhoeven 	int rc;
1867d57a4282SGrant Likely 
1868d57a4282SGrant Likely 	/* Mode (clock phase/polarity/etc.) */
1869e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpha"))
1870d57a4282SGrant Likely 		spi->mode |= SPI_CPHA;
1871e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-cpol"))
1872d57a4282SGrant Likely 		spi->mode |= SPI_CPOL;
1873e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-3wire"))
1874c20151dfSLars-Peter Clausen 		spi->mode |= SPI_3WIRE;
1875e0bcb680SSergei Shtylyov 	if (of_property_read_bool(nc, "spi-lsb-first"))
1876cd6339e6SZhao Qiang 		spi->mode |= SPI_LSB_FIRST;
1877d57a4282SGrant Likely 
1878f3186dd8SLinus Walleij 	/*
1879f3186dd8SLinus Walleij 	 * For descriptors associated with the device, polarity inversion is
1880f3186dd8SLinus Walleij 	 * handled in the gpiolib, so all chip selects are "active high" in
1881f3186dd8SLinus Walleij 	 * the logical sense, the gpiolib will invert the line if need be.
1882f3186dd8SLinus Walleij 	 */
1883f3186dd8SLinus Walleij 	if (ctlr->use_gpio_descriptors)
1884f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
1885f3186dd8SLinus Walleij 	else if (of_property_read_bool(nc, "spi-cs-high"))
1886f3186dd8SLinus Walleij 		spi->mode |= SPI_CS_HIGH;
1887f3186dd8SLinus Walleij 
1888f477b7fbSwangyuhang 	/* Device DUAL/QUAD mode */
188989da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
189089da4293STrent Piepho 		switch (value) {
189189da4293STrent Piepho 		case 1:
1892f477b7fbSwangyuhang 			break;
189389da4293STrent Piepho 		case 2:
1894f477b7fbSwangyuhang 			spi->mode |= SPI_TX_DUAL;
1895f477b7fbSwangyuhang 			break;
189689da4293STrent Piepho 		case 4:
1897f477b7fbSwangyuhang 			spi->mode |= SPI_TX_QUAD;
1898f477b7fbSwangyuhang 			break;
18996b03061fSYogesh Narayan Gaur 		case 8:
19006b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_TX_OCTAL;
19016b03061fSYogesh Narayan Gaur 			break;
1902f477b7fbSwangyuhang 		default:
19038caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
1904a110f93dSwangyuhang 				"spi-tx-bus-width %d not supported\n",
190589da4293STrent Piepho 				value);
190680874d8cSGeert Uytterhoeven 			break;
1907f477b7fbSwangyuhang 		}
1908a822e99cSMark Brown 	}
1909f477b7fbSwangyuhang 
191089da4293STrent Piepho 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
191189da4293STrent Piepho 		switch (value) {
191289da4293STrent Piepho 		case 1:
1913f477b7fbSwangyuhang 			break;
191489da4293STrent Piepho 		case 2:
1915f477b7fbSwangyuhang 			spi->mode |= SPI_RX_DUAL;
1916f477b7fbSwangyuhang 			break;
191789da4293STrent Piepho 		case 4:
1918f477b7fbSwangyuhang 			spi->mode |= SPI_RX_QUAD;
1919f477b7fbSwangyuhang 			break;
19206b03061fSYogesh Narayan Gaur 		case 8:
19216b03061fSYogesh Narayan Gaur 			spi->mode |= SPI_RX_OCTAL;
19226b03061fSYogesh Narayan Gaur 			break;
1923f477b7fbSwangyuhang 		default:
19248caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
1925a110f93dSwangyuhang 				"spi-rx-bus-width %d not supported\n",
192689da4293STrent Piepho 				value);
192780874d8cSGeert Uytterhoeven 			break;
1928f477b7fbSwangyuhang 		}
1929a822e99cSMark Brown 	}
1930f477b7fbSwangyuhang 
19318caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr)) {
1932194276b0SRob Herring 		if (!of_node_name_eq(nc, "slave")) {
193325c56c88SRob Herring 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
193425c56c88SRob Herring 				nc);
19356c364062SGeert Uytterhoeven 			return -EINVAL;
19366c364062SGeert Uytterhoeven 		}
19376c364062SGeert Uytterhoeven 		return 0;
19386c364062SGeert Uytterhoeven 	}
19396c364062SGeert Uytterhoeven 
19406c364062SGeert Uytterhoeven 	/* Device address */
19416c364062SGeert Uytterhoeven 	rc = of_property_read_u32(nc, "reg", &value);
19426c364062SGeert Uytterhoeven 	if (rc) {
194325c56c88SRob Herring 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
194425c56c88SRob Herring 			nc, rc);
19456c364062SGeert Uytterhoeven 		return rc;
19466c364062SGeert Uytterhoeven 	}
19476c364062SGeert Uytterhoeven 	spi->chip_select = value;
19486c364062SGeert Uytterhoeven 
1949d57a4282SGrant Likely 	/* Device speed */
195089da4293STrent Piepho 	rc = of_property_read_u32(nc, "spi-max-frequency", &value);
195189da4293STrent Piepho 	if (rc) {
19528caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev,
195325c56c88SRob Herring 			"%pOF has no valid 'spi-max-frequency' property (%d)\n", nc, rc);
1954c2e51ac3SGeert Uytterhoeven 		return rc;
1955d57a4282SGrant Likely 	}
195689da4293STrent Piepho 	spi->max_speed_hz = value;
1957d57a4282SGrant Likely 
1958c2e51ac3SGeert Uytterhoeven 	return 0;
1959c2e51ac3SGeert Uytterhoeven }
1960c2e51ac3SGeert Uytterhoeven 
1961c2e51ac3SGeert Uytterhoeven static struct spi_device *
19628caab75fSGeert Uytterhoeven of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
1963c2e51ac3SGeert Uytterhoeven {
1964c2e51ac3SGeert Uytterhoeven 	struct spi_device *spi;
1965c2e51ac3SGeert Uytterhoeven 	int rc;
1966c2e51ac3SGeert Uytterhoeven 
1967c2e51ac3SGeert Uytterhoeven 	/* Alloc an spi_device */
19688caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
1969c2e51ac3SGeert Uytterhoeven 	if (!spi) {
197025c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
1971c2e51ac3SGeert Uytterhoeven 		rc = -ENOMEM;
1972c2e51ac3SGeert Uytterhoeven 		goto err_out;
1973c2e51ac3SGeert Uytterhoeven 	}
1974c2e51ac3SGeert Uytterhoeven 
1975c2e51ac3SGeert Uytterhoeven 	/* Select device driver */
1976c2e51ac3SGeert Uytterhoeven 	rc = of_modalias_node(nc, spi->modalias,
1977c2e51ac3SGeert Uytterhoeven 				sizeof(spi->modalias));
1978c2e51ac3SGeert Uytterhoeven 	if (rc < 0) {
197925c56c88SRob Herring 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
1980c2e51ac3SGeert Uytterhoeven 		goto err_out;
1981c2e51ac3SGeert Uytterhoeven 	}
1982c2e51ac3SGeert Uytterhoeven 
19838caab75fSGeert Uytterhoeven 	rc = of_spi_parse_dt(ctlr, spi, nc);
1984c2e51ac3SGeert Uytterhoeven 	if (rc)
1985c2e51ac3SGeert Uytterhoeven 		goto err_out;
1986c2e51ac3SGeert Uytterhoeven 
1987d57a4282SGrant Likely 	/* Store a pointer to the node in the device structure */
1988d57a4282SGrant Likely 	of_node_get(nc);
1989d57a4282SGrant Likely 	spi->dev.of_node = nc;
1990d57a4282SGrant Likely 
1991d57a4282SGrant Likely 	/* Register the new device */
1992d57a4282SGrant Likely 	rc = spi_add_device(spi);
1993d57a4282SGrant Likely 	if (rc) {
199425c56c88SRob Herring 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
19958324147fSJohan Hovold 		goto err_of_node_put;
1996d57a4282SGrant Likely 	}
1997d57a4282SGrant Likely 
1998aff5e3f8SPantelis Antoniou 	return spi;
1999aff5e3f8SPantelis Antoniou 
20008324147fSJohan Hovold err_of_node_put:
20018324147fSJohan Hovold 	of_node_put(nc);
2002aff5e3f8SPantelis Antoniou err_out:
2003aff5e3f8SPantelis Antoniou 	spi_dev_put(spi);
2004aff5e3f8SPantelis Antoniou 	return ERR_PTR(rc);
2005aff5e3f8SPantelis Antoniou }
2006aff5e3f8SPantelis Antoniou 
2007aff5e3f8SPantelis Antoniou /**
2008aff5e3f8SPantelis Antoniou  * of_register_spi_devices() - Register child devices onto the SPI bus
20098caab75fSGeert Uytterhoeven  * @ctlr:	Pointer to spi_controller device
2010aff5e3f8SPantelis Antoniou  *
20116c364062SGeert Uytterhoeven  * Registers an spi_device for each child node of controller node which
20126c364062SGeert Uytterhoeven  * represents a valid SPI slave.
2013aff5e3f8SPantelis Antoniou  */
20148caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr)
2015aff5e3f8SPantelis Antoniou {
2016aff5e3f8SPantelis Antoniou 	struct spi_device *spi;
2017aff5e3f8SPantelis Antoniou 	struct device_node *nc;
2018aff5e3f8SPantelis Antoniou 
20198caab75fSGeert Uytterhoeven 	if (!ctlr->dev.of_node)
2020aff5e3f8SPantelis Antoniou 		return;
2021aff5e3f8SPantelis Antoniou 
20228caab75fSGeert Uytterhoeven 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2023bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2024bd6c1644SGeert Uytterhoeven 			continue;
20258caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, nc);
2026e0af98a7SRalf Ramsauer 		if (IS_ERR(spi)) {
20278caab75fSGeert Uytterhoeven 			dev_warn(&ctlr->dev,
202825c56c88SRob Herring 				 "Failed to create SPI device for %pOF\n", nc);
2029e0af98a7SRalf Ramsauer 			of_node_clear_flag(nc, OF_POPULATED);
2030e0af98a7SRalf Ramsauer 		}
2031d57a4282SGrant Likely 	}
2032d57a4282SGrant Likely }
2033d57a4282SGrant Likely #else
20348caab75fSGeert Uytterhoeven static void of_register_spi_devices(struct spi_controller *ctlr) { }
2035d57a4282SGrant Likely #endif
2036d57a4282SGrant Likely 
203764bee4d2SMika Westerberg #ifdef CONFIG_ACPI
20384c3c5954SArd Biesheuvel struct acpi_spi_lookup {
20394c3c5954SArd Biesheuvel 	struct spi_controller 	*ctlr;
20404c3c5954SArd Biesheuvel 	u32			max_speed_hz;
20414c3c5954SArd Biesheuvel 	u32			mode;
20424c3c5954SArd Biesheuvel 	int			irq;
20434c3c5954SArd Biesheuvel 	u8			bits_per_word;
20444c3c5954SArd Biesheuvel 	u8			chip_select;
20454c3c5954SArd Biesheuvel };
20464c3c5954SArd Biesheuvel 
20474c3c5954SArd Biesheuvel static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
20484c3c5954SArd Biesheuvel 					    struct acpi_spi_lookup *lookup)
20498a2e487eSLukas Wunner {
20508a2e487eSLukas Wunner 	const union acpi_object *obj;
20518a2e487eSLukas Wunner 
20528a2e487eSLukas Wunner 	if (!x86_apple_machine)
20538a2e487eSLukas Wunner 		return;
20548a2e487eSLukas Wunner 
20558a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
20568a2e487eSLukas Wunner 	    && obj->buffer.length >= 4)
20574c3c5954SArd Biesheuvel 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
20588a2e487eSLukas Wunner 
20598a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
20608a2e487eSLukas Wunner 	    && obj->buffer.length == 8)
20614c3c5954SArd Biesheuvel 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
20628a2e487eSLukas Wunner 
20638a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
20648a2e487eSLukas Wunner 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
20654c3c5954SArd Biesheuvel 		lookup->mode |= SPI_LSB_FIRST;
20668a2e487eSLukas Wunner 
20678a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
20688a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
20694c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPOL;
20708a2e487eSLukas Wunner 
20718a2e487eSLukas Wunner 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
20728a2e487eSLukas Wunner 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
20734c3c5954SArd Biesheuvel 		lookup->mode |= SPI_CPHA;
20748a2e487eSLukas Wunner }
20758a2e487eSLukas Wunner 
207664bee4d2SMika Westerberg static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
207764bee4d2SMika Westerberg {
20784c3c5954SArd Biesheuvel 	struct acpi_spi_lookup *lookup = data;
20794c3c5954SArd Biesheuvel 	struct spi_controller *ctlr = lookup->ctlr;
208064bee4d2SMika Westerberg 
208164bee4d2SMika Westerberg 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
208264bee4d2SMika Westerberg 		struct acpi_resource_spi_serialbus *sb;
20834c3c5954SArd Biesheuvel 		acpi_handle parent_handle;
20844c3c5954SArd Biesheuvel 		acpi_status status;
208564bee4d2SMika Westerberg 
208664bee4d2SMika Westerberg 		sb = &ares->data.spi_serial_bus;
208764bee4d2SMika Westerberg 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
20884c3c5954SArd Biesheuvel 
20894c3c5954SArd Biesheuvel 			status = acpi_get_handle(NULL,
20904c3c5954SArd Biesheuvel 						 sb->resource_source.string_ptr,
20914c3c5954SArd Biesheuvel 						 &parent_handle);
20924c3c5954SArd Biesheuvel 
2093b5e3cf41SArd Biesheuvel 			if (ACPI_FAILURE(status) ||
20944c3c5954SArd Biesheuvel 			    ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
20954c3c5954SArd Biesheuvel 				return -ENODEV;
20964c3c5954SArd Biesheuvel 
2097a0a90718SMika Westerberg 			/*
2098a0a90718SMika Westerberg 			 * ACPI DeviceSelection numbering is handled by the
2099a0a90718SMika Westerberg 			 * host controller driver in Windows and can vary
2100a0a90718SMika Westerberg 			 * from driver to driver. In Linux we always expect
2101a0a90718SMika Westerberg 			 * 0 .. max - 1 so we need to ask the driver to
2102a0a90718SMika Westerberg 			 * translate between the two schemes.
2103a0a90718SMika Westerberg 			 */
21048caab75fSGeert Uytterhoeven 			if (ctlr->fw_translate_cs) {
21058caab75fSGeert Uytterhoeven 				int cs = ctlr->fw_translate_cs(ctlr,
2106a0a90718SMika Westerberg 						sb->device_selection);
2107a0a90718SMika Westerberg 				if (cs < 0)
2108a0a90718SMika Westerberg 					return cs;
21094c3c5954SArd Biesheuvel 				lookup->chip_select = cs;
2110a0a90718SMika Westerberg 			} else {
21114c3c5954SArd Biesheuvel 				lookup->chip_select = sb->device_selection;
2112a0a90718SMika Westerberg 			}
2113a0a90718SMika Westerberg 
21144c3c5954SArd Biesheuvel 			lookup->max_speed_hz = sb->connection_speed;
211564bee4d2SMika Westerberg 
211664bee4d2SMika Westerberg 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
21174c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPHA;
211864bee4d2SMika Westerberg 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
21194c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CPOL;
212064bee4d2SMika Westerberg 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
21214c3c5954SArd Biesheuvel 				lookup->mode |= SPI_CS_HIGH;
212264bee4d2SMika Westerberg 		}
21234c3c5954SArd Biesheuvel 	} else if (lookup->irq < 0) {
212464bee4d2SMika Westerberg 		struct resource r;
212564bee4d2SMika Westerberg 
212664bee4d2SMika Westerberg 		if (acpi_dev_resource_interrupt(ares, 0, &r))
21274c3c5954SArd Biesheuvel 			lookup->irq = r.start;
212864bee4d2SMika Westerberg 	}
212964bee4d2SMika Westerberg 
213064bee4d2SMika Westerberg 	/* Always tell the ACPI core to skip this resource */
213164bee4d2SMika Westerberg 	return 1;
213264bee4d2SMika Westerberg }
213364bee4d2SMika Westerberg 
21348caab75fSGeert Uytterhoeven static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
21357f24467fSOctavian Purdila 					    struct acpi_device *adev)
213664bee4d2SMika Westerberg {
21374c3c5954SArd Biesheuvel 	acpi_handle parent_handle = NULL;
213864bee4d2SMika Westerberg 	struct list_head resource_list;
2139b28944c6SArd Biesheuvel 	struct acpi_spi_lookup lookup = {};
214064bee4d2SMika Westerberg 	struct spi_device *spi;
214164bee4d2SMika Westerberg 	int ret;
214264bee4d2SMika Westerberg 
21437f24467fSOctavian Purdila 	if (acpi_bus_get_status(adev) || !adev->status.present ||
21447f24467fSOctavian Purdila 	    acpi_device_enumerated(adev))
214564bee4d2SMika Westerberg 		return AE_OK;
214664bee4d2SMika Westerberg 
21474c3c5954SArd Biesheuvel 	lookup.ctlr		= ctlr;
21484c3c5954SArd Biesheuvel 	lookup.irq		= -1;
21494c3c5954SArd Biesheuvel 
21504c3c5954SArd Biesheuvel 	INIT_LIST_HEAD(&resource_list);
21514c3c5954SArd Biesheuvel 	ret = acpi_dev_get_resources(adev, &resource_list,
21524c3c5954SArd Biesheuvel 				     acpi_spi_add_resource, &lookup);
21534c3c5954SArd Biesheuvel 	acpi_dev_free_resource_list(&resource_list);
21544c3c5954SArd Biesheuvel 
21554c3c5954SArd Biesheuvel 	if (ret < 0)
21564c3c5954SArd Biesheuvel 		/* found SPI in _CRS but it points to another controller */
21574c3c5954SArd Biesheuvel 		return AE_OK;
21584c3c5954SArd Biesheuvel 
21594c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz &&
21604c3c5954SArd Biesheuvel 	    !ACPI_FAILURE(acpi_get_parent(adev->handle, &parent_handle)) &&
21614c3c5954SArd Biesheuvel 	    ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
21624c3c5954SArd Biesheuvel 		/* Apple does not use _CRS but nested devices for SPI slaves */
21634c3c5954SArd Biesheuvel 		acpi_spi_parse_apple_properties(adev, &lookup);
21644c3c5954SArd Biesheuvel 	}
21654c3c5954SArd Biesheuvel 
21664c3c5954SArd Biesheuvel 	if (!lookup.max_speed_hz)
21674c3c5954SArd Biesheuvel 		return AE_OK;
21684c3c5954SArd Biesheuvel 
21698caab75fSGeert Uytterhoeven 	spi = spi_alloc_device(ctlr);
217064bee4d2SMika Westerberg 	if (!spi) {
21718caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
217264bee4d2SMika Westerberg 			dev_name(&adev->dev));
217364bee4d2SMika Westerberg 		return AE_NO_MEMORY;
217464bee4d2SMika Westerberg 	}
217564bee4d2SMika Westerberg 
21767b199811SRafael J. Wysocki 	ACPI_COMPANION_SET(&spi->dev, adev);
21774c3c5954SArd Biesheuvel 	spi->max_speed_hz	= lookup.max_speed_hz;
21784c3c5954SArd Biesheuvel 	spi->mode		= lookup.mode;
21794c3c5954SArd Biesheuvel 	spi->irq		= lookup.irq;
21804c3c5954SArd Biesheuvel 	spi->bits_per_word	= lookup.bits_per_word;
21814c3c5954SArd Biesheuvel 	spi->chip_select	= lookup.chip_select;
218264bee4d2SMika Westerberg 
21830c6543f6SDan O'Donovan 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
21840c6543f6SDan O'Donovan 			  sizeof(spi->modalias));
21850c6543f6SDan O'Donovan 
218633ada67dSChristophe RICARD 	if (spi->irq < 0)
218733ada67dSChristophe RICARD 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
218833ada67dSChristophe RICARD 
21897f24467fSOctavian Purdila 	acpi_device_set_enumerated(adev);
21907f24467fSOctavian Purdila 
219133cf00e5SMika Westerberg 	adev->power.flags.ignore_parent = true;
219264bee4d2SMika Westerberg 	if (spi_add_device(spi)) {
219333cf00e5SMika Westerberg 		adev->power.flags.ignore_parent = false;
21948caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
219564bee4d2SMika Westerberg 			dev_name(&adev->dev));
219664bee4d2SMika Westerberg 		spi_dev_put(spi);
219764bee4d2SMika Westerberg 	}
219864bee4d2SMika Westerberg 
219964bee4d2SMika Westerberg 	return AE_OK;
220064bee4d2SMika Westerberg }
220164bee4d2SMika Westerberg 
22027f24467fSOctavian Purdila static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
22037f24467fSOctavian Purdila 				       void *data, void **return_value)
22047f24467fSOctavian Purdila {
22058caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = data;
22067f24467fSOctavian Purdila 	struct acpi_device *adev;
22077f24467fSOctavian Purdila 
22087f24467fSOctavian Purdila 	if (acpi_bus_get_device(handle, &adev))
22097f24467fSOctavian Purdila 		return AE_OK;
22107f24467fSOctavian Purdila 
22118caab75fSGeert Uytterhoeven 	return acpi_register_spi_device(ctlr, adev);
22127f24467fSOctavian Purdila }
22137f24467fSOctavian Purdila 
22144c3c5954SArd Biesheuvel #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
22154c3c5954SArd Biesheuvel 
22168caab75fSGeert Uytterhoeven static void acpi_register_spi_devices(struct spi_controller *ctlr)
221764bee4d2SMika Westerberg {
221864bee4d2SMika Westerberg 	acpi_status status;
221964bee4d2SMika Westerberg 	acpi_handle handle;
222064bee4d2SMika Westerberg 
22218caab75fSGeert Uytterhoeven 	handle = ACPI_HANDLE(ctlr->dev.parent);
222264bee4d2SMika Westerberg 	if (!handle)
222364bee4d2SMika Westerberg 		return;
222464bee4d2SMika Westerberg 
22254c3c5954SArd Biesheuvel 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
22264c3c5954SArd Biesheuvel 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
22278caab75fSGeert Uytterhoeven 				     acpi_spi_add_device, NULL, ctlr, NULL);
222864bee4d2SMika Westerberg 	if (ACPI_FAILURE(status))
22298caab75fSGeert Uytterhoeven 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
223064bee4d2SMika Westerberg }
223164bee4d2SMika Westerberg #else
22328caab75fSGeert Uytterhoeven static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
223364bee4d2SMika Westerberg #endif /* CONFIG_ACPI */
223464bee4d2SMika Westerberg 
22358caab75fSGeert Uytterhoeven static void spi_controller_release(struct device *dev)
22368ae12a0dSDavid Brownell {
22378caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
22388ae12a0dSDavid Brownell 
22398caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
22408caab75fSGeert Uytterhoeven 	kfree(ctlr);
22418ae12a0dSDavid Brownell }
22428ae12a0dSDavid Brownell 
22438ae12a0dSDavid Brownell static struct class spi_master_class = {
22448ae12a0dSDavid Brownell 	.name		= "spi_master",
22458ae12a0dSDavid Brownell 	.owner		= THIS_MODULE,
22468caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
2247eca2ebc7SMartin Sperl 	.dev_groups	= spi_master_groups,
22488ae12a0dSDavid Brownell };
22498ae12a0dSDavid Brownell 
22506c364062SGeert Uytterhoeven #ifdef CONFIG_SPI_SLAVE
22516c364062SGeert Uytterhoeven /**
22526c364062SGeert Uytterhoeven  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
22536c364062SGeert Uytterhoeven  *		     controller
22546c364062SGeert Uytterhoeven  * @spi: device used for the current transfer
22556c364062SGeert Uytterhoeven  */
22566c364062SGeert Uytterhoeven int spi_slave_abort(struct spi_device *spi)
22576c364062SGeert Uytterhoeven {
22588caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
22596c364062SGeert Uytterhoeven 
22608caab75fSGeert Uytterhoeven 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
22618caab75fSGeert Uytterhoeven 		return ctlr->slave_abort(ctlr);
22626c364062SGeert Uytterhoeven 
22636c364062SGeert Uytterhoeven 	return -ENOTSUPP;
22646c364062SGeert Uytterhoeven }
22656c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_slave_abort);
22666c364062SGeert Uytterhoeven 
22676c364062SGeert Uytterhoeven static int match_true(struct device *dev, void *data)
22686c364062SGeert Uytterhoeven {
22696c364062SGeert Uytterhoeven 	return 1;
22706c364062SGeert Uytterhoeven }
22716c364062SGeert Uytterhoeven 
2272cc8b4659SGeert Uytterhoeven static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2273cc8b4659SGeert Uytterhoeven 			  char *buf)
22746c364062SGeert Uytterhoeven {
22758caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
22768caab75fSGeert Uytterhoeven 						   dev);
22776c364062SGeert Uytterhoeven 	struct device *child;
22786c364062SGeert Uytterhoeven 
22796c364062SGeert Uytterhoeven 	child = device_find_child(&ctlr->dev, NULL, match_true);
22806c364062SGeert Uytterhoeven 	return sprintf(buf, "%s\n",
22816c364062SGeert Uytterhoeven 		       child ? to_spi_device(child)->modalias : NULL);
22826c364062SGeert Uytterhoeven }
22836c364062SGeert Uytterhoeven 
2284cc8b4659SGeert Uytterhoeven static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2285cc8b4659SGeert Uytterhoeven 			   const char *buf, size_t count)
22866c364062SGeert Uytterhoeven {
22878caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
22888caab75fSGeert Uytterhoeven 						   dev);
22896c364062SGeert Uytterhoeven 	struct spi_device *spi;
22906c364062SGeert Uytterhoeven 	struct device *child;
22916c364062SGeert Uytterhoeven 	char name[32];
22926c364062SGeert Uytterhoeven 	int rc;
22936c364062SGeert Uytterhoeven 
22946c364062SGeert Uytterhoeven 	rc = sscanf(buf, "%31s", name);
22956c364062SGeert Uytterhoeven 	if (rc != 1 || !name[0])
22966c364062SGeert Uytterhoeven 		return -EINVAL;
22976c364062SGeert Uytterhoeven 
22986c364062SGeert Uytterhoeven 	child = device_find_child(&ctlr->dev, NULL, match_true);
22996c364062SGeert Uytterhoeven 	if (child) {
23006c364062SGeert Uytterhoeven 		/* Remove registered slave */
23016c364062SGeert Uytterhoeven 		device_unregister(child);
23026c364062SGeert Uytterhoeven 		put_device(child);
23036c364062SGeert Uytterhoeven 	}
23046c364062SGeert Uytterhoeven 
23056c364062SGeert Uytterhoeven 	if (strcmp(name, "(null)")) {
23066c364062SGeert Uytterhoeven 		/* Register new slave */
23076c364062SGeert Uytterhoeven 		spi = spi_alloc_device(ctlr);
23086c364062SGeert Uytterhoeven 		if (!spi)
23096c364062SGeert Uytterhoeven 			return -ENOMEM;
23106c364062SGeert Uytterhoeven 
23116c364062SGeert Uytterhoeven 		strlcpy(spi->modalias, name, sizeof(spi->modalias));
23126c364062SGeert Uytterhoeven 
23136c364062SGeert Uytterhoeven 		rc = spi_add_device(spi);
23146c364062SGeert Uytterhoeven 		if (rc) {
23156c364062SGeert Uytterhoeven 			spi_dev_put(spi);
23166c364062SGeert Uytterhoeven 			return rc;
23176c364062SGeert Uytterhoeven 		}
23186c364062SGeert Uytterhoeven 	}
23196c364062SGeert Uytterhoeven 
23206c364062SGeert Uytterhoeven 	return count;
23216c364062SGeert Uytterhoeven }
23226c364062SGeert Uytterhoeven 
2323cc8b4659SGeert Uytterhoeven static DEVICE_ATTR_RW(slave);
23246c364062SGeert Uytterhoeven 
23256c364062SGeert Uytterhoeven static struct attribute *spi_slave_attrs[] = {
23266c364062SGeert Uytterhoeven 	&dev_attr_slave.attr,
23276c364062SGeert Uytterhoeven 	NULL,
23286c364062SGeert Uytterhoeven };
23296c364062SGeert Uytterhoeven 
23306c364062SGeert Uytterhoeven static const struct attribute_group spi_slave_group = {
23316c364062SGeert Uytterhoeven 	.attrs = spi_slave_attrs,
23326c364062SGeert Uytterhoeven };
23336c364062SGeert Uytterhoeven 
23346c364062SGeert Uytterhoeven static const struct attribute_group *spi_slave_groups[] = {
23358caab75fSGeert Uytterhoeven 	&spi_controller_statistics_group,
23366c364062SGeert Uytterhoeven 	&spi_slave_group,
23376c364062SGeert Uytterhoeven 	NULL,
23386c364062SGeert Uytterhoeven };
23396c364062SGeert Uytterhoeven 
23406c364062SGeert Uytterhoeven static struct class spi_slave_class = {
23416c364062SGeert Uytterhoeven 	.name		= "spi_slave",
23426c364062SGeert Uytterhoeven 	.owner		= THIS_MODULE,
23438caab75fSGeert Uytterhoeven 	.dev_release	= spi_controller_release,
23446c364062SGeert Uytterhoeven 	.dev_groups	= spi_slave_groups,
23456c364062SGeert Uytterhoeven };
23466c364062SGeert Uytterhoeven #else
23476c364062SGeert Uytterhoeven extern struct class spi_slave_class;	/* dummy */
23486c364062SGeert Uytterhoeven #endif
23498ae12a0dSDavid Brownell 
23508ae12a0dSDavid Brownell /**
23516c364062SGeert Uytterhoeven  * __spi_alloc_controller - allocate an SPI master or slave controller
23528ae12a0dSDavid Brownell  * @dev: the controller, possibly using the platform_bus
235333e34dc6SDavid Brownell  * @size: how much zeroed driver-private data to allocate; the pointer to this
2354229e6af1SLukas Wunner  *	memory is in the driver_data field of the returned device, accessible
2355229e6af1SLukas Wunner  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2356229e6af1SLukas Wunner  *	drivers granting DMA access to portions of their private data need to
2357229e6af1SLukas Wunner  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
23586c364062SGeert Uytterhoeven  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
23596c364062SGeert Uytterhoeven  *	slave (true) controller
236033e34dc6SDavid Brownell  * Context: can sleep
23618ae12a0dSDavid Brownell  *
23626c364062SGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
23638ae12a0dSDavid Brownell  * only ones directly touching chip registers.  It's how they allocate
23648caab75fSGeert Uytterhoeven  * an spi_controller structure, prior to calling spi_register_controller().
23658ae12a0dSDavid Brownell  *
236697d56dc6SJavier Martinez Canillas  * This must be called from context that can sleep.
23678ae12a0dSDavid Brownell  *
23686c364062SGeert Uytterhoeven  * The caller is responsible for assigning the bus number and initializing the
23698caab75fSGeert Uytterhoeven  * controller's methods before calling spi_register_controller(); and (after
23708caab75fSGeert Uytterhoeven  * errors adding the device) calling spi_controller_put() to prevent a memory
23718caab75fSGeert Uytterhoeven  * leak.
237297d56dc6SJavier Martinez Canillas  *
23736c364062SGeert Uytterhoeven  * Return: the SPI controller structure on success, else NULL.
23748ae12a0dSDavid Brownell  */
23758caab75fSGeert Uytterhoeven struct spi_controller *__spi_alloc_controller(struct device *dev,
23766c364062SGeert Uytterhoeven 					      unsigned int size, bool slave)
23778ae12a0dSDavid Brownell {
23788caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr;
2379229e6af1SLukas Wunner 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
23808ae12a0dSDavid Brownell 
23810c868461SDavid Brownell 	if (!dev)
23820c868461SDavid Brownell 		return NULL;
23830c868461SDavid Brownell 
2384229e6af1SLukas Wunner 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
23858caab75fSGeert Uytterhoeven 	if (!ctlr)
23868ae12a0dSDavid Brownell 		return NULL;
23878ae12a0dSDavid Brownell 
23888caab75fSGeert Uytterhoeven 	device_initialize(&ctlr->dev);
23898caab75fSGeert Uytterhoeven 	ctlr->bus_num = -1;
23908caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = 1;
23918caab75fSGeert Uytterhoeven 	ctlr->slave = slave;
23926c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
23938caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_slave_class;
23946c364062SGeert Uytterhoeven 	else
23958caab75fSGeert Uytterhoeven 		ctlr->dev.class = &spi_master_class;
23968caab75fSGeert Uytterhoeven 	ctlr->dev.parent = dev;
23978caab75fSGeert Uytterhoeven 	pm_suspend_ignore_children(&ctlr->dev, true);
2398229e6af1SLukas Wunner 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
23998ae12a0dSDavid Brownell 
24008caab75fSGeert Uytterhoeven 	return ctlr;
24018ae12a0dSDavid Brownell }
24026c364062SGeert Uytterhoeven EXPORT_SYMBOL_GPL(__spi_alloc_controller);
24038ae12a0dSDavid Brownell 
240474317984SJean-Christophe PLAGNIOL-VILLARD #ifdef CONFIG_OF
240543004f31SLinus Walleij static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
240674317984SJean-Christophe PLAGNIOL-VILLARD {
2407e80beb27SGrant Likely 	int nb, i, *cs;
24088caab75fSGeert Uytterhoeven 	struct device_node *np = ctlr->dev.of_node;
240974317984SJean-Christophe PLAGNIOL-VILLARD 
241074317984SJean-Christophe PLAGNIOL-VILLARD 	if (!np)
241174317984SJean-Christophe PLAGNIOL-VILLARD 		return 0;
241274317984SJean-Christophe PLAGNIOL-VILLARD 
241374317984SJean-Christophe PLAGNIOL-VILLARD 	nb = of_gpio_named_count(np, "cs-gpios");
24148caab75fSGeert Uytterhoeven 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
241574317984SJean-Christophe PLAGNIOL-VILLARD 
24168ec5d84eSAndreas Larsson 	/* Return error only for an incorrectly formed cs-gpios property */
24178ec5d84eSAndreas Larsson 	if (nb == 0 || nb == -ENOENT)
241874317984SJean-Christophe PLAGNIOL-VILLARD 		return 0;
24198ec5d84eSAndreas Larsson 	else if (nb < 0)
24208ec5d84eSAndreas Larsson 		return nb;
242174317984SJean-Christophe PLAGNIOL-VILLARD 
2422a86854d0SKees Cook 	cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
242374317984SJean-Christophe PLAGNIOL-VILLARD 			  GFP_KERNEL);
24248caab75fSGeert Uytterhoeven 	ctlr->cs_gpios = cs;
242574317984SJean-Christophe PLAGNIOL-VILLARD 
24268caab75fSGeert Uytterhoeven 	if (!ctlr->cs_gpios)
242774317984SJean-Christophe PLAGNIOL-VILLARD 		return -ENOMEM;
242874317984SJean-Christophe PLAGNIOL-VILLARD 
24298caab75fSGeert Uytterhoeven 	for (i = 0; i < ctlr->num_chipselect; i++)
2430446411e1SAndreas Larsson 		cs[i] = -ENOENT;
243174317984SJean-Christophe PLAGNIOL-VILLARD 
243274317984SJean-Christophe PLAGNIOL-VILLARD 	for (i = 0; i < nb; i++)
243374317984SJean-Christophe PLAGNIOL-VILLARD 		cs[i] = of_get_named_gpio(np, "cs-gpios", i);
243474317984SJean-Christophe PLAGNIOL-VILLARD 
243574317984SJean-Christophe PLAGNIOL-VILLARD 	return 0;
243674317984SJean-Christophe PLAGNIOL-VILLARD }
243774317984SJean-Christophe PLAGNIOL-VILLARD #else
243843004f31SLinus Walleij static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
243974317984SJean-Christophe PLAGNIOL-VILLARD {
244074317984SJean-Christophe PLAGNIOL-VILLARD 	return 0;
244174317984SJean-Christophe PLAGNIOL-VILLARD }
244274317984SJean-Christophe PLAGNIOL-VILLARD #endif
244374317984SJean-Christophe PLAGNIOL-VILLARD 
2444f3186dd8SLinus Walleij /**
2445f3186dd8SLinus Walleij  * spi_get_gpio_descs() - grab chip select GPIOs for the master
2446f3186dd8SLinus Walleij  * @ctlr: The SPI master to grab GPIO descriptors for
2447f3186dd8SLinus Walleij  */
2448f3186dd8SLinus Walleij static int spi_get_gpio_descs(struct spi_controller *ctlr)
2449f3186dd8SLinus Walleij {
2450f3186dd8SLinus Walleij 	int nb, i;
2451f3186dd8SLinus Walleij 	struct gpio_desc **cs;
2452f3186dd8SLinus Walleij 	struct device *dev = &ctlr->dev;
2453f3186dd8SLinus Walleij 
2454f3186dd8SLinus Walleij 	nb = gpiod_count(dev, "cs");
2455f3186dd8SLinus Walleij 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2456f3186dd8SLinus Walleij 
2457f3186dd8SLinus Walleij 	/* No GPIOs at all is fine, else return the error */
2458f3186dd8SLinus Walleij 	if (nb == 0 || nb == -ENOENT)
2459f3186dd8SLinus Walleij 		return 0;
2460f3186dd8SLinus Walleij 	else if (nb < 0)
2461f3186dd8SLinus Walleij 		return nb;
2462f3186dd8SLinus Walleij 
2463f3186dd8SLinus Walleij 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2464f3186dd8SLinus Walleij 			  GFP_KERNEL);
2465f3186dd8SLinus Walleij 	if (!cs)
2466f3186dd8SLinus Walleij 		return -ENOMEM;
2467f3186dd8SLinus Walleij 	ctlr->cs_gpiods = cs;
2468f3186dd8SLinus Walleij 
2469f3186dd8SLinus Walleij 	for (i = 0; i < nb; i++) {
2470f3186dd8SLinus Walleij 		/*
2471f3186dd8SLinus Walleij 		 * Most chipselects are active low, the inverted
2472f3186dd8SLinus Walleij 		 * semantics are handled by special quirks in gpiolib,
2473f3186dd8SLinus Walleij 		 * so initializing them GPIOD_OUT_LOW here means
2474f3186dd8SLinus Walleij 		 * "unasserted", in most cases this will drive the physical
2475f3186dd8SLinus Walleij 		 * line high.
2476f3186dd8SLinus Walleij 		 */
2477f3186dd8SLinus Walleij 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2478f3186dd8SLinus Walleij 						      GPIOD_OUT_LOW);
24791723fdecSGeert Uytterhoeven 		if (IS_ERR(cs[i]))
24801723fdecSGeert Uytterhoeven 			return PTR_ERR(cs[i]);
2481f3186dd8SLinus Walleij 
2482f3186dd8SLinus Walleij 		if (cs[i]) {
2483f3186dd8SLinus Walleij 			/*
2484f3186dd8SLinus Walleij 			 * If we find a CS GPIO, name it after the device and
2485f3186dd8SLinus Walleij 			 * chip select line.
2486f3186dd8SLinus Walleij 			 */
2487f3186dd8SLinus Walleij 			char *gpioname;
2488f3186dd8SLinus Walleij 
2489f3186dd8SLinus Walleij 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2490f3186dd8SLinus Walleij 						  dev_name(dev), i);
2491f3186dd8SLinus Walleij 			if (!gpioname)
2492f3186dd8SLinus Walleij 				return -ENOMEM;
2493f3186dd8SLinus Walleij 			gpiod_set_consumer_name(cs[i], gpioname);
2494f3186dd8SLinus Walleij 		}
2495f3186dd8SLinus Walleij 	}
2496f3186dd8SLinus Walleij 
2497f3186dd8SLinus Walleij 	return 0;
2498f3186dd8SLinus Walleij }
2499f3186dd8SLinus Walleij 
2500bdf3a3b5SBoris Brezillon static int spi_controller_check_ops(struct spi_controller *ctlr)
2501bdf3a3b5SBoris Brezillon {
2502bdf3a3b5SBoris Brezillon 	/*
2503b5932f5cSBoris Brezillon 	 * The controller may implement only the high-level SPI-memory like
2504b5932f5cSBoris Brezillon 	 * operations if it does not support regular SPI transfers, and this is
2505b5932f5cSBoris Brezillon 	 * valid use case.
2506b5932f5cSBoris Brezillon 	 * If ->mem_ops is NULL, we request that at least one of the
2507b5932f5cSBoris Brezillon 	 * ->transfer_xxx() method be implemented.
2508bdf3a3b5SBoris Brezillon 	 */
2509b5932f5cSBoris Brezillon 	if (ctlr->mem_ops) {
2510b5932f5cSBoris Brezillon 		if (!ctlr->mem_ops->exec_op)
2511bdf3a3b5SBoris Brezillon 			return -EINVAL;
2512b5932f5cSBoris Brezillon 	} else if (!ctlr->transfer && !ctlr->transfer_one &&
2513b5932f5cSBoris Brezillon 		   !ctlr->transfer_one_message) {
2514b5932f5cSBoris Brezillon 		return -EINVAL;
2515b5932f5cSBoris Brezillon 	}
2516bdf3a3b5SBoris Brezillon 
2517bdf3a3b5SBoris Brezillon 	return 0;
2518bdf3a3b5SBoris Brezillon }
2519bdf3a3b5SBoris Brezillon 
25208ae12a0dSDavid Brownell /**
25218caab75fSGeert Uytterhoeven  * spi_register_controller - register SPI master or slave controller
25228caab75fSGeert Uytterhoeven  * @ctlr: initialized master, originally from spi_alloc_master() or
25238caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
252433e34dc6SDavid Brownell  * Context: can sleep
25258ae12a0dSDavid Brownell  *
25268caab75fSGeert Uytterhoeven  * SPI controllers connect to their drivers using some non-SPI bus,
25278ae12a0dSDavid Brownell  * such as the platform bus.  The final stage of probe() in that code
25288caab75fSGeert Uytterhoeven  * includes calling spi_register_controller() to hook up to this SPI bus glue.
25298ae12a0dSDavid Brownell  *
25308ae12a0dSDavid Brownell  * SPI controllers use board specific (often SOC specific) bus numbers,
25318ae12a0dSDavid Brownell  * and board-specific addressing for SPI devices combines those numbers
25328ae12a0dSDavid Brownell  * with chip select numbers.  Since SPI does not directly support dynamic
25338ae12a0dSDavid Brownell  * device identification, boards need configuration tables telling which
25348ae12a0dSDavid Brownell  * chip is at which address.
25358ae12a0dSDavid Brownell  *
25368ae12a0dSDavid Brownell  * This must be called from context that can sleep.  It returns zero on
25378caab75fSGeert Uytterhoeven  * success, else a negative error code (dropping the controller's refcount).
25380c868461SDavid Brownell  * After a successful return, the caller is responsible for calling
25398caab75fSGeert Uytterhoeven  * spi_unregister_controller().
254097d56dc6SJavier Martinez Canillas  *
254197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
25428ae12a0dSDavid Brownell  */
25438caab75fSGeert Uytterhoeven int spi_register_controller(struct spi_controller *ctlr)
25448ae12a0dSDavid Brownell {
25458caab75fSGeert Uytterhoeven 	struct device		*dev = ctlr->dev.parent;
25462b9603a0SFeng Tang 	struct boardinfo	*bi;
2547b93318a2SSergei Shtylyov 	int			status;
254842bdd706SLucas Stach 	int			id, first_dynamic;
25498ae12a0dSDavid Brownell 
25500c868461SDavid Brownell 	if (!dev)
25510c868461SDavid Brownell 		return -ENODEV;
25520c868461SDavid Brownell 
2553bdf3a3b5SBoris Brezillon 	/*
2554bdf3a3b5SBoris Brezillon 	 * Make sure all necessary hooks are implemented before registering
2555bdf3a3b5SBoris Brezillon 	 * the SPI controller.
2556bdf3a3b5SBoris Brezillon 	 */
2557bdf3a3b5SBoris Brezillon 	status = spi_controller_check_ops(ctlr);
2558bdf3a3b5SBoris Brezillon 	if (status)
2559bdf3a3b5SBoris Brezillon 		return status;
2560bdf3a3b5SBoris Brezillon 
256104b2d03aSGeert Uytterhoeven 	if (ctlr->bus_num >= 0) {
256204b2d03aSGeert Uytterhoeven 		/* devices with a fixed bus num must check-in with the num */
256304b2d03aSGeert Uytterhoeven 		mutex_lock(&board_lock);
256404b2d03aSGeert Uytterhoeven 		id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
256504b2d03aSGeert Uytterhoeven 			ctlr->bus_num + 1, GFP_KERNEL);
256604b2d03aSGeert Uytterhoeven 		mutex_unlock(&board_lock);
256704b2d03aSGeert Uytterhoeven 		if (WARN(id < 0, "couldn't get idr"))
256804b2d03aSGeert Uytterhoeven 			return id == -ENOSPC ? -EBUSY : id;
256904b2d03aSGeert Uytterhoeven 		ctlr->bus_num = id;
257004b2d03aSGeert Uytterhoeven 	} else if (ctlr->dev.of_node) {
25719b61e302SSuniel Mahesh 		/* allocate dynamic bus number using Linux idr */
25729b61e302SSuniel Mahesh 		id = of_alias_get_id(ctlr->dev.of_node, "spi");
25739b61e302SSuniel Mahesh 		if (id >= 0) {
25749b61e302SSuniel Mahesh 			ctlr->bus_num = id;
25759b61e302SSuniel Mahesh 			mutex_lock(&board_lock);
25769b61e302SSuniel Mahesh 			id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
25779b61e302SSuniel Mahesh 				       ctlr->bus_num + 1, GFP_KERNEL);
25789b61e302SSuniel Mahesh 			mutex_unlock(&board_lock);
25799b61e302SSuniel Mahesh 			if (WARN(id < 0, "couldn't get idr"))
25809b61e302SSuniel Mahesh 				return id == -ENOSPC ? -EBUSY : id;
25819b61e302SSuniel Mahesh 		}
25829b61e302SSuniel Mahesh 	}
25838caab75fSGeert Uytterhoeven 	if (ctlr->bus_num < 0) {
258442bdd706SLucas Stach 		first_dynamic = of_alias_get_highest_id("spi");
258542bdd706SLucas Stach 		if (first_dynamic < 0)
258642bdd706SLucas Stach 			first_dynamic = 0;
258742bdd706SLucas Stach 		else
258842bdd706SLucas Stach 			first_dynamic++;
258942bdd706SLucas Stach 
25909b61e302SSuniel Mahesh 		mutex_lock(&board_lock);
259142bdd706SLucas Stach 		id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
259242bdd706SLucas Stach 			       0, GFP_KERNEL);
25939b61e302SSuniel Mahesh 		mutex_unlock(&board_lock);
25949b61e302SSuniel Mahesh 		if (WARN(id < 0, "couldn't get idr"))
25959b61e302SSuniel Mahesh 			return id;
25969b61e302SSuniel Mahesh 		ctlr->bus_num = id;
25978ae12a0dSDavid Brownell 	}
25988caab75fSGeert Uytterhoeven 	INIT_LIST_HEAD(&ctlr->queue);
25998caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->queue_lock);
26008caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->bus_lock_spinlock);
26018caab75fSGeert Uytterhoeven 	mutex_init(&ctlr->bus_lock_mutex);
26028caab75fSGeert Uytterhoeven 	mutex_init(&ctlr->io_mutex);
26038caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
26048caab75fSGeert Uytterhoeven 	init_completion(&ctlr->xfer_completion);
26058caab75fSGeert Uytterhoeven 	if (!ctlr->max_dma_len)
26068caab75fSGeert Uytterhoeven 		ctlr->max_dma_len = INT_MAX;
2607cf32b71eSErnst Schwab 
26088ae12a0dSDavid Brownell 	/* register the device, then userspace will see it.
26098ae12a0dSDavid Brownell 	 * registration fails if the bus ID is in use.
26108ae12a0dSDavid Brownell 	 */
26118caab75fSGeert Uytterhoeven 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
26120a919ae4SAndrey Smirnov 
26130a919ae4SAndrey Smirnov 	if (!spi_controller_is_slave(ctlr)) {
26140a919ae4SAndrey Smirnov 		if (ctlr->use_gpio_descriptors) {
26150a919ae4SAndrey Smirnov 			status = spi_get_gpio_descs(ctlr);
26160a919ae4SAndrey Smirnov 			if (status)
26170a919ae4SAndrey Smirnov 				return status;
26180a919ae4SAndrey Smirnov 			/*
26190a919ae4SAndrey Smirnov 			 * A controller using GPIO descriptors always
26200a919ae4SAndrey Smirnov 			 * supports SPI_CS_HIGH if need be.
26210a919ae4SAndrey Smirnov 			 */
26220a919ae4SAndrey Smirnov 			ctlr->mode_bits |= SPI_CS_HIGH;
26230a919ae4SAndrey Smirnov 		} else {
26240a919ae4SAndrey Smirnov 			/* Legacy code path for GPIOs from DT */
262543004f31SLinus Walleij 			status = of_spi_get_gpio_numbers(ctlr);
26260a919ae4SAndrey Smirnov 			if (status)
26270a919ae4SAndrey Smirnov 				return status;
26280a919ae4SAndrey Smirnov 		}
26290a919ae4SAndrey Smirnov 	}
26300a919ae4SAndrey Smirnov 
2631f9481b08STudor Ambarus 	/*
2632f9481b08STudor Ambarus 	 * Even if it's just one always-selected device, there must
2633f9481b08STudor Ambarus 	 * be at least one chipselect.
2634f9481b08STudor Ambarus 	 */
2635f9481b08STudor Ambarus 	if (!ctlr->num_chipselect)
2636f9481b08STudor Ambarus 		return -EINVAL;
2637f9481b08STudor Ambarus 
26388caab75fSGeert Uytterhoeven 	status = device_add(&ctlr->dev);
26399b61e302SSuniel Mahesh 	if (status < 0) {
26409b61e302SSuniel Mahesh 		/* free bus id */
26419b61e302SSuniel Mahesh 		mutex_lock(&board_lock);
26429b61e302SSuniel Mahesh 		idr_remove(&spi_master_idr, ctlr->bus_num);
26439b61e302SSuniel Mahesh 		mutex_unlock(&board_lock);
26448ae12a0dSDavid Brownell 		goto done;
26459b61e302SSuniel Mahesh 	}
26469b61e302SSuniel Mahesh 	dev_dbg(dev, "registered %s %s\n",
26478caab75fSGeert Uytterhoeven 			spi_controller_is_slave(ctlr) ? "slave" : "master",
26489b61e302SSuniel Mahesh 			dev_name(&ctlr->dev));
26498ae12a0dSDavid Brownell 
2650b5932f5cSBoris Brezillon 	/*
2651b5932f5cSBoris Brezillon 	 * If we're using a queued driver, start the queue. Note that we don't
2652b5932f5cSBoris Brezillon 	 * need the queueing logic if the driver is only supporting high-level
2653b5932f5cSBoris Brezillon 	 * memory operations.
2654b5932f5cSBoris Brezillon 	 */
2655b5932f5cSBoris Brezillon 	if (ctlr->transfer) {
26568caab75fSGeert Uytterhoeven 		dev_info(dev, "controller is unqueued, this is deprecated\n");
2657b5932f5cSBoris Brezillon 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
26588caab75fSGeert Uytterhoeven 		status = spi_controller_initialize_queue(ctlr);
2659ffbbdd21SLinus Walleij 		if (status) {
26608caab75fSGeert Uytterhoeven 			device_del(&ctlr->dev);
26619b61e302SSuniel Mahesh 			/* free bus id */
26629b61e302SSuniel Mahesh 			mutex_lock(&board_lock);
26639b61e302SSuniel Mahesh 			idr_remove(&spi_master_idr, ctlr->bus_num);
26649b61e302SSuniel Mahesh 			mutex_unlock(&board_lock);
2665ffbbdd21SLinus Walleij 			goto done;
2666ffbbdd21SLinus Walleij 		}
2667ffbbdd21SLinus Walleij 	}
2668eca2ebc7SMartin Sperl 	/* add statistics */
26698caab75fSGeert Uytterhoeven 	spin_lock_init(&ctlr->statistics.lock);
2670ffbbdd21SLinus Walleij 
26712b9603a0SFeng Tang 	mutex_lock(&board_lock);
26728caab75fSGeert Uytterhoeven 	list_add_tail(&ctlr->list, &spi_controller_list);
26732b9603a0SFeng Tang 	list_for_each_entry(bi, &board_list, list)
26748caab75fSGeert Uytterhoeven 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
26752b9603a0SFeng Tang 	mutex_unlock(&board_lock);
26762b9603a0SFeng Tang 
267764bee4d2SMika Westerberg 	/* Register devices from the device tree and ACPI */
26788caab75fSGeert Uytterhoeven 	of_register_spi_devices(ctlr);
26798caab75fSGeert Uytterhoeven 	acpi_register_spi_devices(ctlr);
26808ae12a0dSDavid Brownell done:
26818ae12a0dSDavid Brownell 	return status;
26828ae12a0dSDavid Brownell }
26838caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_register_controller);
26848ae12a0dSDavid Brownell 
2685666d5b4cSMark Brown static void devm_spi_unregister(struct device *dev, void *res)
2686666d5b4cSMark Brown {
26878caab75fSGeert Uytterhoeven 	spi_unregister_controller(*(struct spi_controller **)res);
2688666d5b4cSMark Brown }
2689666d5b4cSMark Brown 
2690666d5b4cSMark Brown /**
26918caab75fSGeert Uytterhoeven  * devm_spi_register_controller - register managed SPI master or slave
26928caab75fSGeert Uytterhoeven  *	controller
26938caab75fSGeert Uytterhoeven  * @dev:    device managing SPI controller
26948caab75fSGeert Uytterhoeven  * @ctlr: initialized controller, originally from spi_alloc_master() or
26958caab75fSGeert Uytterhoeven  *	spi_alloc_slave()
2696666d5b4cSMark Brown  * Context: can sleep
2697666d5b4cSMark Brown  *
26988caab75fSGeert Uytterhoeven  * Register a SPI device as with spi_register_controller() which will
269968b892f1SJohan Hovold  * automatically be unregistered and freed.
270097d56dc6SJavier Martinez Canillas  *
270197d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
2702666d5b4cSMark Brown  */
27038caab75fSGeert Uytterhoeven int devm_spi_register_controller(struct device *dev,
27048caab75fSGeert Uytterhoeven 				 struct spi_controller *ctlr)
2705666d5b4cSMark Brown {
27068caab75fSGeert Uytterhoeven 	struct spi_controller **ptr;
2707666d5b4cSMark Brown 	int ret;
2708666d5b4cSMark Brown 
2709666d5b4cSMark Brown 	ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2710666d5b4cSMark Brown 	if (!ptr)
2711666d5b4cSMark Brown 		return -ENOMEM;
2712666d5b4cSMark Brown 
27138caab75fSGeert Uytterhoeven 	ret = spi_register_controller(ctlr);
27144b92894eSStephen Warren 	if (!ret) {
27158caab75fSGeert Uytterhoeven 		*ptr = ctlr;
2716666d5b4cSMark Brown 		devres_add(dev, ptr);
2717666d5b4cSMark Brown 	} else {
2718666d5b4cSMark Brown 		devres_free(ptr);
2719666d5b4cSMark Brown 	}
2720666d5b4cSMark Brown 
2721666d5b4cSMark Brown 	return ret;
2722666d5b4cSMark Brown }
27238caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2724666d5b4cSMark Brown 
272534860089SDavid Lamparter static int __unregister(struct device *dev, void *null)
27268ae12a0dSDavid Brownell {
27270c868461SDavid Brownell 	spi_unregister_device(to_spi_device(dev));
27288ae12a0dSDavid Brownell 	return 0;
27298ae12a0dSDavid Brownell }
27308ae12a0dSDavid Brownell 
27318ae12a0dSDavid Brownell /**
27328caab75fSGeert Uytterhoeven  * spi_unregister_controller - unregister SPI master or slave controller
27338caab75fSGeert Uytterhoeven  * @ctlr: the controller being unregistered
273433e34dc6SDavid Brownell  * Context: can sleep
27358ae12a0dSDavid Brownell  *
27368caab75fSGeert Uytterhoeven  * This call is used only by SPI controller drivers, which are the
27378ae12a0dSDavid Brownell  * only ones directly touching chip registers.
27388ae12a0dSDavid Brownell  *
27398ae12a0dSDavid Brownell  * This must be called from context that can sleep.
274068b892f1SJohan Hovold  *
274168b892f1SJohan Hovold  * Note that this function also drops a reference to the controller.
27428ae12a0dSDavid Brownell  */
27438caab75fSGeert Uytterhoeven void spi_unregister_controller(struct spi_controller *ctlr)
27448ae12a0dSDavid Brownell {
27459b61e302SSuniel Mahesh 	struct spi_controller *found;
274667f7b278SJohan Hovold 	int id = ctlr->bus_num;
274789fc9a1aSJeff Garzik 
27489b61e302SSuniel Mahesh 	/* First make sure that this controller was ever added */
27499b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
275067f7b278SJohan Hovold 	found = idr_find(&spi_master_idr, id);
27519b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
27528caab75fSGeert Uytterhoeven 	if (ctlr->queued) {
27538caab75fSGeert Uytterhoeven 		if (spi_destroy_queue(ctlr))
27548caab75fSGeert Uytterhoeven 			dev_err(&ctlr->dev, "queue remove failed\n");
2755ffbbdd21SLinus Walleij 	}
27562b9603a0SFeng Tang 	mutex_lock(&board_lock);
27578caab75fSGeert Uytterhoeven 	list_del(&ctlr->list);
27582b9603a0SFeng Tang 	mutex_unlock(&board_lock);
27592b9603a0SFeng Tang 
2760ebc37af5SAndy Shevchenko 	device_for_each_child(&ctlr->dev, NULL, __unregister);
27618caab75fSGeert Uytterhoeven 	device_unregister(&ctlr->dev);
27629b61e302SSuniel Mahesh 	/* free bus id */
27639b61e302SSuniel Mahesh 	mutex_lock(&board_lock);
2764613bd1eaSJarkko Nikula 	if (found == ctlr)
276567f7b278SJohan Hovold 		idr_remove(&spi_master_idr, id);
27669b61e302SSuniel Mahesh 	mutex_unlock(&board_lock);
27678ae12a0dSDavid Brownell }
27688caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_unregister_controller);
27698ae12a0dSDavid Brownell 
27708caab75fSGeert Uytterhoeven int spi_controller_suspend(struct spi_controller *ctlr)
2771ffbbdd21SLinus Walleij {
2772ffbbdd21SLinus Walleij 	int ret;
2773ffbbdd21SLinus Walleij 
27748caab75fSGeert Uytterhoeven 	/* Basically no-ops for non-queued controllers */
27758caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
2776ffbbdd21SLinus Walleij 		return 0;
2777ffbbdd21SLinus Walleij 
27788caab75fSGeert Uytterhoeven 	ret = spi_stop_queue(ctlr);
2779ffbbdd21SLinus Walleij 	if (ret)
27808caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue stop failed\n");
2781ffbbdd21SLinus Walleij 
2782ffbbdd21SLinus Walleij 	return ret;
2783ffbbdd21SLinus Walleij }
27848caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_suspend);
2785ffbbdd21SLinus Walleij 
27868caab75fSGeert Uytterhoeven int spi_controller_resume(struct spi_controller *ctlr)
2787ffbbdd21SLinus Walleij {
2788ffbbdd21SLinus Walleij 	int ret;
2789ffbbdd21SLinus Walleij 
27908caab75fSGeert Uytterhoeven 	if (!ctlr->queued)
2791ffbbdd21SLinus Walleij 		return 0;
2792ffbbdd21SLinus Walleij 
27938caab75fSGeert Uytterhoeven 	ret = spi_start_queue(ctlr);
2794ffbbdd21SLinus Walleij 	if (ret)
27958caab75fSGeert Uytterhoeven 		dev_err(&ctlr->dev, "queue restart failed\n");
2796ffbbdd21SLinus Walleij 
2797ffbbdd21SLinus Walleij 	return ret;
2798ffbbdd21SLinus Walleij }
27998caab75fSGeert Uytterhoeven EXPORT_SYMBOL_GPL(spi_controller_resume);
2800ffbbdd21SLinus Walleij 
28018caab75fSGeert Uytterhoeven static int __spi_controller_match(struct device *dev, const void *data)
28025ed2c832SDave Young {
28038caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
28049f3b795aSMichał Mirosław 	const u16 *bus_num = data;
28055ed2c832SDave Young 
28068caab75fSGeert Uytterhoeven 	ctlr = container_of(dev, struct spi_controller, dev);
28078caab75fSGeert Uytterhoeven 	return ctlr->bus_num == *bus_num;
28085ed2c832SDave Young }
28095ed2c832SDave Young 
28108ae12a0dSDavid Brownell /**
28118ae12a0dSDavid Brownell  * spi_busnum_to_master - look up master associated with bus_num
28128ae12a0dSDavid Brownell  * @bus_num: the master's bus number
281333e34dc6SDavid Brownell  * Context: can sleep
28148ae12a0dSDavid Brownell  *
28158ae12a0dSDavid Brownell  * This call may be used with devices that are registered after
28168ae12a0dSDavid Brownell  * arch init time.  It returns a refcounted pointer to the relevant
28178caab75fSGeert Uytterhoeven  * spi_controller (which the caller must release), or NULL if there is
28188ae12a0dSDavid Brownell  * no such master registered.
281997d56dc6SJavier Martinez Canillas  *
282097d56dc6SJavier Martinez Canillas  * Return: the SPI master structure on success, else NULL.
28218ae12a0dSDavid Brownell  */
28228caab75fSGeert Uytterhoeven struct spi_controller *spi_busnum_to_master(u16 bus_num)
28238ae12a0dSDavid Brownell {
282449dce689STony Jones 	struct device		*dev;
28258caab75fSGeert Uytterhoeven 	struct spi_controller	*ctlr = NULL;
28268ae12a0dSDavid Brownell 
2827695794aeSGreg Kroah-Hartman 	dev = class_find_device(&spi_master_class, NULL, &bus_num,
28288caab75fSGeert Uytterhoeven 				__spi_controller_match);
28295ed2c832SDave Young 	if (dev)
28308caab75fSGeert Uytterhoeven 		ctlr = container_of(dev, struct spi_controller, dev);
28315ed2c832SDave Young 	/* reference got in class_find_device */
28328caab75fSGeert Uytterhoeven 	return ctlr;
28338ae12a0dSDavid Brownell }
28348ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_busnum_to_master);
28358ae12a0dSDavid Brownell 
2836d780c371SMartin Sperl /*-------------------------------------------------------------------------*/
2837d780c371SMartin Sperl 
2838d780c371SMartin Sperl /* Core methods for SPI resource management */
2839d780c371SMartin Sperl 
2840d780c371SMartin Sperl /**
2841d780c371SMartin Sperl  * spi_res_alloc - allocate a spi resource that is life-cycle managed
2842d780c371SMartin Sperl  *                 during the processing of a spi_message while using
2843d780c371SMartin Sperl  *                 spi_transfer_one
2844d780c371SMartin Sperl  * @spi:     the spi device for which we allocate memory
2845d780c371SMartin Sperl  * @release: the release code to execute for this resource
2846d780c371SMartin Sperl  * @size:    size to alloc and return
2847d780c371SMartin Sperl  * @gfp:     GFP allocation flags
2848d780c371SMartin Sperl  *
2849d780c371SMartin Sperl  * Return: the pointer to the allocated data
2850d780c371SMartin Sperl  *
2851d780c371SMartin Sperl  * This may get enhanced in the future to allocate from a memory pool
28528caab75fSGeert Uytterhoeven  * of the @spi_device or @spi_controller to avoid repeated allocations.
2853d780c371SMartin Sperl  */
2854d780c371SMartin Sperl void *spi_res_alloc(struct spi_device *spi,
2855d780c371SMartin Sperl 		    spi_res_release_t release,
2856d780c371SMartin Sperl 		    size_t size, gfp_t gfp)
2857d780c371SMartin Sperl {
2858d780c371SMartin Sperl 	struct spi_res *sres;
2859d780c371SMartin Sperl 
2860d780c371SMartin Sperl 	sres = kzalloc(sizeof(*sres) + size, gfp);
2861d780c371SMartin Sperl 	if (!sres)
2862d780c371SMartin Sperl 		return NULL;
2863d780c371SMartin Sperl 
2864d780c371SMartin Sperl 	INIT_LIST_HEAD(&sres->entry);
2865d780c371SMartin Sperl 	sres->release = release;
2866d780c371SMartin Sperl 
2867d780c371SMartin Sperl 	return sres->data;
2868d780c371SMartin Sperl }
2869d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_alloc);
2870d780c371SMartin Sperl 
2871d780c371SMartin Sperl /**
2872d780c371SMartin Sperl  * spi_res_free - free an spi resource
2873d780c371SMartin Sperl  * @res: pointer to the custom data of a resource
2874d780c371SMartin Sperl  *
2875d780c371SMartin Sperl  */
2876d780c371SMartin Sperl void spi_res_free(void *res)
2877d780c371SMartin Sperl {
2878d780c371SMartin Sperl 	struct spi_res *sres = container_of(res, struct spi_res, data);
2879d780c371SMartin Sperl 
2880d780c371SMartin Sperl 	if (!res)
2881d780c371SMartin Sperl 		return;
2882d780c371SMartin Sperl 
2883d780c371SMartin Sperl 	WARN_ON(!list_empty(&sres->entry));
2884d780c371SMartin Sperl 	kfree(sres);
2885d780c371SMartin Sperl }
2886d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_free);
2887d780c371SMartin Sperl 
2888d780c371SMartin Sperl /**
2889d780c371SMartin Sperl  * spi_res_add - add a spi_res to the spi_message
2890d780c371SMartin Sperl  * @message: the spi message
2891d780c371SMartin Sperl  * @res:     the spi_resource
2892d780c371SMartin Sperl  */
2893d780c371SMartin Sperl void spi_res_add(struct spi_message *message, void *res)
2894d780c371SMartin Sperl {
2895d780c371SMartin Sperl 	struct spi_res *sres = container_of(res, struct spi_res, data);
2896d780c371SMartin Sperl 
2897d780c371SMartin Sperl 	WARN_ON(!list_empty(&sres->entry));
2898d780c371SMartin Sperl 	list_add_tail(&sres->entry, &message->resources);
2899d780c371SMartin Sperl }
2900d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_add);
2901d780c371SMartin Sperl 
2902d780c371SMartin Sperl /**
2903d780c371SMartin Sperl  * spi_res_release - release all spi resources for this message
29048caab75fSGeert Uytterhoeven  * @ctlr:  the @spi_controller
2905d780c371SMartin Sperl  * @message: the @spi_message
2906d780c371SMartin Sperl  */
29078caab75fSGeert Uytterhoeven void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
2908d780c371SMartin Sperl {
2909f5694369SVladimir Zapolskiy 	struct spi_res *res, *tmp;
2910d780c371SMartin Sperl 
2911f5694369SVladimir Zapolskiy 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
2912d780c371SMartin Sperl 		if (res->release)
29138caab75fSGeert Uytterhoeven 			res->release(ctlr, message, res->data);
2914d780c371SMartin Sperl 
2915d780c371SMartin Sperl 		list_del(&res->entry);
2916d780c371SMartin Sperl 
2917d780c371SMartin Sperl 		kfree(res);
2918d780c371SMartin Sperl 	}
2919d780c371SMartin Sperl }
2920d780c371SMartin Sperl EXPORT_SYMBOL_GPL(spi_res_release);
29218ae12a0dSDavid Brownell 
29228ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
29238ae12a0dSDavid Brownell 
2924523baf5aSMartin Sperl /* Core methods for spi_message alterations */
2925523baf5aSMartin Sperl 
29268caab75fSGeert Uytterhoeven static void __spi_replace_transfers_release(struct spi_controller *ctlr,
2927523baf5aSMartin Sperl 					    struct spi_message *msg,
2928523baf5aSMartin Sperl 					    void *res)
2929523baf5aSMartin Sperl {
2930523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer = res;
2931523baf5aSMartin Sperl 	size_t i;
2932523baf5aSMartin Sperl 
2933523baf5aSMartin Sperl 	/* call extra callback if requested */
2934523baf5aSMartin Sperl 	if (rxfer->release)
29358caab75fSGeert Uytterhoeven 		rxfer->release(ctlr, msg, res);
2936523baf5aSMartin Sperl 
2937523baf5aSMartin Sperl 	/* insert replaced transfers back into the message */
2938523baf5aSMartin Sperl 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
2939523baf5aSMartin Sperl 
2940523baf5aSMartin Sperl 	/* remove the formerly inserted entries */
2941523baf5aSMartin Sperl 	for (i = 0; i < rxfer->inserted; i++)
2942523baf5aSMartin Sperl 		list_del(&rxfer->inserted_transfers[i].transfer_list);
2943523baf5aSMartin Sperl }
2944523baf5aSMartin Sperl 
2945523baf5aSMartin Sperl /**
2946523baf5aSMartin Sperl  * spi_replace_transfers - replace transfers with several transfers
2947523baf5aSMartin Sperl  *                         and register change with spi_message.resources
2948523baf5aSMartin Sperl  * @msg:           the spi_message we work upon
2949523baf5aSMartin Sperl  * @xfer_first:    the first spi_transfer we want to replace
2950523baf5aSMartin Sperl  * @remove:        number of transfers to remove
2951523baf5aSMartin Sperl  * @insert:        the number of transfers we want to insert instead
2952523baf5aSMartin Sperl  * @release:       extra release code necessary in some circumstances
2953523baf5aSMartin Sperl  * @extradatasize: extra data to allocate (with alignment guarantees
2954523baf5aSMartin Sperl  *                 of struct @spi_transfer)
295505885397SMartin Sperl  * @gfp:           gfp flags
2956523baf5aSMartin Sperl  *
2957523baf5aSMartin Sperl  * Returns: pointer to @spi_replaced_transfers,
2958523baf5aSMartin Sperl  *          PTR_ERR(...) in case of errors.
2959523baf5aSMartin Sperl  */
2960523baf5aSMartin Sperl struct spi_replaced_transfers *spi_replace_transfers(
2961523baf5aSMartin Sperl 	struct spi_message *msg,
2962523baf5aSMartin Sperl 	struct spi_transfer *xfer_first,
2963523baf5aSMartin Sperl 	size_t remove,
2964523baf5aSMartin Sperl 	size_t insert,
2965523baf5aSMartin Sperl 	spi_replaced_release_t release,
2966523baf5aSMartin Sperl 	size_t extradatasize,
2967523baf5aSMartin Sperl 	gfp_t gfp)
2968523baf5aSMartin Sperl {
2969523baf5aSMartin Sperl 	struct spi_replaced_transfers *rxfer;
2970523baf5aSMartin Sperl 	struct spi_transfer *xfer;
2971523baf5aSMartin Sperl 	size_t i;
2972523baf5aSMartin Sperl 
2973523baf5aSMartin Sperl 	/* allocate the structure using spi_res */
2974523baf5aSMartin Sperl 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
2975aef97522SGustavo A. R. Silva 			      struct_size(rxfer, inserted_transfers, insert)
2976523baf5aSMartin Sperl 			      + extradatasize,
2977523baf5aSMartin Sperl 			      gfp);
2978523baf5aSMartin Sperl 	if (!rxfer)
2979523baf5aSMartin Sperl 		return ERR_PTR(-ENOMEM);
2980523baf5aSMartin Sperl 
2981523baf5aSMartin Sperl 	/* the release code to invoke before running the generic release */
2982523baf5aSMartin Sperl 	rxfer->release = release;
2983523baf5aSMartin Sperl 
2984523baf5aSMartin Sperl 	/* assign extradata */
2985523baf5aSMartin Sperl 	if (extradatasize)
2986523baf5aSMartin Sperl 		rxfer->extradata =
2987523baf5aSMartin Sperl 			&rxfer->inserted_transfers[insert];
2988523baf5aSMartin Sperl 
2989523baf5aSMartin Sperl 	/* init the replaced_transfers list */
2990523baf5aSMartin Sperl 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
2991523baf5aSMartin Sperl 
2992523baf5aSMartin Sperl 	/* assign the list_entry after which we should reinsert
2993523baf5aSMartin Sperl 	 * the @replaced_transfers - it may be spi_message.messages!
2994523baf5aSMartin Sperl 	 */
2995523baf5aSMartin Sperl 	rxfer->replaced_after = xfer_first->transfer_list.prev;
2996523baf5aSMartin Sperl 
2997523baf5aSMartin Sperl 	/* remove the requested number of transfers */
2998523baf5aSMartin Sperl 	for (i = 0; i < remove; i++) {
2999523baf5aSMartin Sperl 		/* if the entry after replaced_after it is msg->transfers
3000523baf5aSMartin Sperl 		 * then we have been requested to remove more transfers
3001523baf5aSMartin Sperl 		 * than are in the list
3002523baf5aSMartin Sperl 		 */
3003523baf5aSMartin Sperl 		if (rxfer->replaced_after->next == &msg->transfers) {
3004523baf5aSMartin Sperl 			dev_err(&msg->spi->dev,
3005523baf5aSMartin Sperl 				"requested to remove more spi_transfers than are available\n");
3006523baf5aSMartin Sperl 			/* insert replaced transfers back into the message */
3007523baf5aSMartin Sperl 			list_splice(&rxfer->replaced_transfers,
3008523baf5aSMartin Sperl 				    rxfer->replaced_after);
3009523baf5aSMartin Sperl 
3010523baf5aSMartin Sperl 			/* free the spi_replace_transfer structure */
3011523baf5aSMartin Sperl 			spi_res_free(rxfer);
3012523baf5aSMartin Sperl 
3013523baf5aSMartin Sperl 			/* and return with an error */
3014523baf5aSMartin Sperl 			return ERR_PTR(-EINVAL);
3015523baf5aSMartin Sperl 		}
3016523baf5aSMartin Sperl 
3017523baf5aSMartin Sperl 		/* remove the entry after replaced_after from list of
3018523baf5aSMartin Sperl 		 * transfers and add it to list of replaced_transfers
3019523baf5aSMartin Sperl 		 */
3020523baf5aSMartin Sperl 		list_move_tail(rxfer->replaced_after->next,
3021523baf5aSMartin Sperl 			       &rxfer->replaced_transfers);
3022523baf5aSMartin Sperl 	}
3023523baf5aSMartin Sperl 
3024523baf5aSMartin Sperl 	/* create copy of the given xfer with identical settings
3025523baf5aSMartin Sperl 	 * based on the first transfer to get removed
3026523baf5aSMartin Sperl 	 */
3027523baf5aSMartin Sperl 	for (i = 0; i < insert; i++) {
3028523baf5aSMartin Sperl 		/* we need to run in reverse order */
3029523baf5aSMartin Sperl 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3030523baf5aSMartin Sperl 
3031523baf5aSMartin Sperl 		/* copy all spi_transfer data */
3032523baf5aSMartin Sperl 		memcpy(xfer, xfer_first, sizeof(*xfer));
3033523baf5aSMartin Sperl 
3034523baf5aSMartin Sperl 		/* add to list */
3035523baf5aSMartin Sperl 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3036523baf5aSMartin Sperl 
3037bebcfd27SAlexandru Ardelean 		/* clear cs_change and delay for all but the last */
3038523baf5aSMartin Sperl 		if (i) {
3039523baf5aSMartin Sperl 			xfer->cs_change = false;
3040523baf5aSMartin Sperl 			xfer->delay_usecs = 0;
3041bebcfd27SAlexandru Ardelean 			xfer->delay.value = 0;
3042523baf5aSMartin Sperl 		}
3043523baf5aSMartin Sperl 	}
3044523baf5aSMartin Sperl 
3045523baf5aSMartin Sperl 	/* set up inserted */
3046523baf5aSMartin Sperl 	rxfer->inserted = insert;
3047523baf5aSMartin Sperl 
3048523baf5aSMartin Sperl 	/* and register it with spi_res/spi_message */
3049523baf5aSMartin Sperl 	spi_res_add(msg, rxfer);
3050523baf5aSMartin Sperl 
3051523baf5aSMartin Sperl 	return rxfer;
3052523baf5aSMartin Sperl }
3053523baf5aSMartin Sperl EXPORT_SYMBOL_GPL(spi_replace_transfers);
3054523baf5aSMartin Sperl 
30558caab75fSGeert Uytterhoeven static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3056d9f12122SMartin Sperl 					struct spi_message *msg,
3057d9f12122SMartin Sperl 					struct spi_transfer **xferp,
3058d9f12122SMartin Sperl 					size_t maxsize,
3059d9f12122SMartin Sperl 					gfp_t gfp)
3060d9f12122SMartin Sperl {
3061d9f12122SMartin Sperl 	struct spi_transfer *xfer = *xferp, *xfers;
3062d9f12122SMartin Sperl 	struct spi_replaced_transfers *srt;
3063d9f12122SMartin Sperl 	size_t offset;
3064d9f12122SMartin Sperl 	size_t count, i;
3065d9f12122SMartin Sperl 
3066d9f12122SMartin Sperl 	/* calculate how many we have to replace */
3067d9f12122SMartin Sperl 	count = DIV_ROUND_UP(xfer->len, maxsize);
3068d9f12122SMartin Sperl 
3069d9f12122SMartin Sperl 	/* create replacement */
3070d9f12122SMartin Sperl 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3071657d32efSDan Carpenter 	if (IS_ERR(srt))
3072657d32efSDan Carpenter 		return PTR_ERR(srt);
3073d9f12122SMartin Sperl 	xfers = srt->inserted_transfers;
3074d9f12122SMartin Sperl 
3075d9f12122SMartin Sperl 	/* now handle each of those newly inserted spi_transfers
3076d9f12122SMartin Sperl 	 * note that the replacements spi_transfers all are preset
3077d9f12122SMartin Sperl 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3078d9f12122SMartin Sperl 	 * are all identical (as well as most others)
3079d9f12122SMartin Sperl 	 * so we just have to fix up len and the pointers.
3080d9f12122SMartin Sperl 	 *
3081d9f12122SMartin Sperl 	 * this also includes support for the depreciated
3082d9f12122SMartin Sperl 	 * spi_message.is_dma_mapped interface
3083d9f12122SMartin Sperl 	 */
3084d9f12122SMartin Sperl 
3085d9f12122SMartin Sperl 	/* the first transfer just needs the length modified, so we
3086d9f12122SMartin Sperl 	 * run it outside the loop
3087d9f12122SMartin Sperl 	 */
3088c8dab77aSFabio Estevam 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3089d9f12122SMartin Sperl 
3090d9f12122SMartin Sperl 	/* all the others need rx_buf/tx_buf also set */
3091d9f12122SMartin Sperl 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3092d9f12122SMartin Sperl 		/* update rx_buf, tx_buf and dma */
3093d9f12122SMartin Sperl 		if (xfers[i].rx_buf)
3094d9f12122SMartin Sperl 			xfers[i].rx_buf += offset;
3095d9f12122SMartin Sperl 		if (xfers[i].rx_dma)
3096d9f12122SMartin Sperl 			xfers[i].rx_dma += offset;
3097d9f12122SMartin Sperl 		if (xfers[i].tx_buf)
3098d9f12122SMartin Sperl 			xfers[i].tx_buf += offset;
3099d9f12122SMartin Sperl 		if (xfers[i].tx_dma)
3100d9f12122SMartin Sperl 			xfers[i].tx_dma += offset;
3101d9f12122SMartin Sperl 
3102d9f12122SMartin Sperl 		/* update length */
3103d9f12122SMartin Sperl 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3104d9f12122SMartin Sperl 	}
3105d9f12122SMartin Sperl 
3106d9f12122SMartin Sperl 	/* we set up xferp to the last entry we have inserted,
3107d9f12122SMartin Sperl 	 * so that we skip those already split transfers
3108d9f12122SMartin Sperl 	 */
3109d9f12122SMartin Sperl 	*xferp = &xfers[count - 1];
3110d9f12122SMartin Sperl 
3111d9f12122SMartin Sperl 	/* increment statistics counters */
31128caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3113d9f12122SMartin Sperl 				       transfers_split_maxsize);
3114d9f12122SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3115d9f12122SMartin Sperl 				       transfers_split_maxsize);
3116d9f12122SMartin Sperl 
3117d9f12122SMartin Sperl 	return 0;
3118d9f12122SMartin Sperl }
3119d9f12122SMartin Sperl 
3120d9f12122SMartin Sperl /**
3121d9f12122SMartin Sperl  * spi_split_tranfers_maxsize - split spi transfers into multiple transfers
3122d9f12122SMartin Sperl  *                              when an individual transfer exceeds a
3123d9f12122SMartin Sperl  *                              certain size
31248caab75fSGeert Uytterhoeven  * @ctlr:    the @spi_controller for this transfer
31253700ce95SMasanari Iida  * @msg:   the @spi_message to transform
31263700ce95SMasanari Iida  * @maxsize:  the maximum when to apply this
312710f11a22SJavier Martinez Canillas  * @gfp: GFP allocation flags
3128d9f12122SMartin Sperl  *
3129d9f12122SMartin Sperl  * Return: status of transformation
3130d9f12122SMartin Sperl  */
31318caab75fSGeert Uytterhoeven int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3132d9f12122SMartin Sperl 				struct spi_message *msg,
3133d9f12122SMartin Sperl 				size_t maxsize,
3134d9f12122SMartin Sperl 				gfp_t gfp)
3135d9f12122SMartin Sperl {
3136d9f12122SMartin Sperl 	struct spi_transfer *xfer;
3137d9f12122SMartin Sperl 	int ret;
3138d9f12122SMartin Sperl 
3139d9f12122SMartin Sperl 	/* iterate over the transfer_list,
3140d9f12122SMartin Sperl 	 * but note that xfer is advanced to the last transfer inserted
3141d9f12122SMartin Sperl 	 * to avoid checking sizes again unnecessarily (also xfer does
3142d9f12122SMartin Sperl 	 * potentiall belong to a different list by the time the
3143d9f12122SMartin Sperl 	 * replacement has happened
3144d9f12122SMartin Sperl 	 */
3145d9f12122SMartin Sperl 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3146d9f12122SMartin Sperl 		if (xfer->len > maxsize) {
31478caab75fSGeert Uytterhoeven 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
31488caab75fSGeert Uytterhoeven 							   maxsize, gfp);
3149d9f12122SMartin Sperl 			if (ret)
3150d9f12122SMartin Sperl 				return ret;
3151d9f12122SMartin Sperl 		}
3152d9f12122SMartin Sperl 	}
3153d9f12122SMartin Sperl 
3154d9f12122SMartin Sperl 	return 0;
3155d9f12122SMartin Sperl }
3156d9f12122SMartin Sperl EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
31578ae12a0dSDavid Brownell 
31588ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
31598ae12a0dSDavid Brownell 
31608caab75fSGeert Uytterhoeven /* Core methods for SPI controller protocol drivers.  Some of the
31617d077197SDavid Brownell  * other core methods are currently defined as inline functions.
31627d077197SDavid Brownell  */
31637d077197SDavid Brownell 
31648caab75fSGeert Uytterhoeven static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
31658caab75fSGeert Uytterhoeven 					u8 bits_per_word)
316663ab645fSStefan Brüns {
31678caab75fSGeert Uytterhoeven 	if (ctlr->bits_per_word_mask) {
316863ab645fSStefan Brüns 		/* Only 32 bits fit in the mask */
316963ab645fSStefan Brüns 		if (bits_per_word > 32)
317063ab645fSStefan Brüns 			return -EINVAL;
31718caab75fSGeert Uytterhoeven 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
317263ab645fSStefan Brüns 			return -EINVAL;
317363ab645fSStefan Brüns 	}
317463ab645fSStefan Brüns 
317563ab645fSStefan Brüns 	return 0;
317663ab645fSStefan Brüns }
317763ab645fSStefan Brüns 
31787d077197SDavid Brownell /**
31797d077197SDavid Brownell  * spi_setup - setup SPI mode and clock rate
31807d077197SDavid Brownell  * @spi: the device whose settings are being modified
31817d077197SDavid Brownell  * Context: can sleep, and no requests are queued to the device
31827d077197SDavid Brownell  *
31837d077197SDavid Brownell  * SPI protocol drivers may need to update the transfer mode if the
31847d077197SDavid Brownell  * device doesn't work with its default.  They may likewise need
31857d077197SDavid Brownell  * to update clock rates or word sizes from initial values.  This function
31867d077197SDavid Brownell  * changes those settings, and must be called from a context that can sleep.
31877d077197SDavid Brownell  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
31887d077197SDavid Brownell  * effect the next time the device is selected and data is transferred to
31897d077197SDavid Brownell  * or from it.  When this function returns, the spi device is deselected.
31907d077197SDavid Brownell  *
31917d077197SDavid Brownell  * Note that this call will fail if the protocol driver specifies an option
31927d077197SDavid Brownell  * that the underlying controller or its driver does not support.  For
31937d077197SDavid Brownell  * example, not all hardware supports wire transfers using nine bit words,
31947d077197SDavid Brownell  * LSB-first wire encoding, or active-high chipselects.
319597d56dc6SJavier Martinez Canillas  *
319697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
31977d077197SDavid Brownell  */
31987d077197SDavid Brownell int spi_setup(struct spi_device *spi)
31997d077197SDavid Brownell {
320083596fbeSGeert Uytterhoeven 	unsigned	bad_bits, ugly_bits;
32015ab8d262SAndy Shevchenko 	int		status;
32027d077197SDavid Brownell 
3203f477b7fbSwangyuhang 	/* check mode to prevent that DUAL and QUAD set at the same time
3204f477b7fbSwangyuhang 	 */
3205f477b7fbSwangyuhang 	if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
3206f477b7fbSwangyuhang 		((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
3207f477b7fbSwangyuhang 		dev_err(&spi->dev,
3208f477b7fbSwangyuhang 		"setup: can not select dual and quad at the same time\n");
3209f477b7fbSwangyuhang 		return -EINVAL;
3210f477b7fbSwangyuhang 	}
3211f477b7fbSwangyuhang 	/* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3212f477b7fbSwangyuhang 	 */
3213f477b7fbSwangyuhang 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
32146b03061fSYogesh Narayan Gaur 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
32156b03061fSYogesh Narayan Gaur 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3216f477b7fbSwangyuhang 		return -EINVAL;
3217e7db06b5SDavid Brownell 	/* help drivers fail *cleanly* when they need options
32188caab75fSGeert Uytterhoeven 	 * that aren't supported with their current controller
3219cbaa62e0SDavid Lechner 	 * SPI_CS_WORD has a fallback software implementation,
3220cbaa62e0SDavid Lechner 	 * so it is ignored here.
3221e7db06b5SDavid Brownell 	 */
3222cbaa62e0SDavid Lechner 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD);
3223d61ad23cSSerge Semin 	/* nothing prevents from working with active-high CS in case if it
3224d61ad23cSSerge Semin 	 * is driven by GPIO.
3225d61ad23cSSerge Semin 	 */
3226d61ad23cSSerge Semin 	if (gpio_is_valid(spi->cs_gpio))
3227d61ad23cSSerge Semin 		bad_bits &= ~SPI_CS_HIGH;
322883596fbeSGeert Uytterhoeven 	ugly_bits = bad_bits &
32296b03061fSYogesh Narayan Gaur 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
32306b03061fSYogesh Narayan Gaur 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
323183596fbeSGeert Uytterhoeven 	if (ugly_bits) {
323283596fbeSGeert Uytterhoeven 		dev_warn(&spi->dev,
323383596fbeSGeert Uytterhoeven 			 "setup: ignoring unsupported mode bits %x\n",
323483596fbeSGeert Uytterhoeven 			 ugly_bits);
323583596fbeSGeert Uytterhoeven 		spi->mode &= ~ugly_bits;
323683596fbeSGeert Uytterhoeven 		bad_bits &= ~ugly_bits;
323783596fbeSGeert Uytterhoeven 	}
3238e7db06b5SDavid Brownell 	if (bad_bits) {
3239eb288a1fSLinus Walleij 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3240e7db06b5SDavid Brownell 			bad_bits);
3241e7db06b5SDavid Brownell 		return -EINVAL;
3242e7db06b5SDavid Brownell 	}
3243e7db06b5SDavid Brownell 
32447d077197SDavid Brownell 	if (!spi->bits_per_word)
32457d077197SDavid Brownell 		spi->bits_per_word = 8;
32467d077197SDavid Brownell 
32478caab75fSGeert Uytterhoeven 	status = __spi_validate_bits_per_word(spi->controller,
32488caab75fSGeert Uytterhoeven 					      spi->bits_per_word);
32495ab8d262SAndy Shevchenko 	if (status)
32505ab8d262SAndy Shevchenko 		return status;
325163ab645fSStefan Brüns 
3252052eb2d4SAxel Lin 	if (!spi->max_speed_hz)
32538caab75fSGeert Uytterhoeven 		spi->max_speed_hz = spi->controller->max_speed_hz;
3254052eb2d4SAxel Lin 
32558caab75fSGeert Uytterhoeven 	if (spi->controller->setup)
32568caab75fSGeert Uytterhoeven 		status = spi->controller->setup(spi);
32577d077197SDavid Brownell 
3258d948e6caSLuhua Xu 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3259d948e6caSLuhua Xu 		status = pm_runtime_get_sync(spi->controller->dev.parent);
3260d948e6caSLuhua Xu 		if (status < 0) {
3261d948e6caSLuhua Xu 			pm_runtime_put_noidle(spi->controller->dev.parent);
3262d948e6caSLuhua Xu 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3263d948e6caSLuhua Xu 				status);
3264d948e6caSLuhua Xu 			return status;
3265d948e6caSLuhua Xu 		}
326657a94607STony Lindgren 
326757a94607STony Lindgren 		/*
326857a94607STony Lindgren 		 * We do not want to return positive value from pm_runtime_get,
326957a94607STony Lindgren 		 * there are many instances of devices calling spi_setup() and
327057a94607STony Lindgren 		 * checking for a non-zero return value instead of a negative
327157a94607STony Lindgren 		 * return value.
327257a94607STony Lindgren 		 */
327357a94607STony Lindgren 		status = 0;
327457a94607STony Lindgren 
3275abeedb01SFranklin S Cooper Jr 		spi_set_cs(spi, false);
3276d948e6caSLuhua Xu 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3277d948e6caSLuhua Xu 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3278d948e6caSLuhua Xu 	} else {
3279d948e6caSLuhua Xu 		spi_set_cs(spi, false);
3280d948e6caSLuhua Xu 	}
3281abeedb01SFranklin S Cooper Jr 
3282924b5867SDouglas Anderson 	if (spi->rt && !spi->controller->rt) {
3283924b5867SDouglas Anderson 		spi->controller->rt = true;
3284924b5867SDouglas Anderson 		spi_set_thread_rt(spi->controller);
3285924b5867SDouglas Anderson 	}
3286924b5867SDouglas Anderson 
32875fe5f05eSJingoo Han 	dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
32887d077197SDavid Brownell 			(int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
32897d077197SDavid Brownell 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
32907d077197SDavid Brownell 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
32917d077197SDavid Brownell 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
32927d077197SDavid Brownell 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
32937d077197SDavid Brownell 			spi->bits_per_word, spi->max_speed_hz,
32947d077197SDavid Brownell 			status);
32957d077197SDavid Brownell 
32967d077197SDavid Brownell 	return status;
32977d077197SDavid Brownell }
32987d077197SDavid Brownell EXPORT_SYMBOL_GPL(spi_setup);
32997d077197SDavid Brownell 
3300f1ca9992SSowjanya Komatineni /**
3301f1ca9992SSowjanya Komatineni  * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3302f1ca9992SSowjanya Komatineni  * @spi: the device that requires specific CS timing configuration
330381059366SAlexandru Ardelean  * @setup: CS setup time specified via @spi_delay
330481059366SAlexandru Ardelean  * @hold: CS hold time specified via @spi_delay
330581059366SAlexandru Ardelean  * @inactive: CS inactive delay between transfers specified via @spi_delay
330681059366SAlexandru Ardelean  *
330781059366SAlexandru Ardelean  * Return: zero on success, else a negative error code.
3308f1ca9992SSowjanya Komatineni  */
330981059366SAlexandru Ardelean int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
331081059366SAlexandru Ardelean 		      struct spi_delay *hold, struct spi_delay *inactive)
3311f1ca9992SSowjanya Komatineni {
331225093bdeSAlexandru Ardelean 	size_t len;
331325093bdeSAlexandru Ardelean 
3314f1ca9992SSowjanya Komatineni 	if (spi->controller->set_cs_timing)
331581059366SAlexandru Ardelean 		return spi->controller->set_cs_timing(spi, setup, hold,
331681059366SAlexandru Ardelean 						      inactive);
331725093bdeSAlexandru Ardelean 
331825093bdeSAlexandru Ardelean 	if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
331925093bdeSAlexandru Ardelean 	    (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
332025093bdeSAlexandru Ardelean 	    (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
332125093bdeSAlexandru Ardelean 		dev_err(&spi->dev,
332225093bdeSAlexandru Ardelean 			"Clock-cycle delays for CS not supported in SW mode\n");
332381059366SAlexandru Ardelean 		return -ENOTSUPP;
3324f1ca9992SSowjanya Komatineni 	}
332525093bdeSAlexandru Ardelean 
332625093bdeSAlexandru Ardelean 	len = sizeof(struct spi_delay);
332725093bdeSAlexandru Ardelean 
332825093bdeSAlexandru Ardelean 	/* copy delays to controller */
332925093bdeSAlexandru Ardelean 	if (setup)
333025093bdeSAlexandru Ardelean 		memcpy(&spi->controller->cs_setup, setup, len);
333125093bdeSAlexandru Ardelean 	else
333225093bdeSAlexandru Ardelean 		memset(&spi->controller->cs_setup, 0, len);
333325093bdeSAlexandru Ardelean 
333425093bdeSAlexandru Ardelean 	if (hold)
333525093bdeSAlexandru Ardelean 		memcpy(&spi->controller->cs_hold, hold, len);
333625093bdeSAlexandru Ardelean 	else
333725093bdeSAlexandru Ardelean 		memset(&spi->controller->cs_hold, 0, len);
333825093bdeSAlexandru Ardelean 
333925093bdeSAlexandru Ardelean 	if (inactive)
334025093bdeSAlexandru Ardelean 		memcpy(&spi->controller->cs_inactive, inactive, len);
334125093bdeSAlexandru Ardelean 	else
334225093bdeSAlexandru Ardelean 		memset(&spi->controller->cs_inactive, 0, len);
334325093bdeSAlexandru Ardelean 
334425093bdeSAlexandru Ardelean 	return 0;
334525093bdeSAlexandru Ardelean }
3346f1ca9992SSowjanya Komatineni EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3347f1ca9992SSowjanya Komatineni 
33486c613f68SAlexandru Ardelean static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
33496c613f68SAlexandru Ardelean 				       struct spi_device *spi)
33506c613f68SAlexandru Ardelean {
33516c613f68SAlexandru Ardelean 	int delay1, delay2;
33526c613f68SAlexandru Ardelean 
33533984d39bSAlexandru Ardelean 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
33546c613f68SAlexandru Ardelean 	if (delay1 < 0)
33556c613f68SAlexandru Ardelean 		return delay1;
33566c613f68SAlexandru Ardelean 
33573984d39bSAlexandru Ardelean 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
33586c613f68SAlexandru Ardelean 	if (delay2 < 0)
33596c613f68SAlexandru Ardelean 		return delay2;
33606c613f68SAlexandru Ardelean 
33616c613f68SAlexandru Ardelean 	if (delay1 < delay2)
33626c613f68SAlexandru Ardelean 		memcpy(&xfer->word_delay, &spi->word_delay,
33636c613f68SAlexandru Ardelean 		       sizeof(xfer->word_delay));
33646c613f68SAlexandru Ardelean 
33656c613f68SAlexandru Ardelean 	return 0;
33666c613f68SAlexandru Ardelean }
33676c613f68SAlexandru Ardelean 
336890808738SMark Brown static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3369cf32b71eSErnst Schwab {
33708caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3371e6811d1dSLaxman Dewangan 	struct spi_transfer *xfer;
33726ea31293SAtsushi Nemoto 	int w_size;
3373cf32b71eSErnst Schwab 
337424a0013aSMark Brown 	if (list_empty(&message->transfers))
337524a0013aSMark Brown 		return -EINVAL;
337624a0013aSMark Brown 
3377cbaa62e0SDavid Lechner 	/* If an SPI controller does not support toggling the CS line on each
337871388b21SDavid Lechner 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
337971388b21SDavid Lechner 	 * for the CS line, we can emulate the CS-per-word hardware function by
3380cbaa62e0SDavid Lechner 	 * splitting transfers into one-word transfers and ensuring that
3381cbaa62e0SDavid Lechner 	 * cs_change is set for each transfer.
3382cbaa62e0SDavid Lechner 	 */
338371388b21SDavid Lechner 	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3384f3186dd8SLinus Walleij 					  spi->cs_gpiod ||
338571388b21SDavid Lechner 					  gpio_is_valid(spi->cs_gpio))) {
3386cbaa62e0SDavid Lechner 		size_t maxsize;
3387cbaa62e0SDavid Lechner 		int ret;
3388cbaa62e0SDavid Lechner 
3389cbaa62e0SDavid Lechner 		maxsize = (spi->bits_per_word + 7) / 8;
3390cbaa62e0SDavid Lechner 
3391cbaa62e0SDavid Lechner 		/* spi_split_transfers_maxsize() requires message->spi */
3392cbaa62e0SDavid Lechner 		message->spi = spi;
3393cbaa62e0SDavid Lechner 
3394cbaa62e0SDavid Lechner 		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3395cbaa62e0SDavid Lechner 						  GFP_KERNEL);
3396cbaa62e0SDavid Lechner 		if (ret)
3397cbaa62e0SDavid Lechner 			return ret;
3398cbaa62e0SDavid Lechner 
3399cbaa62e0SDavid Lechner 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3400cbaa62e0SDavid Lechner 			/* don't change cs_change on the last entry in the list */
3401cbaa62e0SDavid Lechner 			if (list_is_last(&xfer->transfer_list, &message->transfers))
3402cbaa62e0SDavid Lechner 				break;
3403cbaa62e0SDavid Lechner 			xfer->cs_change = 1;
3404cbaa62e0SDavid Lechner 		}
3405cbaa62e0SDavid Lechner 	}
3406cbaa62e0SDavid Lechner 
3407cf32b71eSErnst Schwab 	/* Half-duplex links include original MicroWire, and ones with
3408cf32b71eSErnst Schwab 	 * only one data pin like SPI_3WIRE (switches direction) or where
3409cf32b71eSErnst Schwab 	 * either MOSI or MISO is missing.  They can also be caused by
3410cf32b71eSErnst Schwab 	 * software limitations.
3411cf32b71eSErnst Schwab 	 */
34128caab75fSGeert Uytterhoeven 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
34138caab75fSGeert Uytterhoeven 	    (spi->mode & SPI_3WIRE)) {
34148caab75fSGeert Uytterhoeven 		unsigned flags = ctlr->flags;
3415cf32b71eSErnst Schwab 
3416cf32b71eSErnst Schwab 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3417cf32b71eSErnst Schwab 			if (xfer->rx_buf && xfer->tx_buf)
3418cf32b71eSErnst Schwab 				return -EINVAL;
34198caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3420cf32b71eSErnst Schwab 				return -EINVAL;
34218caab75fSGeert Uytterhoeven 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3422cf32b71eSErnst Schwab 				return -EINVAL;
3423cf32b71eSErnst Schwab 		}
3424cf32b71eSErnst Schwab 	}
3425cf32b71eSErnst Schwab 
3426e6811d1dSLaxman Dewangan 	/**
3427059b8ffeSLaxman Dewangan 	 * Set transfer bits_per_word and max speed as spi device default if
3428059b8ffeSLaxman Dewangan 	 * it is not set for this transfer.
3429f477b7fbSwangyuhang 	 * Set transfer tx_nbits and rx_nbits as single transfer default
3430f477b7fbSwangyuhang 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3431b7bb367aSJonas Bonn 	 * Ensure transfer word_delay is at least as long as that required by
3432b7bb367aSJonas Bonn 	 * device itself.
3433e6811d1dSLaxman Dewangan 	 */
343477e80588SMartin Sperl 	message->frame_length = 0;
3435e6811d1dSLaxman Dewangan 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
34365d7e2b5eSMartin Sperl 		xfer->effective_speed_hz = 0;
3437078726ceSSourav Poddar 		message->frame_length += xfer->len;
3438e6811d1dSLaxman Dewangan 		if (!xfer->bits_per_word)
3439e6811d1dSLaxman Dewangan 			xfer->bits_per_word = spi->bits_per_word;
3440a6f87fadSAxel Lin 
3441a6f87fadSAxel Lin 		if (!xfer->speed_hz)
3442059b8ffeSLaxman Dewangan 			xfer->speed_hz = spi->max_speed_hz;
3443a6f87fadSAxel Lin 
34448caab75fSGeert Uytterhoeven 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
34458caab75fSGeert Uytterhoeven 			xfer->speed_hz = ctlr->max_speed_hz;
344656ede94aSGabor Juhos 
34478caab75fSGeert Uytterhoeven 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3448543bb255SStephen Warren 			return -EINVAL;
3449a2fd4f9fSMark Brown 
34504d94bd21SIvan T. Ivanov 		/*
34514d94bd21SIvan T. Ivanov 		 * SPI transfer length should be multiple of SPI word size
34524d94bd21SIvan T. Ivanov 		 * where SPI word size should be power-of-two multiple
34534d94bd21SIvan T. Ivanov 		 */
34544d94bd21SIvan T. Ivanov 		if (xfer->bits_per_word <= 8)
34554d94bd21SIvan T. Ivanov 			w_size = 1;
34564d94bd21SIvan T. Ivanov 		else if (xfer->bits_per_word <= 16)
34574d94bd21SIvan T. Ivanov 			w_size = 2;
34584d94bd21SIvan T. Ivanov 		else
34594d94bd21SIvan T. Ivanov 			w_size = 4;
34604d94bd21SIvan T. Ivanov 
34614d94bd21SIvan T. Ivanov 		/* No partial transfers accepted */
34626ea31293SAtsushi Nemoto 		if (xfer->len % w_size)
34634d94bd21SIvan T. Ivanov 			return -EINVAL;
34644d94bd21SIvan T. Ivanov 
34658caab75fSGeert Uytterhoeven 		if (xfer->speed_hz && ctlr->min_speed_hz &&
34668caab75fSGeert Uytterhoeven 		    xfer->speed_hz < ctlr->min_speed_hz)
3467a2fd4f9fSMark Brown 			return -EINVAL;
3468f477b7fbSwangyuhang 
3469f477b7fbSwangyuhang 		if (xfer->tx_buf && !xfer->tx_nbits)
3470f477b7fbSwangyuhang 			xfer->tx_nbits = SPI_NBITS_SINGLE;
3471f477b7fbSwangyuhang 		if (xfer->rx_buf && !xfer->rx_nbits)
3472f477b7fbSwangyuhang 			xfer->rx_nbits = SPI_NBITS_SINGLE;
3473f477b7fbSwangyuhang 		/* check transfer tx/rx_nbits:
34741afd9989SGeert Uytterhoeven 		 * 1. check the value matches one of single, dual and quad
34751afd9989SGeert Uytterhoeven 		 * 2. check tx/rx_nbits match the mode in spi_device
3476f477b7fbSwangyuhang 		 */
3477db90a441SSourav Poddar 		if (xfer->tx_buf) {
3478f477b7fbSwangyuhang 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3479f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_DUAL &&
3480f477b7fbSwangyuhang 				xfer->tx_nbits != SPI_NBITS_QUAD)
3481a2fd4f9fSMark Brown 				return -EINVAL;
3482f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3483f477b7fbSwangyuhang 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3484f477b7fbSwangyuhang 				return -EINVAL;
3485f477b7fbSwangyuhang 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3486f477b7fbSwangyuhang 				!(spi->mode & SPI_TX_QUAD))
3487f477b7fbSwangyuhang 				return -EINVAL;
3488db90a441SSourav Poddar 		}
3489f477b7fbSwangyuhang 		/* check transfer rx_nbits */
3490db90a441SSourav Poddar 		if (xfer->rx_buf) {
3491f477b7fbSwangyuhang 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3492f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_DUAL &&
3493f477b7fbSwangyuhang 				xfer->rx_nbits != SPI_NBITS_QUAD)
3494f477b7fbSwangyuhang 				return -EINVAL;
3495f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3496f477b7fbSwangyuhang 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3497f477b7fbSwangyuhang 				return -EINVAL;
3498f477b7fbSwangyuhang 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3499f477b7fbSwangyuhang 				!(spi->mode & SPI_RX_QUAD))
3500f477b7fbSwangyuhang 				return -EINVAL;
3501e6811d1dSLaxman Dewangan 		}
3502b7bb367aSJonas Bonn 
35036c613f68SAlexandru Ardelean 		if (_spi_xfer_word_delay_update(xfer, spi))
35046c613f68SAlexandru Ardelean 			return -EINVAL;
3505e6811d1dSLaxman Dewangan 	}
3506e6811d1dSLaxman Dewangan 
3507cf32b71eSErnst Schwab 	message->status = -EINPROGRESS;
350890808738SMark Brown 
350990808738SMark Brown 	return 0;
351090808738SMark Brown }
351190808738SMark Brown 
351290808738SMark Brown static int __spi_async(struct spi_device *spi, struct spi_message *message)
351390808738SMark Brown {
35148caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3515b42faeeeSVladimir Oltean 	struct spi_transfer *xfer;
351690808738SMark Brown 
3517b5932f5cSBoris Brezillon 	/*
3518b5932f5cSBoris Brezillon 	 * Some controllers do not support doing regular SPI transfers. Return
3519b5932f5cSBoris Brezillon 	 * ENOTSUPP when this is the case.
3520b5932f5cSBoris Brezillon 	 */
3521b5932f5cSBoris Brezillon 	if (!ctlr->transfer)
3522b5932f5cSBoris Brezillon 		return -ENOTSUPP;
3523b5932f5cSBoris Brezillon 
352490808738SMark Brown 	message->spi = spi;
352590808738SMark Brown 
35268caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3527eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3528eca2ebc7SMartin Sperl 
352990808738SMark Brown 	trace_spi_message_submit(message);
353090808738SMark Brown 
3531b42faeeeSVladimir Oltean 	if (!ctlr->ptp_sts_supported) {
3532b42faeeeSVladimir Oltean 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3533b42faeeeSVladimir Oltean 			xfer->ptp_sts_word_pre = 0;
3534b42faeeeSVladimir Oltean 			ptp_read_system_prets(xfer->ptp_sts);
3535b42faeeeSVladimir Oltean 		}
3536b42faeeeSVladimir Oltean 	}
3537b42faeeeSVladimir Oltean 
35388caab75fSGeert Uytterhoeven 	return ctlr->transfer(spi, message);
3539cf32b71eSErnst Schwab }
3540cf32b71eSErnst Schwab 
3541568d0697SDavid Brownell /**
3542568d0697SDavid Brownell  * spi_async - asynchronous SPI transfer
3543568d0697SDavid Brownell  * @spi: device with which data will be exchanged
3544568d0697SDavid Brownell  * @message: describes the data transfers, including completion callback
3545568d0697SDavid Brownell  * Context: any (irqs may be blocked, etc)
3546568d0697SDavid Brownell  *
3547568d0697SDavid Brownell  * This call may be used in_irq and other contexts which can't sleep,
3548568d0697SDavid Brownell  * as well as from task contexts which can sleep.
3549568d0697SDavid Brownell  *
3550568d0697SDavid Brownell  * The completion callback is invoked in a context which can't sleep.
3551568d0697SDavid Brownell  * Before that invocation, the value of message->status is undefined.
3552568d0697SDavid Brownell  * When the callback is issued, message->status holds either zero (to
3553568d0697SDavid Brownell  * indicate complete success) or a negative error code.  After that
3554568d0697SDavid Brownell  * callback returns, the driver which issued the transfer request may
3555568d0697SDavid Brownell  * deallocate the associated memory; it's no longer in use by any SPI
3556568d0697SDavid Brownell  * core or controller driver code.
3557568d0697SDavid Brownell  *
3558568d0697SDavid Brownell  * Note that although all messages to a spi_device are handled in
3559568d0697SDavid Brownell  * FIFO order, messages may go to different devices in other orders.
3560568d0697SDavid Brownell  * Some device might be higher priority, or have various "hard" access
3561568d0697SDavid Brownell  * time requirements, for example.
3562568d0697SDavid Brownell  *
3563568d0697SDavid Brownell  * On detection of any fault during the transfer, processing of
3564568d0697SDavid Brownell  * the entire message is aborted, and the device is deselected.
3565568d0697SDavid Brownell  * Until returning from the associated message completion callback,
3566568d0697SDavid Brownell  * no other spi_message queued to that device will be processed.
3567568d0697SDavid Brownell  * (This rule applies equally to all the synchronous transfer calls,
3568568d0697SDavid Brownell  * which are wrappers around this core asynchronous primitive.)
356997d56dc6SJavier Martinez Canillas  *
357097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3571568d0697SDavid Brownell  */
3572568d0697SDavid Brownell int spi_async(struct spi_device *spi, struct spi_message *message)
3573568d0697SDavid Brownell {
35748caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3575cf32b71eSErnst Schwab 	int ret;
3576cf32b71eSErnst Schwab 	unsigned long flags;
3577568d0697SDavid Brownell 
357890808738SMark Brown 	ret = __spi_validate(spi, message);
357990808738SMark Brown 	if (ret != 0)
358090808738SMark Brown 		return ret;
358190808738SMark Brown 
35828caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3583568d0697SDavid Brownell 
35848caab75fSGeert Uytterhoeven 	if (ctlr->bus_lock_flag)
3585cf32b71eSErnst Schwab 		ret = -EBUSY;
3586cf32b71eSErnst Schwab 	else
3587cf32b71eSErnst Schwab 		ret = __spi_async(spi, message);
3588568d0697SDavid Brownell 
35898caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3590cf32b71eSErnst Schwab 
3591cf32b71eSErnst Schwab 	return ret;
3592568d0697SDavid Brownell }
3593568d0697SDavid Brownell EXPORT_SYMBOL_GPL(spi_async);
3594568d0697SDavid Brownell 
3595cf32b71eSErnst Schwab /**
3596cf32b71eSErnst Schwab  * spi_async_locked - version of spi_async with exclusive bus usage
3597cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
3598cf32b71eSErnst Schwab  * @message: describes the data transfers, including completion callback
3599cf32b71eSErnst Schwab  * Context: any (irqs may be blocked, etc)
3600cf32b71eSErnst Schwab  *
3601cf32b71eSErnst Schwab  * This call may be used in_irq and other contexts which can't sleep,
3602cf32b71eSErnst Schwab  * as well as from task contexts which can sleep.
3603cf32b71eSErnst Schwab  *
3604cf32b71eSErnst Schwab  * The completion callback is invoked in a context which can't sleep.
3605cf32b71eSErnst Schwab  * Before that invocation, the value of message->status is undefined.
3606cf32b71eSErnst Schwab  * When the callback is issued, message->status holds either zero (to
3607cf32b71eSErnst Schwab  * indicate complete success) or a negative error code.  After that
3608cf32b71eSErnst Schwab  * callback returns, the driver which issued the transfer request may
3609cf32b71eSErnst Schwab  * deallocate the associated memory; it's no longer in use by any SPI
3610cf32b71eSErnst Schwab  * core or controller driver code.
3611cf32b71eSErnst Schwab  *
3612cf32b71eSErnst Schwab  * Note that although all messages to a spi_device are handled in
3613cf32b71eSErnst Schwab  * FIFO order, messages may go to different devices in other orders.
3614cf32b71eSErnst Schwab  * Some device might be higher priority, or have various "hard" access
3615cf32b71eSErnst Schwab  * time requirements, for example.
3616cf32b71eSErnst Schwab  *
3617cf32b71eSErnst Schwab  * On detection of any fault during the transfer, processing of
3618cf32b71eSErnst Schwab  * the entire message is aborted, and the device is deselected.
3619cf32b71eSErnst Schwab  * Until returning from the associated message completion callback,
3620cf32b71eSErnst Schwab  * no other spi_message queued to that device will be processed.
3621cf32b71eSErnst Schwab  * (This rule applies equally to all the synchronous transfer calls,
3622cf32b71eSErnst Schwab  * which are wrappers around this core asynchronous primitive.)
362397d56dc6SJavier Martinez Canillas  *
362497d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3625cf32b71eSErnst Schwab  */
3626cf32b71eSErnst Schwab int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3627cf32b71eSErnst Schwab {
36288caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
3629cf32b71eSErnst Schwab 	int ret;
3630cf32b71eSErnst Schwab 	unsigned long flags;
3631cf32b71eSErnst Schwab 
363290808738SMark Brown 	ret = __spi_validate(spi, message);
363390808738SMark Brown 	if (ret != 0)
363490808738SMark Brown 		return ret;
363590808738SMark Brown 
36368caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3637cf32b71eSErnst Schwab 
3638cf32b71eSErnst Schwab 	ret = __spi_async(spi, message);
3639cf32b71eSErnst Schwab 
36408caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3641cf32b71eSErnst Schwab 
3642cf32b71eSErnst Schwab 	return ret;
3643cf32b71eSErnst Schwab 
3644cf32b71eSErnst Schwab }
3645cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_async_locked);
3646cf32b71eSErnst Schwab 
36477d077197SDavid Brownell /*-------------------------------------------------------------------------*/
36487d077197SDavid Brownell 
36498caab75fSGeert Uytterhoeven /* Utility methods for SPI protocol drivers, layered on
36507d077197SDavid Brownell  * top of the core.  Some other utility methods are defined as
36517d077197SDavid Brownell  * inline functions.
36527d077197SDavid Brownell  */
36537d077197SDavid Brownell 
36545d870c8eSAndrew Morton static void spi_complete(void *arg)
36555d870c8eSAndrew Morton {
36565d870c8eSAndrew Morton 	complete(arg);
36575d870c8eSAndrew Morton }
36585d870c8eSAndrew Morton 
3659ef4d96ecSMark Brown static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3660cf32b71eSErnst Schwab {
3661cf32b71eSErnst Schwab 	DECLARE_COMPLETION_ONSTACK(done);
3662cf32b71eSErnst Schwab 	int status;
36638caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr = spi->controller;
36640461a414SMark Brown 	unsigned long flags;
36650461a414SMark Brown 
36660461a414SMark Brown 	status = __spi_validate(spi, message);
36670461a414SMark Brown 	if (status != 0)
36680461a414SMark Brown 		return status;
3669cf32b71eSErnst Schwab 
3670cf32b71eSErnst Schwab 	message->complete = spi_complete;
3671cf32b71eSErnst Schwab 	message->context = &done;
36720461a414SMark Brown 	message->spi = spi;
3673cf32b71eSErnst Schwab 
36748caab75fSGeert Uytterhoeven 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3675eca2ebc7SMartin Sperl 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3676eca2ebc7SMartin Sperl 
36770461a414SMark Brown 	/* If we're not using the legacy transfer method then we will
36780461a414SMark Brown 	 * try to transfer in the calling context so special case.
36790461a414SMark Brown 	 * This code would be less tricky if we could remove the
36800461a414SMark Brown 	 * support for driver implemented message queues.
36810461a414SMark Brown 	 */
36828caab75fSGeert Uytterhoeven 	if (ctlr->transfer == spi_queued_transfer) {
36838caab75fSGeert Uytterhoeven 		spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
36840461a414SMark Brown 
36850461a414SMark Brown 		trace_spi_message_submit(message);
36860461a414SMark Brown 
36870461a414SMark Brown 		status = __spi_queued_transfer(spi, message, false);
36880461a414SMark Brown 
36898caab75fSGeert Uytterhoeven 		spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
36900461a414SMark Brown 	} else {
3691cf32b71eSErnst Schwab 		status = spi_async_locked(spi, message);
36920461a414SMark Brown 	}
3693cf32b71eSErnst Schwab 
3694cf32b71eSErnst Schwab 	if (status == 0) {
36950461a414SMark Brown 		/* Push out the messages in the calling context if we
36960461a414SMark Brown 		 * can.
36970461a414SMark Brown 		 */
36988caab75fSGeert Uytterhoeven 		if (ctlr->transfer == spi_queued_transfer) {
36998caab75fSGeert Uytterhoeven 			SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3700eca2ebc7SMartin Sperl 						       spi_sync_immediate);
3701eca2ebc7SMartin Sperl 			SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3702eca2ebc7SMartin Sperl 						       spi_sync_immediate);
37038caab75fSGeert Uytterhoeven 			__spi_pump_messages(ctlr, false);
3704eca2ebc7SMartin Sperl 		}
37050461a414SMark Brown 
3706cf32b71eSErnst Schwab 		wait_for_completion(&done);
3707cf32b71eSErnst Schwab 		status = message->status;
3708cf32b71eSErnst Schwab 	}
3709cf32b71eSErnst Schwab 	message->context = NULL;
3710cf32b71eSErnst Schwab 	return status;
3711cf32b71eSErnst Schwab }
3712cf32b71eSErnst Schwab 
37138ae12a0dSDavid Brownell /**
37148ae12a0dSDavid Brownell  * spi_sync - blocking/synchronous SPI data transfers
37158ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
37168ae12a0dSDavid Brownell  * @message: describes the data transfers
371733e34dc6SDavid Brownell  * Context: can sleep
37188ae12a0dSDavid Brownell  *
37198ae12a0dSDavid Brownell  * This call may only be used from a context that may sleep.  The sleep
37208ae12a0dSDavid Brownell  * is non-interruptible, and has no timeout.  Low-overhead controller
37218ae12a0dSDavid Brownell  * drivers may DMA directly into and out of the message buffers.
37228ae12a0dSDavid Brownell  *
37238ae12a0dSDavid Brownell  * Note that the SPI device's chip select is active during the message,
37248ae12a0dSDavid Brownell  * and then is normally disabled between messages.  Drivers for some
37258ae12a0dSDavid Brownell  * frequently-used devices may want to minimize costs of selecting a chip,
37268ae12a0dSDavid Brownell  * by leaving it selected in anticipation that the next message will go
37278ae12a0dSDavid Brownell  * to the same chip.  (That may increase power usage.)
37288ae12a0dSDavid Brownell  *
37290c868461SDavid Brownell  * Also, the caller is guaranteeing that the memory associated with the
37300c868461SDavid Brownell  * message will not be freed before this call returns.
37310c868461SDavid Brownell  *
373297d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
37338ae12a0dSDavid Brownell  */
37348ae12a0dSDavid Brownell int spi_sync(struct spi_device *spi, struct spi_message *message)
37358ae12a0dSDavid Brownell {
3736ef4d96ecSMark Brown 	int ret;
3737ef4d96ecSMark Brown 
37388caab75fSGeert Uytterhoeven 	mutex_lock(&spi->controller->bus_lock_mutex);
3739ef4d96ecSMark Brown 	ret = __spi_sync(spi, message);
37408caab75fSGeert Uytterhoeven 	mutex_unlock(&spi->controller->bus_lock_mutex);
3741ef4d96ecSMark Brown 
3742ef4d96ecSMark Brown 	return ret;
37438ae12a0dSDavid Brownell }
37448ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_sync);
37458ae12a0dSDavid Brownell 
3746cf32b71eSErnst Schwab /**
3747cf32b71eSErnst Schwab  * spi_sync_locked - version of spi_sync with exclusive bus usage
3748cf32b71eSErnst Schwab  * @spi: device with which data will be exchanged
3749cf32b71eSErnst Schwab  * @message: describes the data transfers
3750cf32b71eSErnst Schwab  * Context: can sleep
3751cf32b71eSErnst Schwab  *
3752cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3753cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.  Low-overhead controller
3754cf32b71eSErnst Schwab  * drivers may DMA directly into and out of the message buffers.
3755cf32b71eSErnst Schwab  *
3756cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
375725985edcSLucas De Marchi  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3758cf32b71eSErnst Schwab  * be released by a spi_bus_unlock call when the exclusive access is over.
3759cf32b71eSErnst Schwab  *
376097d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
3761cf32b71eSErnst Schwab  */
3762cf32b71eSErnst Schwab int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3763cf32b71eSErnst Schwab {
3764ef4d96ecSMark Brown 	return __spi_sync(spi, message);
3765cf32b71eSErnst Schwab }
3766cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_sync_locked);
3767cf32b71eSErnst Schwab 
3768cf32b71eSErnst Schwab /**
3769cf32b71eSErnst Schwab  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
37708caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that should be locked for exclusive bus access
3771cf32b71eSErnst Schwab  * Context: can sleep
3772cf32b71eSErnst Schwab  *
3773cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3774cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
3775cf32b71eSErnst Schwab  *
3776cf32b71eSErnst Schwab  * This call should be used by drivers that require exclusive access to the
3777cf32b71eSErnst Schwab  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3778cf32b71eSErnst Schwab  * exclusive access is over. Data transfer must be done by spi_sync_locked
3779cf32b71eSErnst Schwab  * and spi_async_locked calls when the SPI bus lock is held.
3780cf32b71eSErnst Schwab  *
378197d56dc6SJavier Martinez Canillas  * Return: always zero.
3782cf32b71eSErnst Schwab  */
37838caab75fSGeert Uytterhoeven int spi_bus_lock(struct spi_controller *ctlr)
3784cf32b71eSErnst Schwab {
3785cf32b71eSErnst Schwab 	unsigned long flags;
3786cf32b71eSErnst Schwab 
37878caab75fSGeert Uytterhoeven 	mutex_lock(&ctlr->bus_lock_mutex);
3788cf32b71eSErnst Schwab 
37898caab75fSGeert Uytterhoeven 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
37908caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 1;
37918caab75fSGeert Uytterhoeven 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3792cf32b71eSErnst Schwab 
3793cf32b71eSErnst Schwab 	/* mutex remains locked until spi_bus_unlock is called */
3794cf32b71eSErnst Schwab 
3795cf32b71eSErnst Schwab 	return 0;
3796cf32b71eSErnst Schwab }
3797cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_lock);
3798cf32b71eSErnst Schwab 
3799cf32b71eSErnst Schwab /**
3800cf32b71eSErnst Schwab  * spi_bus_unlock - release the lock for exclusive SPI bus usage
38018caab75fSGeert Uytterhoeven  * @ctlr: SPI bus master that was locked for exclusive bus access
3802cf32b71eSErnst Schwab  * Context: can sleep
3803cf32b71eSErnst Schwab  *
3804cf32b71eSErnst Schwab  * This call may only be used from a context that may sleep.  The sleep
3805cf32b71eSErnst Schwab  * is non-interruptible, and has no timeout.
3806cf32b71eSErnst Schwab  *
3807cf32b71eSErnst Schwab  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3808cf32b71eSErnst Schwab  * call.
3809cf32b71eSErnst Schwab  *
381097d56dc6SJavier Martinez Canillas  * Return: always zero.
3811cf32b71eSErnst Schwab  */
38128caab75fSGeert Uytterhoeven int spi_bus_unlock(struct spi_controller *ctlr)
3813cf32b71eSErnst Schwab {
38148caab75fSGeert Uytterhoeven 	ctlr->bus_lock_flag = 0;
3815cf32b71eSErnst Schwab 
38168caab75fSGeert Uytterhoeven 	mutex_unlock(&ctlr->bus_lock_mutex);
3817cf32b71eSErnst Schwab 
3818cf32b71eSErnst Schwab 	return 0;
3819cf32b71eSErnst Schwab }
3820cf32b71eSErnst Schwab EXPORT_SYMBOL_GPL(spi_bus_unlock);
3821cf32b71eSErnst Schwab 
3822a9948b61SDavid Brownell /* portable code must never pass more than 32 bytes */
3823a9948b61SDavid Brownell #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
38248ae12a0dSDavid Brownell 
38258ae12a0dSDavid Brownell static u8	*buf;
38268ae12a0dSDavid Brownell 
38278ae12a0dSDavid Brownell /**
38288ae12a0dSDavid Brownell  * spi_write_then_read - SPI synchronous write followed by read
38298ae12a0dSDavid Brownell  * @spi: device with which data will be exchanged
38308ae12a0dSDavid Brownell  * @txbuf: data to be written (need not be dma-safe)
38318ae12a0dSDavid Brownell  * @n_tx: size of txbuf, in bytes
383227570497SJiri Pirko  * @rxbuf: buffer into which data will be read (need not be dma-safe)
383327570497SJiri Pirko  * @n_rx: size of rxbuf, in bytes
383433e34dc6SDavid Brownell  * Context: can sleep
38358ae12a0dSDavid Brownell  *
38368ae12a0dSDavid Brownell  * This performs a half duplex MicroWire style transaction with the
38378ae12a0dSDavid Brownell  * device, sending txbuf and then reading rxbuf.  The return value
38388ae12a0dSDavid Brownell  * is zero for success, else a negative errno status code.
3839b885244eSDavid Brownell  * This call may only be used from a context that may sleep.
38408ae12a0dSDavid Brownell  *
38410c868461SDavid Brownell  * Parameters to this routine are always copied using a small buffer;
384233e34dc6SDavid Brownell  * portable code should never use this for more than 32 bytes.
384333e34dc6SDavid Brownell  * Performance-sensitive or bulk transfer code should instead use
38440c868461SDavid Brownell  * spi_{async,sync}() calls with dma-safe buffers.
384597d56dc6SJavier Martinez Canillas  *
384697d56dc6SJavier Martinez Canillas  * Return: zero on success, else a negative error code.
38478ae12a0dSDavid Brownell  */
38488ae12a0dSDavid Brownell int spi_write_then_read(struct spi_device *spi,
38490c4a1590SMark Brown 		const void *txbuf, unsigned n_tx,
38500c4a1590SMark Brown 		void *rxbuf, unsigned n_rx)
38518ae12a0dSDavid Brownell {
3852068f4070SDavid Brownell 	static DEFINE_MUTEX(lock);
38538ae12a0dSDavid Brownell 
38548ae12a0dSDavid Brownell 	int			status;
38558ae12a0dSDavid Brownell 	struct spi_message	message;
3856bdff549eSDavid Brownell 	struct spi_transfer	x[2];
38578ae12a0dSDavid Brownell 	u8			*local_buf;
38588ae12a0dSDavid Brownell 
3859b3a223eeSMark Brown 	/* Use preallocated DMA-safe buffer if we can.  We can't avoid
3860b3a223eeSMark Brown 	 * copying here, (as a pure convenience thing), but we can
3861b3a223eeSMark Brown 	 * keep heap costs out of the hot path unless someone else is
3862b3a223eeSMark Brown 	 * using the pre-allocated buffer or the transfer is too large.
38638ae12a0dSDavid Brownell 	 */
3864b3a223eeSMark Brown 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
38652cd94c8aSMark Brown 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
38662cd94c8aSMark Brown 				    GFP_KERNEL | GFP_DMA);
3867b3a223eeSMark Brown 		if (!local_buf)
3868b3a223eeSMark Brown 			return -ENOMEM;
3869b3a223eeSMark Brown 	} else {
3870b3a223eeSMark Brown 		local_buf = buf;
3871b3a223eeSMark Brown 	}
38728ae12a0dSDavid Brownell 
38738275c642SVitaly Wool 	spi_message_init(&message);
38745fe5f05eSJingoo Han 	memset(x, 0, sizeof(x));
3875bdff549eSDavid Brownell 	if (n_tx) {
3876bdff549eSDavid Brownell 		x[0].len = n_tx;
3877bdff549eSDavid Brownell 		spi_message_add_tail(&x[0], &message);
3878bdff549eSDavid Brownell 	}
3879bdff549eSDavid Brownell 	if (n_rx) {
3880bdff549eSDavid Brownell 		x[1].len = n_rx;
3881bdff549eSDavid Brownell 		spi_message_add_tail(&x[1], &message);
3882bdff549eSDavid Brownell 	}
38838275c642SVitaly Wool 
38848ae12a0dSDavid Brownell 	memcpy(local_buf, txbuf, n_tx);
3885bdff549eSDavid Brownell 	x[0].tx_buf = local_buf;
3886bdff549eSDavid Brownell 	x[1].rx_buf = local_buf + n_tx;
38878ae12a0dSDavid Brownell 
38888ae12a0dSDavid Brownell 	/* do the i/o */
38898ae12a0dSDavid Brownell 	status = spi_sync(spi, &message);
38909b938b74SMarc Pignat 	if (status == 0)
3891bdff549eSDavid Brownell 		memcpy(rxbuf, x[1].rx_buf, n_rx);
38928ae12a0dSDavid Brownell 
3893bdff549eSDavid Brownell 	if (x[0].tx_buf == buf)
3894068f4070SDavid Brownell 		mutex_unlock(&lock);
38958ae12a0dSDavid Brownell 	else
38968ae12a0dSDavid Brownell 		kfree(local_buf);
38978ae12a0dSDavid Brownell 
38988ae12a0dSDavid Brownell 	return status;
38998ae12a0dSDavid Brownell }
39008ae12a0dSDavid Brownell EXPORT_SYMBOL_GPL(spi_write_then_read);
39018ae12a0dSDavid Brownell 
39028ae12a0dSDavid Brownell /*-------------------------------------------------------------------------*/
39038ae12a0dSDavid Brownell 
39045f143af7SMarco Felsch #if IS_ENABLED(CONFIG_OF)
3905ce79d54aSPantelis Antoniou /* must call put_device() when done with returned spi_device device */
39065f143af7SMarco Felsch struct spi_device *of_find_spi_device_by_node(struct device_node *node)
3907ce79d54aSPantelis Antoniou {
3908cfba5de9SSuzuki K Poulose 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
3909cfba5de9SSuzuki K Poulose 
3910ce79d54aSPantelis Antoniou 	return dev ? to_spi_device(dev) : NULL;
3911ce79d54aSPantelis Antoniou }
39125f143af7SMarco Felsch EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
39135f143af7SMarco Felsch #endif /* IS_ENABLED(CONFIG_OF) */
3914ce79d54aSPantelis Antoniou 
39155f143af7SMarco Felsch #if IS_ENABLED(CONFIG_OF_DYNAMIC)
39168caab75fSGeert Uytterhoeven /* the spi controllers are not using spi_bus, so we find it with another way */
39178caab75fSGeert Uytterhoeven static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
3918ce79d54aSPantelis Antoniou {
3919ce79d54aSPantelis Antoniou 	struct device *dev;
3920ce79d54aSPantelis Antoniou 
3921cfba5de9SSuzuki K Poulose 	dev = class_find_device_by_of_node(&spi_master_class, node);
39226c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
3923cfba5de9SSuzuki K Poulose 		dev = class_find_device_by_of_node(&spi_slave_class, node);
3924ce79d54aSPantelis Antoniou 	if (!dev)
3925ce79d54aSPantelis Antoniou 		return NULL;
3926ce79d54aSPantelis Antoniou 
3927ce79d54aSPantelis Antoniou 	/* reference got in class_find_device */
39288caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
3929ce79d54aSPantelis Antoniou }
3930ce79d54aSPantelis Antoniou 
3931ce79d54aSPantelis Antoniou static int of_spi_notify(struct notifier_block *nb, unsigned long action,
3932ce79d54aSPantelis Antoniou 			 void *arg)
3933ce79d54aSPantelis Antoniou {
3934ce79d54aSPantelis Antoniou 	struct of_reconfig_data *rd = arg;
39358caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
3936ce79d54aSPantelis Antoniou 	struct spi_device *spi;
3937ce79d54aSPantelis Antoniou 
3938ce79d54aSPantelis Antoniou 	switch (of_reconfig_get_state_change(action, arg)) {
3939ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_ADD:
39408caab75fSGeert Uytterhoeven 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
39418caab75fSGeert Uytterhoeven 		if (ctlr == NULL)
3942ce79d54aSPantelis Antoniou 			return NOTIFY_OK;	/* not for us */
3943ce79d54aSPantelis Antoniou 
3944bd6c1644SGeert Uytterhoeven 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
39458caab75fSGeert Uytterhoeven 			put_device(&ctlr->dev);
3946bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
3947bd6c1644SGeert Uytterhoeven 		}
3948bd6c1644SGeert Uytterhoeven 
39498caab75fSGeert Uytterhoeven 		spi = of_register_spi_device(ctlr, rd->dn);
39508caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
3951ce79d54aSPantelis Antoniou 
3952ce79d54aSPantelis Antoniou 		if (IS_ERR(spi)) {
395325c56c88SRob Herring 			pr_err("%s: failed to create for '%pOF'\n",
395425c56c88SRob Herring 					__func__, rd->dn);
3955e0af98a7SRalf Ramsauer 			of_node_clear_flag(rd->dn, OF_POPULATED);
3956ce79d54aSPantelis Antoniou 			return notifier_from_errno(PTR_ERR(spi));
3957ce79d54aSPantelis Antoniou 		}
3958ce79d54aSPantelis Antoniou 		break;
3959ce79d54aSPantelis Antoniou 
3960ce79d54aSPantelis Antoniou 	case OF_RECONFIG_CHANGE_REMOVE:
3961bd6c1644SGeert Uytterhoeven 		/* already depopulated? */
3962bd6c1644SGeert Uytterhoeven 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
3963bd6c1644SGeert Uytterhoeven 			return NOTIFY_OK;
3964bd6c1644SGeert Uytterhoeven 
3965ce79d54aSPantelis Antoniou 		/* find our device by node */
3966ce79d54aSPantelis Antoniou 		spi = of_find_spi_device_by_node(rd->dn);
3967ce79d54aSPantelis Antoniou 		if (spi == NULL)
3968ce79d54aSPantelis Antoniou 			return NOTIFY_OK;	/* no? not meant for us */
3969ce79d54aSPantelis Antoniou 
3970ce79d54aSPantelis Antoniou 		/* unregister takes one ref away */
3971ce79d54aSPantelis Antoniou 		spi_unregister_device(spi);
3972ce79d54aSPantelis Antoniou 
3973ce79d54aSPantelis Antoniou 		/* and put the reference of the find */
3974ce79d54aSPantelis Antoniou 		put_device(&spi->dev);
3975ce79d54aSPantelis Antoniou 		break;
3976ce79d54aSPantelis Antoniou 	}
3977ce79d54aSPantelis Antoniou 
3978ce79d54aSPantelis Antoniou 	return NOTIFY_OK;
3979ce79d54aSPantelis Antoniou }
3980ce79d54aSPantelis Antoniou 
3981ce79d54aSPantelis Antoniou static struct notifier_block spi_of_notifier = {
3982ce79d54aSPantelis Antoniou 	.notifier_call = of_spi_notify,
3983ce79d54aSPantelis Antoniou };
3984ce79d54aSPantelis Antoniou #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3985ce79d54aSPantelis Antoniou extern struct notifier_block spi_of_notifier;
3986ce79d54aSPantelis Antoniou #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
3987ce79d54aSPantelis Antoniou 
39887f24467fSOctavian Purdila #if IS_ENABLED(CONFIG_ACPI)
39898caab75fSGeert Uytterhoeven static int spi_acpi_controller_match(struct device *dev, const void *data)
39907f24467fSOctavian Purdila {
39917f24467fSOctavian Purdila 	return ACPI_COMPANION(dev->parent) == data;
39927f24467fSOctavian Purdila }
39937f24467fSOctavian Purdila 
39948caab75fSGeert Uytterhoeven static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
39957f24467fSOctavian Purdila {
39967f24467fSOctavian Purdila 	struct device *dev;
39977f24467fSOctavian Purdila 
39987f24467fSOctavian Purdila 	dev = class_find_device(&spi_master_class, NULL, adev,
39998caab75fSGeert Uytterhoeven 				spi_acpi_controller_match);
40006c364062SGeert Uytterhoeven 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
40016c364062SGeert Uytterhoeven 		dev = class_find_device(&spi_slave_class, NULL, adev,
40028caab75fSGeert Uytterhoeven 					spi_acpi_controller_match);
40037f24467fSOctavian Purdila 	if (!dev)
40047f24467fSOctavian Purdila 		return NULL;
40057f24467fSOctavian Purdila 
40068caab75fSGeert Uytterhoeven 	return container_of(dev, struct spi_controller, dev);
40077f24467fSOctavian Purdila }
40087f24467fSOctavian Purdila 
40097f24467fSOctavian Purdila static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
40107f24467fSOctavian Purdila {
40117f24467fSOctavian Purdila 	struct device *dev;
40127f24467fSOctavian Purdila 
401300500147SSuzuki K Poulose 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
40147f24467fSOctavian Purdila 	return dev ? to_spi_device(dev) : NULL;
40157f24467fSOctavian Purdila }
40167f24467fSOctavian Purdila 
40177f24467fSOctavian Purdila static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
40187f24467fSOctavian Purdila 			   void *arg)
40197f24467fSOctavian Purdila {
40207f24467fSOctavian Purdila 	struct acpi_device *adev = arg;
40218caab75fSGeert Uytterhoeven 	struct spi_controller *ctlr;
40227f24467fSOctavian Purdila 	struct spi_device *spi;
40237f24467fSOctavian Purdila 
40247f24467fSOctavian Purdila 	switch (value) {
40257f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_ADD:
40268caab75fSGeert Uytterhoeven 		ctlr = acpi_spi_find_controller_by_adev(adev->parent);
40278caab75fSGeert Uytterhoeven 		if (!ctlr)
40287f24467fSOctavian Purdila 			break;
40297f24467fSOctavian Purdila 
40308caab75fSGeert Uytterhoeven 		acpi_register_spi_device(ctlr, adev);
40318caab75fSGeert Uytterhoeven 		put_device(&ctlr->dev);
40327f24467fSOctavian Purdila 		break;
40337f24467fSOctavian Purdila 	case ACPI_RECONFIG_DEVICE_REMOVE:
40347f24467fSOctavian Purdila 		if (!acpi_device_enumerated(adev))
40357f24467fSOctavian Purdila 			break;
40367f24467fSOctavian Purdila 
40377f24467fSOctavian Purdila 		spi = acpi_spi_find_device_by_adev(adev);
40387f24467fSOctavian Purdila 		if (!spi)
40397f24467fSOctavian Purdila 			break;
40407f24467fSOctavian Purdila 
40417f24467fSOctavian Purdila 		spi_unregister_device(spi);
40427f24467fSOctavian Purdila 		put_device(&spi->dev);
40437f24467fSOctavian Purdila 		break;
40447f24467fSOctavian Purdila 	}
40457f24467fSOctavian Purdila 
40467f24467fSOctavian Purdila 	return NOTIFY_OK;
40477f24467fSOctavian Purdila }
40487f24467fSOctavian Purdila 
40497f24467fSOctavian Purdila static struct notifier_block spi_acpi_notifier = {
40507f24467fSOctavian Purdila 	.notifier_call = acpi_spi_notify,
40517f24467fSOctavian Purdila };
40527f24467fSOctavian Purdila #else
40537f24467fSOctavian Purdila extern struct notifier_block spi_acpi_notifier;
40547f24467fSOctavian Purdila #endif
40557f24467fSOctavian Purdila 
40568ae12a0dSDavid Brownell static int __init spi_init(void)
40578ae12a0dSDavid Brownell {
4058b885244eSDavid Brownell 	int	status;
40598ae12a0dSDavid Brownell 
4060e94b1766SChristoph Lameter 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4061b885244eSDavid Brownell 	if (!buf) {
4062b885244eSDavid Brownell 		status = -ENOMEM;
4063b885244eSDavid Brownell 		goto err0;
40648ae12a0dSDavid Brownell 	}
4065b885244eSDavid Brownell 
4066b885244eSDavid Brownell 	status = bus_register(&spi_bus_type);
4067b885244eSDavid Brownell 	if (status < 0)
4068b885244eSDavid Brownell 		goto err1;
4069b885244eSDavid Brownell 
4070b885244eSDavid Brownell 	status = class_register(&spi_master_class);
4071b885244eSDavid Brownell 	if (status < 0)
4072b885244eSDavid Brownell 		goto err2;
4073ce79d54aSPantelis Antoniou 
40746c364062SGeert Uytterhoeven 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
40756c364062SGeert Uytterhoeven 		status = class_register(&spi_slave_class);
40766c364062SGeert Uytterhoeven 		if (status < 0)
40776c364062SGeert Uytterhoeven 			goto err3;
40786c364062SGeert Uytterhoeven 	}
40796c364062SGeert Uytterhoeven 
40805267720eSFabio Estevam 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4081ce79d54aSPantelis Antoniou 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
40827f24467fSOctavian Purdila 	if (IS_ENABLED(CONFIG_ACPI))
40837f24467fSOctavian Purdila 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4084ce79d54aSPantelis Antoniou 
4085b885244eSDavid Brownell 	return 0;
4086b885244eSDavid Brownell 
40876c364062SGeert Uytterhoeven err3:
40886c364062SGeert Uytterhoeven 	class_unregister(&spi_master_class);
4089b885244eSDavid Brownell err2:
4090b885244eSDavid Brownell 	bus_unregister(&spi_bus_type);
4091b885244eSDavid Brownell err1:
4092b885244eSDavid Brownell 	kfree(buf);
4093b885244eSDavid Brownell 	buf = NULL;
4094b885244eSDavid Brownell err0:
4095b885244eSDavid Brownell 	return status;
4096b885244eSDavid Brownell }
4097b885244eSDavid Brownell 
40988ae12a0dSDavid Brownell /* board_info is normally registered in arch_initcall(),
40998ae12a0dSDavid Brownell  * but even essential drivers wait till later
4100b885244eSDavid Brownell  *
4101b885244eSDavid Brownell  * REVISIT only boardinfo really needs static linking. the rest (device and
4102b885244eSDavid Brownell  * driver registration) _could_ be dynamically linked (modular) ... costs
4103b885244eSDavid Brownell  * include needing to have boardinfo data structures be much more public.
41048ae12a0dSDavid Brownell  */
4105673c0c00SDavid Brownell postcore_initcall(spi_init);
4106