• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 // SPI init/core code
3 //
4 // Copyright (C) 2005 David Brownell
5 // Copyright (C) 2008 Secret Lab Technologies Ltd.
6 
7 #include <linux/kernel.h>
8 #include <linux/device.h>
9 #include <linux/init.h>
10 #include <linux/cache.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/dmaengine.h>
13 #include <linux/mutex.h>
14 #include <linux/of_device.h>
15 #include <linux/of_irq.h>
16 #include <linux/clk/clk-conf.h>
17 #include <linux/slab.h>
18 #include <linux/mod_devicetable.h>
19 #include <linux/spi/spi.h>
20 #include <linux/spi/spi-mem.h>
21 #include <linux/of_gpio.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/pm_domain.h>
25 #include <linux/property.h>
26 #include <linux/export.h>
27 #include <linux/sched/rt.h>
28 #include <uapi/linux/sched/types.h>
29 #include <linux/delay.h>
30 #include <linux/kthread.h>
31 #include <linux/ioport.h>
32 #include <linux/acpi.h>
33 #include <linux/highmem.h>
34 #include <linux/idr.h>
35 #include <linux/platform_data/x86/apple.h>
36 
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/spi.h>
39 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
40 EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
41 
42 #include "internals.h"
43 
44 static DEFINE_IDR(spi_master_idr);
45 
spidev_release(struct device * dev)46 static void spidev_release(struct device *dev)
47 {
48 	struct spi_device	*spi = to_spi_device(dev);
49 
50 	spi_controller_put(spi->controller);
51 	kfree(spi->driver_override);
52 	kfree(spi);
53 }
54 
55 static ssize_t
modalias_show(struct device * dev,struct device_attribute * a,char * buf)56 modalias_show(struct device *dev, struct device_attribute *a, char *buf)
57 {
58 	const struct spi_device	*spi = to_spi_device(dev);
59 	int len;
60 
61 	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
62 	if (len != -ENODEV)
63 		return len;
64 
65 	return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
66 }
67 static DEVICE_ATTR_RO(modalias);
68 
driver_override_store(struct device * dev,struct device_attribute * a,const char * buf,size_t count)69 static ssize_t driver_override_store(struct device *dev,
70 				     struct device_attribute *a,
71 				     const char *buf, size_t count)
72 {
73 	struct spi_device *spi = to_spi_device(dev);
74 	const char *end = memchr(buf, '\n', count);
75 	const size_t len = end ? end - buf : count;
76 	const char *driver_override, *old;
77 
78 	/* We need to keep extra room for a newline when displaying value */
79 	if (len >= (PAGE_SIZE - 1))
80 		return -EINVAL;
81 
82 	driver_override = kstrndup(buf, len, GFP_KERNEL);
83 	if (!driver_override)
84 		return -ENOMEM;
85 
86 	device_lock(dev);
87 	old = spi->driver_override;
88 	if (len) {
89 		spi->driver_override = driver_override;
90 	} else {
91 		/* Empty string, disable driver override */
92 		spi->driver_override = NULL;
93 		kfree(driver_override);
94 	}
95 	device_unlock(dev);
96 	kfree(old);
97 
98 	return count;
99 }
100 
driver_override_show(struct device * dev,struct device_attribute * a,char * buf)101 static ssize_t driver_override_show(struct device *dev,
102 				    struct device_attribute *a, char *buf)
103 {
104 	const struct spi_device *spi = to_spi_device(dev);
105 	ssize_t len;
106 
107 	device_lock(dev);
108 	len = snprintf(buf, PAGE_SIZE, "%s\n", spi->driver_override ? : "");
109 	device_unlock(dev);
110 	return len;
111 }
112 static DEVICE_ATTR_RW(driver_override);
113 
114 #define SPI_STATISTICS_ATTRS(field, file)				\
115 static ssize_t spi_controller_##field##_show(struct device *dev,	\
116 					     struct device_attribute *attr, \
117 					     char *buf)			\
118 {									\
119 	struct spi_controller *ctlr = container_of(dev,			\
120 					 struct spi_controller, dev);	\
121 	return spi_statistics_##field##_show(&ctlr->statistics, buf);	\
122 }									\
123 static struct device_attribute dev_attr_spi_controller_##field = {	\
124 	.attr = { .name = file, .mode = 0444 },				\
125 	.show = spi_controller_##field##_show,				\
126 };									\
127 static ssize_t spi_device_##field##_show(struct device *dev,		\
128 					 struct device_attribute *attr,	\
129 					char *buf)			\
130 {									\
131 	struct spi_device *spi = to_spi_device(dev);			\
132 	return spi_statistics_##field##_show(&spi->statistics, buf);	\
133 }									\
134 static struct device_attribute dev_attr_spi_device_##field = {		\
135 	.attr = { .name = file, .mode = 0444 },				\
136 	.show = spi_device_##field##_show,				\
137 }
138 
139 #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string)	\
140 static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
141 					    char *buf)			\
142 {									\
143 	unsigned long flags;						\
144 	ssize_t len;							\
145 	spin_lock_irqsave(&stat->lock, flags);				\
146 	len = sprintf(buf, format_string, stat->field);			\
147 	spin_unlock_irqrestore(&stat->lock, flags);			\
148 	return len;							\
149 }									\
150 SPI_STATISTICS_ATTRS(name, file)
151 
152 #define SPI_STATISTICS_SHOW(field, format_string)			\
153 	SPI_STATISTICS_SHOW_NAME(field, __stringify(field),		\
154 				 field, format_string)
155 
156 SPI_STATISTICS_SHOW(messages, "%lu");
157 SPI_STATISTICS_SHOW(transfers, "%lu");
158 SPI_STATISTICS_SHOW(errors, "%lu");
159 SPI_STATISTICS_SHOW(timedout, "%lu");
160 
161 SPI_STATISTICS_SHOW(spi_sync, "%lu");
162 SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
163 SPI_STATISTICS_SHOW(spi_async, "%lu");
164 
165 SPI_STATISTICS_SHOW(bytes, "%llu");
166 SPI_STATISTICS_SHOW(bytes_rx, "%llu");
167 SPI_STATISTICS_SHOW(bytes_tx, "%llu");
168 
169 #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number)		\
170 	SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index,		\
171 				 "transfer_bytes_histo_" number,	\
172 				 transfer_bytes_histo[index],  "%lu")
173 SPI_STATISTICS_TRANSFER_BYTES_HISTO(0,  "0-1");
174 SPI_STATISTICS_TRANSFER_BYTES_HISTO(1,  "2-3");
175 SPI_STATISTICS_TRANSFER_BYTES_HISTO(2,  "4-7");
176 SPI_STATISTICS_TRANSFER_BYTES_HISTO(3,  "8-15");
177 SPI_STATISTICS_TRANSFER_BYTES_HISTO(4,  "16-31");
178 SPI_STATISTICS_TRANSFER_BYTES_HISTO(5,  "32-63");
179 SPI_STATISTICS_TRANSFER_BYTES_HISTO(6,  "64-127");
180 SPI_STATISTICS_TRANSFER_BYTES_HISTO(7,  "128-255");
181 SPI_STATISTICS_TRANSFER_BYTES_HISTO(8,  "256-511");
182 SPI_STATISTICS_TRANSFER_BYTES_HISTO(9,  "512-1023");
183 SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
184 SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
185 SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
186 SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
187 SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
188 SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
189 SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
190 
191 SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
192 
193 static struct attribute *spi_dev_attrs[] = {
194 	&dev_attr_modalias.attr,
195 	&dev_attr_driver_override.attr,
196 	NULL,
197 };
198 
199 static const struct attribute_group spi_dev_group = {
200 	.attrs  = spi_dev_attrs,
201 };
202 
203 static struct attribute *spi_device_statistics_attrs[] = {
204 	&dev_attr_spi_device_messages.attr,
205 	&dev_attr_spi_device_transfers.attr,
206 	&dev_attr_spi_device_errors.attr,
207 	&dev_attr_spi_device_timedout.attr,
208 	&dev_attr_spi_device_spi_sync.attr,
209 	&dev_attr_spi_device_spi_sync_immediate.attr,
210 	&dev_attr_spi_device_spi_async.attr,
211 	&dev_attr_spi_device_bytes.attr,
212 	&dev_attr_spi_device_bytes_rx.attr,
213 	&dev_attr_spi_device_bytes_tx.attr,
214 	&dev_attr_spi_device_transfer_bytes_histo0.attr,
215 	&dev_attr_spi_device_transfer_bytes_histo1.attr,
216 	&dev_attr_spi_device_transfer_bytes_histo2.attr,
217 	&dev_attr_spi_device_transfer_bytes_histo3.attr,
218 	&dev_attr_spi_device_transfer_bytes_histo4.attr,
219 	&dev_attr_spi_device_transfer_bytes_histo5.attr,
220 	&dev_attr_spi_device_transfer_bytes_histo6.attr,
221 	&dev_attr_spi_device_transfer_bytes_histo7.attr,
222 	&dev_attr_spi_device_transfer_bytes_histo8.attr,
223 	&dev_attr_spi_device_transfer_bytes_histo9.attr,
224 	&dev_attr_spi_device_transfer_bytes_histo10.attr,
225 	&dev_attr_spi_device_transfer_bytes_histo11.attr,
226 	&dev_attr_spi_device_transfer_bytes_histo12.attr,
227 	&dev_attr_spi_device_transfer_bytes_histo13.attr,
228 	&dev_attr_spi_device_transfer_bytes_histo14.attr,
229 	&dev_attr_spi_device_transfer_bytes_histo15.attr,
230 	&dev_attr_spi_device_transfer_bytes_histo16.attr,
231 	&dev_attr_spi_device_transfers_split_maxsize.attr,
232 	NULL,
233 };
234 
235 static const struct attribute_group spi_device_statistics_group = {
236 	.name  = "statistics",
237 	.attrs  = spi_device_statistics_attrs,
238 };
239 
240 static const struct attribute_group *spi_dev_groups[] = {
241 	&spi_dev_group,
242 	&spi_device_statistics_group,
243 	NULL,
244 };
245 
246 static struct attribute *spi_controller_statistics_attrs[] = {
247 	&dev_attr_spi_controller_messages.attr,
248 	&dev_attr_spi_controller_transfers.attr,
249 	&dev_attr_spi_controller_errors.attr,
250 	&dev_attr_spi_controller_timedout.attr,
251 	&dev_attr_spi_controller_spi_sync.attr,
252 	&dev_attr_spi_controller_spi_sync_immediate.attr,
253 	&dev_attr_spi_controller_spi_async.attr,
254 	&dev_attr_spi_controller_bytes.attr,
255 	&dev_attr_spi_controller_bytes_rx.attr,
256 	&dev_attr_spi_controller_bytes_tx.attr,
257 	&dev_attr_spi_controller_transfer_bytes_histo0.attr,
258 	&dev_attr_spi_controller_transfer_bytes_histo1.attr,
259 	&dev_attr_spi_controller_transfer_bytes_histo2.attr,
260 	&dev_attr_spi_controller_transfer_bytes_histo3.attr,
261 	&dev_attr_spi_controller_transfer_bytes_histo4.attr,
262 	&dev_attr_spi_controller_transfer_bytes_histo5.attr,
263 	&dev_attr_spi_controller_transfer_bytes_histo6.attr,
264 	&dev_attr_spi_controller_transfer_bytes_histo7.attr,
265 	&dev_attr_spi_controller_transfer_bytes_histo8.attr,
266 	&dev_attr_spi_controller_transfer_bytes_histo9.attr,
267 	&dev_attr_spi_controller_transfer_bytes_histo10.attr,
268 	&dev_attr_spi_controller_transfer_bytes_histo11.attr,
269 	&dev_attr_spi_controller_transfer_bytes_histo12.attr,
270 	&dev_attr_spi_controller_transfer_bytes_histo13.attr,
271 	&dev_attr_spi_controller_transfer_bytes_histo14.attr,
272 	&dev_attr_spi_controller_transfer_bytes_histo15.attr,
273 	&dev_attr_spi_controller_transfer_bytes_histo16.attr,
274 	&dev_attr_spi_controller_transfers_split_maxsize.attr,
275 	NULL,
276 };
277 
278 static const struct attribute_group spi_controller_statistics_group = {
279 	.name  = "statistics",
280 	.attrs  = spi_controller_statistics_attrs,
281 };
282 
283 static const struct attribute_group *spi_master_groups[] = {
284 	&spi_controller_statistics_group,
285 	NULL,
286 };
287 
spi_statistics_add_transfer_stats(struct spi_statistics * stats,struct spi_transfer * xfer,struct spi_controller * ctlr)288 void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
289 				       struct spi_transfer *xfer,
290 				       struct spi_controller *ctlr)
291 {
292 	unsigned long flags;
293 	int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
294 
295 	if (l2len < 0)
296 		l2len = 0;
297 
298 	spin_lock_irqsave(&stats->lock, flags);
299 
300 	stats->transfers++;
301 	stats->transfer_bytes_histo[l2len]++;
302 
303 	stats->bytes += xfer->len;
304 	if ((xfer->tx_buf) &&
305 	    (xfer->tx_buf != ctlr->dummy_tx))
306 		stats->bytes_tx += xfer->len;
307 	if ((xfer->rx_buf) &&
308 	    (xfer->rx_buf != ctlr->dummy_rx))
309 		stats->bytes_rx += xfer->len;
310 
311 	spin_unlock_irqrestore(&stats->lock, flags);
312 }
313 EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
314 
315 /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
316  * and the sysfs version makes coldplug work too.
317  */
318 
spi_match_id(const struct spi_device_id * id,const struct spi_device * sdev)319 static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
320 						const struct spi_device *sdev)
321 {
322 	while (id->name[0]) {
323 		if (!strcmp(sdev->modalias, id->name))
324 			return id;
325 		id++;
326 	}
327 	return NULL;
328 }
329 
spi_get_device_id(const struct spi_device * sdev)330 const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
331 {
332 	const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
333 
334 	return spi_match_id(sdrv->id_table, sdev);
335 }
336 EXPORT_SYMBOL_GPL(spi_get_device_id);
337 
spi_match_device(struct device * dev,struct device_driver * drv)338 static int spi_match_device(struct device *dev, struct device_driver *drv)
339 {
340 	const struct spi_device	*spi = to_spi_device(dev);
341 	const struct spi_driver	*sdrv = to_spi_driver(drv);
342 
343 	/* Check override first, and if set, only use the named driver */
344 	if (spi->driver_override)
345 		return strcmp(spi->driver_override, drv->name) == 0;
346 
347 	/* Attempt an OF style match */
348 	if (of_driver_match_device(dev, drv))
349 		return 1;
350 
351 	/* Then try ACPI */
352 	if (acpi_driver_match_device(dev, drv))
353 		return 1;
354 
355 	if (sdrv->id_table)
356 		return !!spi_match_id(sdrv->id_table, spi);
357 
358 	return strcmp(spi->modalias, drv->name) == 0;
359 }
360 
spi_uevent(struct device * dev,struct kobj_uevent_env * env)361 static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
362 {
363 	const struct spi_device		*spi = to_spi_device(dev);
364 	int rc;
365 
366 	rc = acpi_device_uevent_modalias(dev, env);
367 	if (rc != -ENODEV)
368 		return rc;
369 
370 	return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
371 }
372 
373 struct bus_type spi_bus_type = {
374 	.name		= "spi",
375 	.dev_groups	= spi_dev_groups,
376 	.match		= spi_match_device,
377 	.uevent		= spi_uevent,
378 };
379 EXPORT_SYMBOL_GPL(spi_bus_type);
380 
381 
spi_drv_probe(struct device * dev)382 static int spi_drv_probe(struct device *dev)
383 {
384 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
385 	struct spi_device		*spi = to_spi_device(dev);
386 	int ret;
387 
388 	ret = of_clk_set_defaults(dev->of_node, false);
389 	if (ret)
390 		return ret;
391 
392 	if (dev->of_node) {
393 		spi->irq = of_irq_get(dev->of_node, 0);
394 		if (spi->irq == -EPROBE_DEFER)
395 			return -EPROBE_DEFER;
396 		if (spi->irq < 0)
397 			spi->irq = 0;
398 	}
399 
400 	ret = dev_pm_domain_attach(dev, true);
401 	if (ret)
402 		return ret;
403 
404 	if (sdrv->probe) {
405 		ret = sdrv->probe(spi);
406 		if (ret)
407 			dev_pm_domain_detach(dev, true);
408 	}
409 
410 	return ret;
411 }
412 
spi_drv_remove(struct device * dev)413 static int spi_drv_remove(struct device *dev)
414 {
415 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
416 	int ret = 0;
417 
418 	if (sdrv->remove)
419 		ret = sdrv->remove(to_spi_device(dev));
420 	dev_pm_domain_detach(dev, true);
421 
422 	return ret;
423 }
424 
spi_drv_shutdown(struct device * dev)425 static void spi_drv_shutdown(struct device *dev)
426 {
427 	const struct spi_driver		*sdrv = to_spi_driver(dev->driver);
428 
429 	sdrv->shutdown(to_spi_device(dev));
430 }
431 
432 /**
433  * __spi_register_driver - register a SPI driver
434  * @owner: owner module of the driver to register
435  * @sdrv: the driver to register
436  * Context: can sleep
437  *
438  * Return: zero on success, else a negative error code.
439  */
__spi_register_driver(struct module * owner,struct spi_driver * sdrv)440 int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
441 {
442 	sdrv->driver.owner = owner;
443 	sdrv->driver.bus = &spi_bus_type;
444 	sdrv->driver.probe = spi_drv_probe;
445 	sdrv->driver.remove = spi_drv_remove;
446 	if (sdrv->shutdown)
447 		sdrv->driver.shutdown = spi_drv_shutdown;
448 	return driver_register(&sdrv->driver);
449 }
450 EXPORT_SYMBOL_GPL(__spi_register_driver);
451 
452 /*-------------------------------------------------------------------------*/
453 
454 /* SPI devices should normally not be created by SPI device drivers; that
455  * would make them board-specific.  Similarly with SPI controller drivers.
456  * Device registration normally goes into like arch/.../mach.../board-YYY.c
457  * with other readonly (flashable) information about mainboard devices.
458  */
459 
460 struct boardinfo {
461 	struct list_head	list;
462 	struct spi_board_info	board_info;
463 };
464 
465 static LIST_HEAD(board_list);
466 static LIST_HEAD(spi_controller_list);
467 
468 /*
469  * Used to protect add/del operation for board_info list and
470  * spi_controller list, and their matching process
471  * also used to protect object of type struct idr
472  */
473 static DEFINE_MUTEX(board_lock);
474 
475 /*
476  * Prevents addition of devices with same chip select and
477  * addition of devices below an unregistering controller.
478  */
479 static DEFINE_MUTEX(spi_add_lock);
480 
481 /**
482  * spi_alloc_device - Allocate a new SPI device
483  * @ctlr: Controller to which device is connected
484  * Context: can sleep
485  *
486  * Allows a driver to allocate and initialize a spi_device without
487  * registering it immediately.  This allows a driver to directly
488  * fill the spi_device with device parameters before calling
489  * spi_add_device() on it.
490  *
491  * Caller is responsible to call spi_add_device() on the returned
492  * spi_device structure to add it to the SPI controller.  If the caller
493  * needs to discard the spi_device without adding it, then it should
494  * call spi_dev_put() on it.
495  *
496  * Return: a pointer to the new device, or NULL.
497  */
spi_alloc_device(struct spi_controller * ctlr)498 struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
499 {
500 	struct spi_device	*spi;
501 
502 	if (!spi_controller_get(ctlr))
503 		return NULL;
504 
505 	spi = kzalloc(sizeof(*spi), GFP_KERNEL);
506 	if (!spi) {
507 		spi_controller_put(ctlr);
508 		return NULL;
509 	}
510 
511 	spi->master = spi->controller = ctlr;
512 	spi->dev.parent = &ctlr->dev;
513 	spi->dev.bus = &spi_bus_type;
514 	spi->dev.release = spidev_release;
515 	spi->cs_gpio = -ENOENT;
516 	spi->mode = ctlr->buswidth_override_bits;
517 
518 	spin_lock_init(&spi->statistics.lock);
519 
520 	device_initialize(&spi->dev);
521 	return spi;
522 }
523 EXPORT_SYMBOL_GPL(spi_alloc_device);
524 
spi_dev_set_name(struct spi_device * spi)525 static void spi_dev_set_name(struct spi_device *spi)
526 {
527 	struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
528 
529 	if (adev) {
530 		dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
531 		return;
532 	}
533 
534 	dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
535 		     spi->chip_select);
536 }
537 
spi_dev_check(struct device * dev,void * data)538 static int spi_dev_check(struct device *dev, void *data)
539 {
540 	struct spi_device *spi = to_spi_device(dev);
541 	struct spi_device *new_spi = data;
542 
543 	if (spi->controller == new_spi->controller &&
544 	    spi->chip_select == new_spi->chip_select)
545 		return -EBUSY;
546 	return 0;
547 }
548 
spi_cleanup(struct spi_device * spi)549 static void spi_cleanup(struct spi_device *spi)
550 {
551 	if (spi->controller->cleanup)
552 		spi->controller->cleanup(spi);
553 }
554 
555 /**
556  * spi_add_device - Add spi_device allocated with spi_alloc_device
557  * @spi: spi_device to register
558  *
559  * Companion function to spi_alloc_device.  Devices allocated with
560  * spi_alloc_device can be added onto the spi bus with this function.
561  *
562  * Return: 0 on success; negative errno on failure
563  */
spi_add_device(struct spi_device * spi)564 int spi_add_device(struct spi_device *spi)
565 {
566 	struct spi_controller *ctlr = spi->controller;
567 	struct device *dev = ctlr->dev.parent;
568 	int status;
569 
570 	/* Chipselects are numbered 0..max; validate. */
571 	if (spi->chip_select >= ctlr->num_chipselect) {
572 		dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
573 			ctlr->num_chipselect);
574 		return -EINVAL;
575 	}
576 
577 	/* Set the bus ID string */
578 	spi_dev_set_name(spi);
579 
580 	/* We need to make sure there's no other device with this
581 	 * chipselect **BEFORE** we call setup(), else we'll trash
582 	 * its configuration.  Lock against concurrent add() calls.
583 	 */
584 	mutex_lock(&spi_add_lock);
585 
586 	status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
587 	if (status) {
588 		dev_err(dev, "chipselect %d already in use\n",
589 				spi->chip_select);
590 		goto done;
591 	}
592 
593 	/* Controller may unregister concurrently */
594 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
595 	    !device_is_registered(&ctlr->dev)) {
596 		status = -ENODEV;
597 		goto done;
598 	}
599 
600 	/* Descriptors take precedence */
601 	if (ctlr->cs_gpiods)
602 		spi->cs_gpiod = ctlr->cs_gpiods[spi->chip_select];
603 	else if (ctlr->cs_gpios)
604 		spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
605 
606 	/* Drivers may modify this initial i/o setup, but will
607 	 * normally rely on the device being setup.  Devices
608 	 * using SPI_CS_HIGH can't coexist well otherwise...
609 	 */
610 	status = spi_setup(spi);
611 	if (status < 0) {
612 		dev_err(dev, "can't setup %s, status %d\n",
613 				dev_name(&spi->dev), status);
614 		goto done;
615 	}
616 
617 	/* Device may be bound to an active driver when this returns */
618 	status = device_add(&spi->dev);
619 	if (status < 0) {
620 		dev_err(dev, "can't add %s, status %d\n",
621 				dev_name(&spi->dev), status);
622 		spi_cleanup(spi);
623 	} else {
624 		dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
625 	}
626 
627 done:
628 	mutex_unlock(&spi_add_lock);
629 	return status;
630 }
631 EXPORT_SYMBOL_GPL(spi_add_device);
632 
633 /**
634  * spi_new_device - instantiate one new SPI device
635  * @ctlr: Controller to which device is connected
636  * @chip: Describes the SPI device
637  * Context: can sleep
638  *
639  * On typical mainboards, this is purely internal; and it's not needed
640  * after board init creates the hard-wired devices.  Some development
641  * platforms may not be able to use spi_register_board_info though, and
642  * this is exported so that for example a USB or parport based adapter
643  * driver could add devices (which it would learn about out-of-band).
644  *
645  * Return: the new device, or NULL.
646  */
spi_new_device(struct spi_controller * ctlr,struct spi_board_info * chip)647 struct spi_device *spi_new_device(struct spi_controller *ctlr,
648 				  struct spi_board_info *chip)
649 {
650 	struct spi_device	*proxy;
651 	int			status;
652 
653 	/* NOTE:  caller did any chip->bus_num checks necessary.
654 	 *
655 	 * Also, unless we change the return value convention to use
656 	 * error-or-pointer (not NULL-or-pointer), troubleshootability
657 	 * suggests syslogged diagnostics are best here (ugh).
658 	 */
659 
660 	proxy = spi_alloc_device(ctlr);
661 	if (!proxy)
662 		return NULL;
663 
664 	WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
665 
666 	proxy->chip_select = chip->chip_select;
667 	proxy->max_speed_hz = chip->max_speed_hz;
668 	proxy->mode = chip->mode;
669 	proxy->irq = chip->irq;
670 	strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
671 	proxy->dev.platform_data = (void *) chip->platform_data;
672 	proxy->controller_data = chip->controller_data;
673 	proxy->controller_state = NULL;
674 
675 	if (chip->properties) {
676 		status = device_add_properties(&proxy->dev, chip->properties);
677 		if (status) {
678 			dev_err(&ctlr->dev,
679 				"failed to add properties to '%s': %d\n",
680 				chip->modalias, status);
681 			goto err_dev_put;
682 		}
683 	}
684 
685 	status = spi_add_device(proxy);
686 	if (status < 0)
687 		goto err_remove_props;
688 
689 	return proxy;
690 
691 err_remove_props:
692 	if (chip->properties)
693 		device_remove_properties(&proxy->dev);
694 err_dev_put:
695 	spi_dev_put(proxy);
696 	return NULL;
697 }
698 EXPORT_SYMBOL_GPL(spi_new_device);
699 
700 /**
701  * spi_unregister_device - unregister a single SPI device
702  * @spi: spi_device to unregister
703  *
704  * Start making the passed SPI device vanish. Normally this would be handled
705  * by spi_unregister_controller().
706  */
spi_unregister_device(struct spi_device * spi)707 void spi_unregister_device(struct spi_device *spi)
708 {
709 	if (!spi)
710 		return;
711 
712 	if (spi->dev.of_node) {
713 		of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
714 		of_node_put(spi->dev.of_node);
715 	}
716 	if (ACPI_COMPANION(&spi->dev))
717 		acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
718 	device_del(&spi->dev);
719 	spi_cleanup(spi);
720 	put_device(&spi->dev);
721 }
722 EXPORT_SYMBOL_GPL(spi_unregister_device);
723 
spi_match_controller_to_boardinfo(struct spi_controller * ctlr,struct spi_board_info * bi)724 static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
725 					      struct spi_board_info *bi)
726 {
727 	struct spi_device *dev;
728 
729 	if (ctlr->bus_num != bi->bus_num)
730 		return;
731 
732 	dev = spi_new_device(ctlr, bi);
733 	if (!dev)
734 		dev_err(ctlr->dev.parent, "can't create new device for %s\n",
735 			bi->modalias);
736 }
737 
738 /**
739  * spi_register_board_info - register SPI devices for a given board
740  * @info: array of chip descriptors
741  * @n: how many descriptors are provided
742  * Context: can sleep
743  *
744  * Board-specific early init code calls this (probably during arch_initcall)
745  * with segments of the SPI device table.  Any device nodes are created later,
746  * after the relevant parent SPI controller (bus_num) is defined.  We keep
747  * this table of devices forever, so that reloading a controller driver will
748  * not make Linux forget about these hard-wired devices.
749  *
750  * Other code can also call this, e.g. a particular add-on board might provide
751  * SPI devices through its expansion connector, so code initializing that board
752  * would naturally declare its SPI devices.
753  *
754  * The board info passed can safely be __initdata ... but be careful of
755  * any embedded pointers (platform_data, etc), they're copied as-is.
756  * Device properties are deep-copied though.
757  *
758  * Return: zero on success, else a negative error code.
759  */
spi_register_board_info(struct spi_board_info const * info,unsigned n)760 int spi_register_board_info(struct spi_board_info const *info, unsigned n)
761 {
762 	struct boardinfo *bi;
763 	int i;
764 
765 	if (!n)
766 		return 0;
767 
768 	bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
769 	if (!bi)
770 		return -ENOMEM;
771 
772 	for (i = 0; i < n; i++, bi++, info++) {
773 		struct spi_controller *ctlr;
774 
775 		memcpy(&bi->board_info, info, sizeof(*info));
776 		if (info->properties) {
777 			bi->board_info.properties =
778 					property_entries_dup(info->properties);
779 			if (IS_ERR(bi->board_info.properties))
780 				return PTR_ERR(bi->board_info.properties);
781 		}
782 
783 		mutex_lock(&board_lock);
784 		list_add_tail(&bi->list, &board_list);
785 		list_for_each_entry(ctlr, &spi_controller_list, list)
786 			spi_match_controller_to_boardinfo(ctlr,
787 							  &bi->board_info);
788 		mutex_unlock(&board_lock);
789 	}
790 
791 	return 0;
792 }
793 
794 /*-------------------------------------------------------------------------*/
795 
spi_set_cs(struct spi_device * spi,bool enable,bool force)796 static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
797 {
798 	bool enable1 = enable;
799 
800 	/*
801 	 * Avoid calling into the driver (or doing delays) if the chip select
802 	 * isn't actually changing from the last time this was called.
803 	 */
804 	if (!force && (spi->controller->last_cs_enable == enable) &&
805 	    (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
806 		return;
807 
808 	spi->controller->last_cs_enable = enable;
809 	spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
810 
811 	if (!spi->controller->set_cs_timing) {
812 		if (enable1)
813 			spi_delay_exec(&spi->controller->cs_setup, NULL);
814 		else
815 			spi_delay_exec(&spi->controller->cs_hold, NULL);
816 	}
817 
818 	if (spi->mode & SPI_CS_HIGH)
819 		enable = !enable;
820 
821 	if (spi->cs_gpiod || gpio_is_valid(spi->cs_gpio)) {
822 		if (!(spi->mode & SPI_NO_CS)) {
823 			if (spi->cs_gpiod) {
824 				/*
825 				 * Historically ACPI has no means of the GPIO polarity and
826 				 * thus the SPISerialBus() resource defines it on the per-chip
827 				 * basis. In order to avoid a chain of negations, the GPIO
828 				 * polarity is considered being Active High. Even for the cases
829 				 * when _DSD() is involved (in the updated versions of ACPI)
830 				 * the GPIO CS polarity must be defined Active High to avoid
831 				 * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
832 				 * into account.
833 				 */
834 				if (has_acpi_companion(&spi->dev))
835 					gpiod_set_value_cansleep(spi->cs_gpiod, !enable);
836 				else
837 					/* Polarity handled by GPIO library */
838 					gpiod_set_value_cansleep(spi->cs_gpiod, enable1);
839 			} else {
840 				/*
841 				 * invert the enable line, as active low is
842 				 * default for SPI.
843 				 */
844 				gpio_set_value_cansleep(spi->cs_gpio, !enable);
845 			}
846 		}
847 		/* Some SPI masters need both GPIO CS & slave_select */
848 		if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
849 		    spi->controller->set_cs)
850 			spi->controller->set_cs(spi, !enable);
851 	} else if (spi->controller->set_cs) {
852 		spi->controller->set_cs(spi, !enable);
853 	}
854 
855 	if (!spi->controller->set_cs_timing) {
856 		if (!enable1)
857 			spi_delay_exec(&spi->controller->cs_inactive, NULL);
858 	}
859 }
860 
861 #ifdef CONFIG_HAS_DMA
spi_map_buf(struct spi_controller * ctlr,struct device * dev,struct sg_table * sgt,void * buf,size_t len,enum dma_data_direction dir)862 int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
863 		struct sg_table *sgt, void *buf, size_t len,
864 		enum dma_data_direction dir)
865 {
866 	const bool vmalloced_buf = is_vmalloc_addr(buf);
867 	unsigned int max_seg_size = dma_get_max_seg_size(dev);
868 #ifdef CONFIG_HIGHMEM
869 	const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
870 				(unsigned long)buf < (PKMAP_BASE +
871 					(LAST_PKMAP * PAGE_SIZE)));
872 #else
873 	const bool kmap_buf = false;
874 #endif
875 	int desc_len;
876 	int sgs;
877 	struct page *vm_page;
878 	struct scatterlist *sg;
879 	void *sg_buf;
880 	size_t min;
881 	int i, ret;
882 
883 	if (vmalloced_buf || kmap_buf) {
884 		desc_len = min_t(int, max_seg_size, PAGE_SIZE);
885 		sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
886 	} else if (virt_addr_valid(buf)) {
887 		desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
888 		sgs = DIV_ROUND_UP(len, desc_len);
889 	} else {
890 		return -EINVAL;
891 	}
892 
893 	ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
894 	if (ret != 0)
895 		return ret;
896 
897 	sg = &sgt->sgl[0];
898 	for (i = 0; i < sgs; i++) {
899 
900 		if (vmalloced_buf || kmap_buf) {
901 			/*
902 			 * Next scatterlist entry size is the minimum between
903 			 * the desc_len and the remaining buffer length that
904 			 * fits in a page.
905 			 */
906 			min = min_t(size_t, desc_len,
907 				    min_t(size_t, len,
908 					  PAGE_SIZE - offset_in_page(buf)));
909 			if (vmalloced_buf)
910 				vm_page = vmalloc_to_page(buf);
911 			else
912 				vm_page = kmap_to_page(buf);
913 			if (!vm_page) {
914 				sg_free_table(sgt);
915 				return -ENOMEM;
916 			}
917 			sg_set_page(sg, vm_page,
918 				    min, offset_in_page(buf));
919 		} else {
920 			min = min_t(size_t, len, desc_len);
921 			sg_buf = buf;
922 			sg_set_buf(sg, sg_buf, min);
923 		}
924 
925 		buf += min;
926 		len -= min;
927 		sg = sg_next(sg);
928 	}
929 
930 	ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
931 	if (!ret)
932 		ret = -ENOMEM;
933 	if (ret < 0) {
934 		sg_free_table(sgt);
935 		return ret;
936 	}
937 
938 	sgt->nents = ret;
939 
940 	return 0;
941 }
942 
spi_unmap_buf(struct spi_controller * ctlr,struct device * dev,struct sg_table * sgt,enum dma_data_direction dir)943 void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
944 		   struct sg_table *sgt, enum dma_data_direction dir)
945 {
946 	if (sgt->orig_nents) {
947 		dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
948 		sg_free_table(sgt);
949 	}
950 }
951 
__spi_map_msg(struct spi_controller * ctlr,struct spi_message * msg)952 static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
953 {
954 	struct device *tx_dev, *rx_dev;
955 	struct spi_transfer *xfer;
956 	int ret;
957 
958 	if (!ctlr->can_dma)
959 		return 0;
960 
961 	if (ctlr->dma_tx)
962 		tx_dev = ctlr->dma_tx->device->dev;
963 	else
964 		tx_dev = ctlr->dev.parent;
965 
966 	if (ctlr->dma_rx)
967 		rx_dev = ctlr->dma_rx->device->dev;
968 	else
969 		rx_dev = ctlr->dev.parent;
970 
971 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
972 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
973 			continue;
974 
975 		if (xfer->tx_buf != NULL) {
976 			ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
977 					  (void *)xfer->tx_buf, xfer->len,
978 					  DMA_TO_DEVICE);
979 			if (ret != 0)
980 				return ret;
981 		}
982 
983 		if (xfer->rx_buf != NULL) {
984 			ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
985 					  xfer->rx_buf, xfer->len,
986 					  DMA_FROM_DEVICE);
987 			if (ret != 0) {
988 				spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
989 					      DMA_TO_DEVICE);
990 				return ret;
991 			}
992 		}
993 	}
994 
995 	ctlr->cur_msg_mapped = true;
996 
997 	return 0;
998 }
999 
__spi_unmap_msg(struct spi_controller * ctlr,struct spi_message * msg)1000 static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
1001 {
1002 	struct spi_transfer *xfer;
1003 	struct device *tx_dev, *rx_dev;
1004 
1005 	if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
1006 		return 0;
1007 
1008 	if (ctlr->dma_tx)
1009 		tx_dev = ctlr->dma_tx->device->dev;
1010 	else
1011 		tx_dev = ctlr->dev.parent;
1012 
1013 	if (ctlr->dma_rx)
1014 		rx_dev = ctlr->dma_rx->device->dev;
1015 	else
1016 		rx_dev = ctlr->dev.parent;
1017 
1018 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1019 		if (!ctlr->can_dma(ctlr, msg->spi, xfer))
1020 			continue;
1021 
1022 		spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
1023 		spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
1024 	}
1025 
1026 	ctlr->cur_msg_mapped = false;
1027 
1028 	return 0;
1029 }
1030 #else /* !CONFIG_HAS_DMA */
__spi_map_msg(struct spi_controller * ctlr,struct spi_message * msg)1031 static inline int __spi_map_msg(struct spi_controller *ctlr,
1032 				struct spi_message *msg)
1033 {
1034 	return 0;
1035 }
1036 
__spi_unmap_msg(struct spi_controller * ctlr,struct spi_message * msg)1037 static inline int __spi_unmap_msg(struct spi_controller *ctlr,
1038 				  struct spi_message *msg)
1039 {
1040 	return 0;
1041 }
1042 #endif /* !CONFIG_HAS_DMA */
1043 
spi_unmap_msg(struct spi_controller * ctlr,struct spi_message * msg)1044 static inline int spi_unmap_msg(struct spi_controller *ctlr,
1045 				struct spi_message *msg)
1046 {
1047 	struct spi_transfer *xfer;
1048 
1049 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1050 		/*
1051 		 * Restore the original value of tx_buf or rx_buf if they are
1052 		 * NULL.
1053 		 */
1054 		if (xfer->tx_buf == ctlr->dummy_tx)
1055 			xfer->tx_buf = NULL;
1056 		if (xfer->rx_buf == ctlr->dummy_rx)
1057 			xfer->rx_buf = NULL;
1058 	}
1059 
1060 	return __spi_unmap_msg(ctlr, msg);
1061 }
1062 
spi_map_msg(struct spi_controller * ctlr,struct spi_message * msg)1063 static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
1064 {
1065 	struct spi_transfer *xfer;
1066 	void *tmp;
1067 	unsigned int max_tx, max_rx;
1068 
1069 	if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
1070 		&& !(msg->spi->mode & SPI_3WIRE)) {
1071 		max_tx = 0;
1072 		max_rx = 0;
1073 
1074 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1075 			if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
1076 			    !xfer->tx_buf)
1077 				max_tx = max(xfer->len, max_tx);
1078 			if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
1079 			    !xfer->rx_buf)
1080 				max_rx = max(xfer->len, max_rx);
1081 		}
1082 
1083 		if (max_tx) {
1084 			tmp = krealloc(ctlr->dummy_tx, max_tx,
1085 				       GFP_KERNEL | GFP_DMA);
1086 			if (!tmp)
1087 				return -ENOMEM;
1088 			ctlr->dummy_tx = tmp;
1089 			memset(tmp, 0, max_tx);
1090 		}
1091 
1092 		if (max_rx) {
1093 			tmp = krealloc(ctlr->dummy_rx, max_rx,
1094 				       GFP_KERNEL | GFP_DMA);
1095 			if (!tmp)
1096 				return -ENOMEM;
1097 			ctlr->dummy_rx = tmp;
1098 		}
1099 
1100 		if (max_tx || max_rx) {
1101 			list_for_each_entry(xfer, &msg->transfers,
1102 					    transfer_list) {
1103 				if (!xfer->len)
1104 					continue;
1105 				if (!xfer->tx_buf)
1106 					xfer->tx_buf = ctlr->dummy_tx;
1107 				if (!xfer->rx_buf)
1108 					xfer->rx_buf = ctlr->dummy_rx;
1109 			}
1110 		}
1111 	}
1112 
1113 	return __spi_map_msg(ctlr, msg);
1114 }
1115 
spi_transfer_wait(struct spi_controller * ctlr,struct spi_message * msg,struct spi_transfer * xfer)1116 static int spi_transfer_wait(struct spi_controller *ctlr,
1117 			     struct spi_message *msg,
1118 			     struct spi_transfer *xfer)
1119 {
1120 	struct spi_statistics *statm = &ctlr->statistics;
1121 	struct spi_statistics *stats = &msg->spi->statistics;
1122 	u32 speed_hz = xfer->speed_hz;
1123 	unsigned long long ms;
1124 
1125 	if (spi_controller_is_slave(ctlr)) {
1126 		if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
1127 			dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
1128 			return -EINTR;
1129 		}
1130 	} else {
1131 		if (!speed_hz)
1132 			speed_hz = 100000;
1133 
1134 		ms = 8LL * 1000LL * xfer->len;
1135 		do_div(ms, speed_hz);
1136 		ms += ms + 200; /* some tolerance */
1137 
1138 		if (ms > UINT_MAX)
1139 			ms = UINT_MAX;
1140 
1141 		ms = wait_for_completion_timeout(&ctlr->xfer_completion,
1142 						 msecs_to_jiffies(ms));
1143 
1144 		if (ms == 0) {
1145 			SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
1146 			SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
1147 			dev_err(&msg->spi->dev,
1148 				"SPI transfer timed out\n");
1149 			return -ETIMEDOUT;
1150 		}
1151 	}
1152 
1153 	return 0;
1154 }
1155 
_spi_transfer_delay_ns(u32 ns)1156 static void _spi_transfer_delay_ns(u32 ns)
1157 {
1158 	if (!ns)
1159 		return;
1160 	if (ns <= 1000) {
1161 		ndelay(ns);
1162 	} else {
1163 		u32 us = DIV_ROUND_UP(ns, 1000);
1164 
1165 		if (us <= 10)
1166 			udelay(us);
1167 		else
1168 			usleep_range(us, us + DIV_ROUND_UP(us, 10));
1169 	}
1170 }
1171 
spi_delay_to_ns(struct spi_delay * _delay,struct spi_transfer * xfer)1172 int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
1173 {
1174 	u32 delay = _delay->value;
1175 	u32 unit = _delay->unit;
1176 	u32 hz;
1177 
1178 	if (!delay)
1179 		return 0;
1180 
1181 	switch (unit) {
1182 	case SPI_DELAY_UNIT_USECS:
1183 		delay *= 1000;
1184 		break;
1185 	case SPI_DELAY_UNIT_NSECS: /* nothing to do here */
1186 		break;
1187 	case SPI_DELAY_UNIT_SCK:
1188 		/* clock cycles need to be obtained from spi_transfer */
1189 		if (!xfer)
1190 			return -EINVAL;
1191 		/* if there is no effective speed know, then approximate
1192 		 * by underestimating with half the requested hz
1193 		 */
1194 		hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
1195 		if (!hz)
1196 			return -EINVAL;
1197 		delay *= DIV_ROUND_UP(1000000000, hz);
1198 		break;
1199 	default:
1200 		return -EINVAL;
1201 	}
1202 
1203 	return delay;
1204 }
1205 EXPORT_SYMBOL_GPL(spi_delay_to_ns);
1206 
spi_delay_exec(struct spi_delay * _delay,struct spi_transfer * xfer)1207 int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
1208 {
1209 	int delay;
1210 
1211 	might_sleep();
1212 
1213 	if (!_delay)
1214 		return -EINVAL;
1215 
1216 	delay = spi_delay_to_ns(_delay, xfer);
1217 	if (delay < 0)
1218 		return delay;
1219 
1220 	_spi_transfer_delay_ns(delay);
1221 
1222 	return 0;
1223 }
1224 EXPORT_SYMBOL_GPL(spi_delay_exec);
1225 
_spi_transfer_cs_change_delay(struct spi_message * msg,struct spi_transfer * xfer)1226 static void _spi_transfer_cs_change_delay(struct spi_message *msg,
1227 					  struct spi_transfer *xfer)
1228 {
1229 	u32 delay = xfer->cs_change_delay.value;
1230 	u32 unit = xfer->cs_change_delay.unit;
1231 	int ret;
1232 
1233 	/* return early on "fast" mode - for everything but USECS */
1234 	if (!delay) {
1235 		if (unit == SPI_DELAY_UNIT_USECS)
1236 			_spi_transfer_delay_ns(10000);
1237 		return;
1238 	}
1239 
1240 	ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
1241 	if (ret) {
1242 		dev_err_once(&msg->spi->dev,
1243 			     "Use of unsupported delay unit %i, using default of 10us\n",
1244 			     unit);
1245 		_spi_transfer_delay_ns(10000);
1246 	}
1247 }
1248 
1249 /*
1250  * spi_transfer_one_message - Default implementation of transfer_one_message()
1251  *
1252  * This is a standard implementation of transfer_one_message() for
1253  * drivers which implement a transfer_one() operation.  It provides
1254  * standard handling of delays and chip select management.
1255  */
spi_transfer_one_message(struct spi_controller * ctlr,struct spi_message * msg)1256 static int spi_transfer_one_message(struct spi_controller *ctlr,
1257 				    struct spi_message *msg)
1258 {
1259 	struct spi_transfer *xfer;
1260 	bool keep_cs = false;
1261 	int ret = 0;
1262 	struct spi_statistics *statm = &ctlr->statistics;
1263 	struct spi_statistics *stats = &msg->spi->statistics;
1264 
1265 	spi_set_cs(msg->spi, true, false);
1266 
1267 	SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
1268 	SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
1269 
1270 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1271 		trace_spi_transfer_start(msg, xfer);
1272 
1273 		spi_statistics_add_transfer_stats(statm, xfer, ctlr);
1274 		spi_statistics_add_transfer_stats(stats, xfer, ctlr);
1275 
1276 		if (!ctlr->ptp_sts_supported) {
1277 			xfer->ptp_sts_word_pre = 0;
1278 			ptp_read_system_prets(xfer->ptp_sts);
1279 		}
1280 
1281 		if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
1282 			reinit_completion(&ctlr->xfer_completion);
1283 
1284 fallback_pio:
1285 			ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
1286 			if (ret < 0) {
1287 				if (ctlr->cur_msg_mapped &&
1288 				   (xfer->error & SPI_TRANS_FAIL_NO_START)) {
1289 					__spi_unmap_msg(ctlr, msg);
1290 					ctlr->fallback = true;
1291 					xfer->error &= ~SPI_TRANS_FAIL_NO_START;
1292 					goto fallback_pio;
1293 				}
1294 
1295 				SPI_STATISTICS_INCREMENT_FIELD(statm,
1296 							       errors);
1297 				SPI_STATISTICS_INCREMENT_FIELD(stats,
1298 							       errors);
1299 				dev_err(&msg->spi->dev,
1300 					"SPI transfer failed: %d\n", ret);
1301 				goto out;
1302 			}
1303 
1304 			if (ret > 0) {
1305 				ret = spi_transfer_wait(ctlr, msg, xfer);
1306 				if (ret < 0)
1307 					msg->status = ret;
1308 			}
1309 		} else {
1310 			if (xfer->len)
1311 				dev_err(&msg->spi->dev,
1312 					"Bufferless transfer has length %u\n",
1313 					xfer->len);
1314 		}
1315 
1316 		if (!ctlr->ptp_sts_supported) {
1317 			ptp_read_system_postts(xfer->ptp_sts);
1318 			xfer->ptp_sts_word_post = xfer->len;
1319 		}
1320 
1321 		trace_spi_transfer_stop(msg, xfer);
1322 
1323 		if (msg->status != -EINPROGRESS)
1324 			goto out;
1325 
1326 		spi_transfer_delay_exec(xfer);
1327 
1328 		if (xfer->cs_change) {
1329 			if (list_is_last(&xfer->transfer_list,
1330 					 &msg->transfers)) {
1331 				keep_cs = true;
1332 			} else {
1333 				spi_set_cs(msg->spi, false, false);
1334 				_spi_transfer_cs_change_delay(msg, xfer);
1335 				spi_set_cs(msg->spi, true, false);
1336 			}
1337 		}
1338 
1339 		msg->actual_length += xfer->len;
1340 	}
1341 
1342 out:
1343 	if (ret != 0 || !keep_cs)
1344 		spi_set_cs(msg->spi, false, false);
1345 
1346 	if (msg->status == -EINPROGRESS)
1347 		msg->status = ret;
1348 
1349 	if (msg->status && ctlr->handle_err)
1350 		ctlr->handle_err(ctlr, msg);
1351 
1352 	spi_finalize_current_message(ctlr);
1353 
1354 	return ret;
1355 }
1356 
1357 /**
1358  * spi_finalize_current_transfer - report completion of a transfer
1359  * @ctlr: the controller reporting completion
1360  *
1361  * Called by SPI drivers using the core transfer_one_message()
1362  * implementation to notify it that the current interrupt driven
1363  * transfer has finished and the next one may be scheduled.
1364  */
spi_finalize_current_transfer(struct spi_controller * ctlr)1365 void spi_finalize_current_transfer(struct spi_controller *ctlr)
1366 {
1367 	complete(&ctlr->xfer_completion);
1368 }
1369 EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
1370 
spi_idle_runtime_pm(struct spi_controller * ctlr)1371 static void spi_idle_runtime_pm(struct spi_controller *ctlr)
1372 {
1373 	if (ctlr->auto_runtime_pm) {
1374 		pm_runtime_mark_last_busy(ctlr->dev.parent);
1375 		pm_runtime_put_autosuspend(ctlr->dev.parent);
1376 	}
1377 }
1378 
1379 /**
1380  * __spi_pump_messages - function which processes spi message queue
1381  * @ctlr: controller to process queue for
1382  * @in_kthread: true if we are in the context of the message pump thread
1383  *
1384  * This function checks if there is any spi message in the queue that
1385  * needs processing and if so call out to the driver to initialize hardware
1386  * and transfer each message.
1387  *
1388  * Note that it is called both from the kthread itself and also from
1389  * inside spi_sync(); the queue extraction handling at the top of the
1390  * function should deal with this safely.
1391  */
__spi_pump_messages(struct spi_controller * ctlr,bool in_kthread)1392 static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
1393 {
1394 	struct spi_transfer *xfer;
1395 	struct spi_message *msg;
1396 	bool was_busy = false;
1397 	unsigned long flags;
1398 	int ret;
1399 
1400 	/* Lock queue */
1401 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1402 
1403 	/* Make sure we are not already running a message */
1404 	if (ctlr->cur_msg) {
1405 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1406 		return;
1407 	}
1408 
1409 	/* If another context is idling the device then defer */
1410 	if (ctlr->idling) {
1411 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1412 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1413 		return;
1414 	}
1415 
1416 	/* Check if the queue is idle */
1417 	if (list_empty(&ctlr->queue) || !ctlr->running) {
1418 		if (!ctlr->busy) {
1419 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1420 			return;
1421 		}
1422 
1423 		/* Defer any non-atomic teardown to the thread */
1424 		if (!in_kthread) {
1425 			if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
1426 			    !ctlr->unprepare_transfer_hardware) {
1427 				spi_idle_runtime_pm(ctlr);
1428 				ctlr->busy = false;
1429 				trace_spi_controller_idle(ctlr);
1430 			} else {
1431 				kthread_queue_work(ctlr->kworker,
1432 						   &ctlr->pump_messages);
1433 			}
1434 			spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1435 			return;
1436 		}
1437 
1438 		ctlr->busy = false;
1439 		ctlr->idling = true;
1440 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1441 
1442 		kfree(ctlr->dummy_rx);
1443 		ctlr->dummy_rx = NULL;
1444 		kfree(ctlr->dummy_tx);
1445 		ctlr->dummy_tx = NULL;
1446 		if (ctlr->unprepare_transfer_hardware &&
1447 		    ctlr->unprepare_transfer_hardware(ctlr))
1448 			dev_err(&ctlr->dev,
1449 				"failed to unprepare transfer hardware\n");
1450 		spi_idle_runtime_pm(ctlr);
1451 		trace_spi_controller_idle(ctlr);
1452 
1453 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1454 		ctlr->idling = false;
1455 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1456 		return;
1457 	}
1458 
1459 	/* Extract head of queue */
1460 	msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
1461 	ctlr->cur_msg = msg;
1462 
1463 	list_del_init(&msg->queue);
1464 	if (ctlr->busy)
1465 		was_busy = true;
1466 	else
1467 		ctlr->busy = true;
1468 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1469 
1470 	mutex_lock(&ctlr->io_mutex);
1471 
1472 	if (!was_busy && ctlr->auto_runtime_pm) {
1473 		ret = pm_runtime_get_sync(ctlr->dev.parent);
1474 		if (ret < 0) {
1475 			pm_runtime_put_noidle(ctlr->dev.parent);
1476 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
1477 				ret);
1478 			mutex_unlock(&ctlr->io_mutex);
1479 			return;
1480 		}
1481 	}
1482 
1483 	if (!was_busy)
1484 		trace_spi_controller_busy(ctlr);
1485 
1486 	if (!was_busy && ctlr->prepare_transfer_hardware) {
1487 		ret = ctlr->prepare_transfer_hardware(ctlr);
1488 		if (ret) {
1489 			dev_err(&ctlr->dev,
1490 				"failed to prepare transfer hardware: %d\n",
1491 				ret);
1492 
1493 			if (ctlr->auto_runtime_pm)
1494 				pm_runtime_put(ctlr->dev.parent);
1495 
1496 			msg->status = ret;
1497 			spi_finalize_current_message(ctlr);
1498 
1499 			mutex_unlock(&ctlr->io_mutex);
1500 			return;
1501 		}
1502 	}
1503 
1504 	trace_spi_message_start(msg);
1505 
1506 	if (ctlr->prepare_message) {
1507 		ret = ctlr->prepare_message(ctlr, msg);
1508 		if (ret) {
1509 			dev_err(&ctlr->dev, "failed to prepare message: %d\n",
1510 				ret);
1511 			msg->status = ret;
1512 			spi_finalize_current_message(ctlr);
1513 			goto out;
1514 		}
1515 		ctlr->cur_msg_prepared = true;
1516 	}
1517 
1518 	ret = spi_map_msg(ctlr, msg);
1519 	if (ret) {
1520 		msg->status = ret;
1521 		spi_finalize_current_message(ctlr);
1522 		goto out;
1523 	}
1524 
1525 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1526 		list_for_each_entry(xfer, &msg->transfers, transfer_list) {
1527 			xfer->ptp_sts_word_pre = 0;
1528 			ptp_read_system_prets(xfer->ptp_sts);
1529 		}
1530 	}
1531 
1532 	ret = ctlr->transfer_one_message(ctlr, msg);
1533 	if (ret) {
1534 		dev_err(&ctlr->dev,
1535 			"failed to transfer one message from queue\n");
1536 		goto out;
1537 	}
1538 
1539 out:
1540 	mutex_unlock(&ctlr->io_mutex);
1541 
1542 	/* Prod the scheduler in case transfer_one() was busy waiting */
1543 	if (!ret)
1544 		cond_resched();
1545 }
1546 
1547 /**
1548  * spi_pump_messages - kthread work function which processes spi message queue
1549  * @work: pointer to kthread work struct contained in the controller struct
1550  */
spi_pump_messages(struct kthread_work * work)1551 static void spi_pump_messages(struct kthread_work *work)
1552 {
1553 	struct spi_controller *ctlr =
1554 		container_of(work, struct spi_controller, pump_messages);
1555 
1556 	__spi_pump_messages(ctlr, true);
1557 }
1558 
1559 /**
1560  * spi_take_timestamp_pre - helper for drivers to collect the beginning of the
1561  *			    TX timestamp for the requested byte from the SPI
1562  *			    transfer. The frequency with which this function
1563  *			    must be called (once per word, once for the whole
1564  *			    transfer, once per batch of words etc) is arbitrary
1565  *			    as long as the @tx buffer offset is greater than or
1566  *			    equal to the requested byte at the time of the
1567  *			    call. The timestamp is only taken once, at the
1568  *			    first such call. It is assumed that the driver
1569  *			    advances its @tx buffer pointer monotonically.
1570  * @ctlr: Pointer to the spi_controller structure of the driver
1571  * @xfer: Pointer to the transfer being timestamped
1572  * @progress: How many words (not bytes) have been transferred so far
1573  * @irqs_off: If true, will disable IRQs and preemption for the duration of the
1574  *	      transfer, for less jitter in time measurement. Only compatible
1575  *	      with PIO drivers. If true, must follow up with
1576  *	      spi_take_timestamp_post or otherwise system will crash.
1577  *	      WARNING: for fully predictable results, the CPU frequency must
1578  *	      also be under control (governor).
1579  */
spi_take_timestamp_pre(struct spi_controller * ctlr,struct spi_transfer * xfer,size_t progress,bool irqs_off)1580 void spi_take_timestamp_pre(struct spi_controller *ctlr,
1581 			    struct spi_transfer *xfer,
1582 			    size_t progress, bool irqs_off)
1583 {
1584 	if (!xfer->ptp_sts)
1585 		return;
1586 
1587 	if (xfer->timestamped)
1588 		return;
1589 
1590 	if (progress > xfer->ptp_sts_word_pre)
1591 		return;
1592 
1593 	/* Capture the resolution of the timestamp */
1594 	xfer->ptp_sts_word_pre = progress;
1595 
1596 	if (irqs_off) {
1597 		local_irq_save(ctlr->irq_flags);
1598 		preempt_disable();
1599 	}
1600 
1601 	ptp_read_system_prets(xfer->ptp_sts);
1602 }
1603 EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
1604 
1605 /**
1606  * spi_take_timestamp_post - helper for drivers to collect the end of the
1607  *			     TX timestamp for the requested byte from the SPI
1608  *			     transfer. Can be called with an arbitrary
1609  *			     frequency: only the first call where @tx exceeds
1610  *			     or is equal to the requested word will be
1611  *			     timestamped.
1612  * @ctlr: Pointer to the spi_controller structure of the driver
1613  * @xfer: Pointer to the transfer being timestamped
1614  * @progress: How many words (not bytes) have been transferred so far
1615  * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
1616  */
spi_take_timestamp_post(struct spi_controller * ctlr,struct spi_transfer * xfer,size_t progress,bool irqs_off)1617 void spi_take_timestamp_post(struct spi_controller *ctlr,
1618 			     struct spi_transfer *xfer,
1619 			     size_t progress, bool irqs_off)
1620 {
1621 	if (!xfer->ptp_sts)
1622 		return;
1623 
1624 	if (xfer->timestamped)
1625 		return;
1626 
1627 	if (progress < xfer->ptp_sts_word_post)
1628 		return;
1629 
1630 	ptp_read_system_postts(xfer->ptp_sts);
1631 
1632 	if (irqs_off) {
1633 		local_irq_restore(ctlr->irq_flags);
1634 		preempt_enable();
1635 	}
1636 
1637 	/* Capture the resolution of the timestamp */
1638 	xfer->ptp_sts_word_post = progress;
1639 
1640 	xfer->timestamped = true;
1641 }
1642 EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
1643 
1644 /**
1645  * spi_set_thread_rt - set the controller to pump at realtime priority
1646  * @ctlr: controller to boost priority of
1647  *
1648  * This can be called because the controller requested realtime priority
1649  * (by setting the ->rt value before calling spi_register_controller()) or
1650  * because a device on the bus said that its transfers needed realtime
1651  * priority.
1652  *
1653  * NOTE: at the moment if any device on a bus says it needs realtime then
1654  * the thread will be at realtime priority for all transfers on that
1655  * controller.  If this eventually becomes a problem we may see if we can
1656  * find a way to boost the priority only temporarily during relevant
1657  * transfers.
1658  */
spi_set_thread_rt(struct spi_controller * ctlr)1659 static void spi_set_thread_rt(struct spi_controller *ctlr)
1660 {
1661 	dev_info(&ctlr->dev,
1662 		"will run message pump with realtime priority\n");
1663 	sched_set_fifo(ctlr->kworker->task);
1664 }
1665 
spi_init_queue(struct spi_controller * ctlr)1666 static int spi_init_queue(struct spi_controller *ctlr)
1667 {
1668 	ctlr->running = false;
1669 	ctlr->busy = false;
1670 
1671 	ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
1672 	if (IS_ERR(ctlr->kworker)) {
1673 		dev_err(&ctlr->dev, "failed to create message pump kworker\n");
1674 		return PTR_ERR(ctlr->kworker);
1675 	}
1676 
1677 	kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
1678 
1679 	/*
1680 	 * Controller config will indicate if this controller should run the
1681 	 * message pump with high (realtime) priority to reduce the transfer
1682 	 * latency on the bus by minimising the delay between a transfer
1683 	 * request and the scheduling of the message pump thread. Without this
1684 	 * setting the message pump thread will remain at default priority.
1685 	 */
1686 	if (ctlr->rt)
1687 		spi_set_thread_rt(ctlr);
1688 
1689 	return 0;
1690 }
1691 
1692 /**
1693  * spi_get_next_queued_message() - called by driver to check for queued
1694  * messages
1695  * @ctlr: the controller to check for queued messages
1696  *
1697  * If there are more messages in the queue, the next message is returned from
1698  * this call.
1699  *
1700  * Return: the next message in the queue, else NULL if the queue is empty.
1701  */
spi_get_next_queued_message(struct spi_controller * ctlr)1702 struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
1703 {
1704 	struct spi_message *next;
1705 	unsigned long flags;
1706 
1707 	/* get a pointer to the next message, if any */
1708 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1709 	next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
1710 					queue);
1711 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1712 
1713 	return next;
1714 }
1715 EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
1716 
1717 /**
1718  * spi_finalize_current_message() - the current message is complete
1719  * @ctlr: the controller to return the message to
1720  *
1721  * Called by the driver to notify the core that the message in the front of the
1722  * queue is complete and can be removed from the queue.
1723  */
spi_finalize_current_message(struct spi_controller * ctlr)1724 void spi_finalize_current_message(struct spi_controller *ctlr)
1725 {
1726 	struct spi_transfer *xfer;
1727 	struct spi_message *mesg;
1728 	unsigned long flags;
1729 	int ret;
1730 
1731 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1732 	mesg = ctlr->cur_msg;
1733 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1734 
1735 	if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
1736 		list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
1737 			ptp_read_system_postts(xfer->ptp_sts);
1738 			xfer->ptp_sts_word_post = xfer->len;
1739 		}
1740 	}
1741 
1742 	if (unlikely(ctlr->ptp_sts_supported))
1743 		list_for_each_entry(xfer, &mesg->transfers, transfer_list)
1744 			WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
1745 
1746 	spi_unmap_msg(ctlr, mesg);
1747 
1748 	/* In the prepare_messages callback the spi bus has the opportunity to
1749 	 * split a transfer to smaller chunks.
1750 	 * Release splited transfers here since spi_map_msg is done on the
1751 	 * splited transfers.
1752 	 */
1753 	spi_res_release(ctlr, mesg);
1754 
1755 	if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
1756 		ret = ctlr->unprepare_message(ctlr, mesg);
1757 		if (ret) {
1758 			dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
1759 				ret);
1760 		}
1761 	}
1762 
1763 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1764 	ctlr->cur_msg = NULL;
1765 	ctlr->cur_msg_prepared = false;
1766 	ctlr->fallback = false;
1767 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1768 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1769 
1770 	trace_spi_message_done(mesg);
1771 
1772 	mesg->state = NULL;
1773 	if (mesg->complete)
1774 		mesg->complete(mesg->context);
1775 }
1776 EXPORT_SYMBOL_GPL(spi_finalize_current_message);
1777 
spi_start_queue(struct spi_controller * ctlr)1778 static int spi_start_queue(struct spi_controller *ctlr)
1779 {
1780 	unsigned long flags;
1781 
1782 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1783 
1784 	if (ctlr->running || ctlr->busy) {
1785 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1786 		return -EBUSY;
1787 	}
1788 
1789 	ctlr->running = true;
1790 	ctlr->cur_msg = NULL;
1791 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1792 
1793 	kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1794 
1795 	return 0;
1796 }
1797 
spi_stop_queue(struct spi_controller * ctlr)1798 static int spi_stop_queue(struct spi_controller *ctlr)
1799 {
1800 	unsigned long flags;
1801 	unsigned limit = 500;
1802 	int ret = 0;
1803 
1804 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1805 
1806 	/*
1807 	 * This is a bit lame, but is optimized for the common execution path.
1808 	 * A wait_queue on the ctlr->busy could be used, but then the common
1809 	 * execution path (pump_messages) would be required to call wake_up or
1810 	 * friends on every SPI message. Do this instead.
1811 	 */
1812 	while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
1813 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1814 		usleep_range(10000, 11000);
1815 		spin_lock_irqsave(&ctlr->queue_lock, flags);
1816 	}
1817 
1818 	if (!list_empty(&ctlr->queue) || ctlr->busy)
1819 		ret = -EBUSY;
1820 	else
1821 		ctlr->running = false;
1822 
1823 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1824 
1825 	if (ret) {
1826 		dev_warn(&ctlr->dev, "could not stop message queue\n");
1827 		return ret;
1828 	}
1829 	return ret;
1830 }
1831 
spi_destroy_queue(struct spi_controller * ctlr)1832 static int spi_destroy_queue(struct spi_controller *ctlr)
1833 {
1834 	int ret;
1835 
1836 	ret = spi_stop_queue(ctlr);
1837 
1838 	/*
1839 	 * kthread_flush_worker will block until all work is done.
1840 	 * If the reason that stop_queue timed out is that the work will never
1841 	 * finish, then it does no good to call flush/stop thread, so
1842 	 * return anyway.
1843 	 */
1844 	if (ret) {
1845 		dev_err(&ctlr->dev, "problem destroying queue\n");
1846 		return ret;
1847 	}
1848 
1849 	kthread_destroy_worker(ctlr->kworker);
1850 
1851 	return 0;
1852 }
1853 
__spi_queued_transfer(struct spi_device * spi,struct spi_message * msg,bool need_pump)1854 static int __spi_queued_transfer(struct spi_device *spi,
1855 				 struct spi_message *msg,
1856 				 bool need_pump)
1857 {
1858 	struct spi_controller *ctlr = spi->controller;
1859 	unsigned long flags;
1860 
1861 	spin_lock_irqsave(&ctlr->queue_lock, flags);
1862 
1863 	if (!ctlr->running) {
1864 		spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1865 		return -ESHUTDOWN;
1866 	}
1867 	msg->actual_length = 0;
1868 	msg->status = -EINPROGRESS;
1869 
1870 	list_add_tail(&msg->queue, &ctlr->queue);
1871 	if (!ctlr->busy && need_pump)
1872 		kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
1873 
1874 	spin_unlock_irqrestore(&ctlr->queue_lock, flags);
1875 	return 0;
1876 }
1877 
1878 /**
1879  * spi_queued_transfer - transfer function for queued transfers
1880  * @spi: spi device which is requesting transfer
1881  * @msg: spi message which is to handled is queued to driver queue
1882  *
1883  * Return: zero on success, else a negative error code.
1884  */
spi_queued_transfer(struct spi_device * spi,struct spi_message * msg)1885 static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
1886 {
1887 	return __spi_queued_transfer(spi, msg, true);
1888 }
1889 
spi_controller_initialize_queue(struct spi_controller * ctlr)1890 static int spi_controller_initialize_queue(struct spi_controller *ctlr)
1891 {
1892 	int ret;
1893 
1894 	ctlr->transfer = spi_queued_transfer;
1895 	if (!ctlr->transfer_one_message)
1896 		ctlr->transfer_one_message = spi_transfer_one_message;
1897 
1898 	/* Initialize and start queue */
1899 	ret = spi_init_queue(ctlr);
1900 	if (ret) {
1901 		dev_err(&ctlr->dev, "problem initializing queue\n");
1902 		goto err_init_queue;
1903 	}
1904 	ctlr->queued = true;
1905 	ret = spi_start_queue(ctlr);
1906 	if (ret) {
1907 		dev_err(&ctlr->dev, "problem starting queue\n");
1908 		goto err_start_queue;
1909 	}
1910 
1911 	return 0;
1912 
1913 err_start_queue:
1914 	spi_destroy_queue(ctlr);
1915 err_init_queue:
1916 	return ret;
1917 }
1918 
1919 /**
1920  * spi_flush_queue - Send all pending messages in the queue from the callers'
1921  *		     context
1922  * @ctlr: controller to process queue for
1923  *
1924  * This should be used when one wants to ensure all pending messages have been
1925  * sent before doing something. Is used by the spi-mem code to make sure SPI
1926  * memory operations do not preempt regular SPI transfers that have been queued
1927  * before the spi-mem operation.
1928  */
spi_flush_queue(struct spi_controller * ctlr)1929 void spi_flush_queue(struct spi_controller *ctlr)
1930 {
1931 	if (ctlr->transfer == spi_queued_transfer)
1932 		__spi_pump_messages(ctlr, false);
1933 }
1934 
1935 /*-------------------------------------------------------------------------*/
1936 
1937 #if defined(CONFIG_OF)
of_spi_parse_dt(struct spi_controller * ctlr,struct spi_device * spi,struct device_node * nc)1938 static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
1939 			   struct device_node *nc)
1940 {
1941 	u32 value;
1942 	int rc;
1943 
1944 	/* Mode (clock phase/polarity/etc.) */
1945 	if (of_property_read_bool(nc, "spi-cpha"))
1946 		spi->mode |= SPI_CPHA;
1947 	if (of_property_read_bool(nc, "spi-cpol"))
1948 		spi->mode |= SPI_CPOL;
1949 	if (of_property_read_bool(nc, "spi-3wire"))
1950 		spi->mode |= SPI_3WIRE;
1951 	if (of_property_read_bool(nc, "spi-lsb-first"))
1952 		spi->mode |= SPI_LSB_FIRST;
1953 	if (of_property_read_bool(nc, "spi-cs-high"))
1954 		spi->mode |= SPI_CS_HIGH;
1955 
1956 	/* Device DUAL/QUAD mode */
1957 	if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
1958 		switch (value) {
1959 		case 1:
1960 			break;
1961 		case 2:
1962 			spi->mode |= SPI_TX_DUAL;
1963 			break;
1964 		case 4:
1965 			spi->mode |= SPI_TX_QUAD;
1966 			break;
1967 		case 8:
1968 			spi->mode |= SPI_TX_OCTAL;
1969 			break;
1970 		default:
1971 			dev_warn(&ctlr->dev,
1972 				"spi-tx-bus-width %d not supported\n",
1973 				value);
1974 			break;
1975 		}
1976 	}
1977 
1978 	if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
1979 		switch (value) {
1980 		case 1:
1981 			break;
1982 		case 2:
1983 			spi->mode |= SPI_RX_DUAL;
1984 			break;
1985 		case 4:
1986 			spi->mode |= SPI_RX_QUAD;
1987 			break;
1988 		case 8:
1989 			spi->mode |= SPI_RX_OCTAL;
1990 			break;
1991 		default:
1992 			dev_warn(&ctlr->dev,
1993 				"spi-rx-bus-width %d not supported\n",
1994 				value);
1995 			break;
1996 		}
1997 	}
1998 
1999 	if (spi_controller_is_slave(ctlr)) {
2000 		if (!of_node_name_eq(nc, "slave")) {
2001 			dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
2002 				nc);
2003 			return -EINVAL;
2004 		}
2005 		return 0;
2006 	}
2007 
2008 	/* Device address */
2009 	rc = of_property_read_u32(nc, "reg", &value);
2010 	if (rc) {
2011 		dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
2012 			nc, rc);
2013 		return rc;
2014 	}
2015 	spi->chip_select = value;
2016 
2017 	/* Device speed */
2018 	if (!of_property_read_u32(nc, "spi-max-frequency", &value))
2019 		spi->max_speed_hz = value;
2020 
2021 	return 0;
2022 }
2023 
2024 static struct spi_device *
of_register_spi_device(struct spi_controller * ctlr,struct device_node * nc)2025 of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
2026 {
2027 	struct spi_device *spi;
2028 	int rc;
2029 
2030 	/* Alloc an spi_device */
2031 	spi = spi_alloc_device(ctlr);
2032 	if (!spi) {
2033 		dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
2034 		rc = -ENOMEM;
2035 		goto err_out;
2036 	}
2037 
2038 	/* Select device driver */
2039 	rc = of_modalias_node(nc, spi->modalias,
2040 				sizeof(spi->modalias));
2041 	if (rc < 0) {
2042 		dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
2043 		goto err_out;
2044 	}
2045 
2046 	rc = of_spi_parse_dt(ctlr, spi, nc);
2047 	if (rc)
2048 		goto err_out;
2049 
2050 	/* Store a pointer to the node in the device structure */
2051 	of_node_get(nc);
2052 	spi->dev.of_node = nc;
2053 	spi->dev.fwnode = of_fwnode_handle(nc);
2054 
2055 	/* Register the new device */
2056 	rc = spi_add_device(spi);
2057 	if (rc) {
2058 		dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
2059 		goto err_of_node_put;
2060 	}
2061 
2062 	return spi;
2063 
2064 err_of_node_put:
2065 	of_node_put(nc);
2066 err_out:
2067 	spi_dev_put(spi);
2068 	return ERR_PTR(rc);
2069 }
2070 
2071 /**
2072  * of_register_spi_devices() - Register child devices onto the SPI bus
2073  * @ctlr:	Pointer to spi_controller device
2074  *
2075  * Registers an spi_device for each child node of controller node which
2076  * represents a valid SPI slave.
2077  */
of_register_spi_devices(struct spi_controller * ctlr)2078 static void of_register_spi_devices(struct spi_controller *ctlr)
2079 {
2080 	struct spi_device *spi;
2081 	struct device_node *nc;
2082 
2083 	if (!ctlr->dev.of_node)
2084 		return;
2085 
2086 	for_each_available_child_of_node(ctlr->dev.of_node, nc) {
2087 		if (of_node_test_and_set_flag(nc, OF_POPULATED))
2088 			continue;
2089 		spi = of_register_spi_device(ctlr, nc);
2090 		if (IS_ERR(spi)) {
2091 			dev_warn(&ctlr->dev,
2092 				 "Failed to create SPI device for %pOF\n", nc);
2093 			of_node_clear_flag(nc, OF_POPULATED);
2094 		}
2095 	}
2096 }
2097 #else
of_register_spi_devices(struct spi_controller * ctlr)2098 static void of_register_spi_devices(struct spi_controller *ctlr) { }
2099 #endif
2100 
2101 #ifdef CONFIG_ACPI
2102 struct acpi_spi_lookup {
2103 	struct spi_controller 	*ctlr;
2104 	u32			max_speed_hz;
2105 	u32			mode;
2106 	int			irq;
2107 	u8			bits_per_word;
2108 	u8			chip_select;
2109 };
2110 
acpi_spi_parse_apple_properties(struct acpi_device * dev,struct acpi_spi_lookup * lookup)2111 static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
2112 					    struct acpi_spi_lookup *lookup)
2113 {
2114 	const union acpi_object *obj;
2115 
2116 	if (!x86_apple_machine)
2117 		return;
2118 
2119 	if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
2120 	    && obj->buffer.length >= 4)
2121 		lookup->max_speed_hz  = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
2122 
2123 	if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
2124 	    && obj->buffer.length == 8)
2125 		lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
2126 
2127 	if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
2128 	    && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
2129 		lookup->mode |= SPI_LSB_FIRST;
2130 
2131 	if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
2132 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
2133 		lookup->mode |= SPI_CPOL;
2134 
2135 	if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
2136 	    && obj->buffer.length == 8 &&  *(u64 *)obj->buffer.pointer)
2137 		lookup->mode |= SPI_CPHA;
2138 }
2139 
acpi_spi_add_resource(struct acpi_resource * ares,void * data)2140 static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
2141 {
2142 	struct acpi_spi_lookup *lookup = data;
2143 	struct spi_controller *ctlr = lookup->ctlr;
2144 
2145 	if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
2146 		struct acpi_resource_spi_serialbus *sb;
2147 		acpi_handle parent_handle;
2148 		acpi_status status;
2149 
2150 		sb = &ares->data.spi_serial_bus;
2151 		if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
2152 
2153 			status = acpi_get_handle(NULL,
2154 						 sb->resource_source.string_ptr,
2155 						 &parent_handle);
2156 
2157 			if (ACPI_FAILURE(status) ||
2158 			    ACPI_HANDLE(ctlr->dev.parent) != parent_handle)
2159 				return -ENODEV;
2160 
2161 			/*
2162 			 * ACPI DeviceSelection numbering is handled by the
2163 			 * host controller driver in Windows and can vary
2164 			 * from driver to driver. In Linux we always expect
2165 			 * 0 .. max - 1 so we need to ask the driver to
2166 			 * translate between the two schemes.
2167 			 */
2168 			if (ctlr->fw_translate_cs) {
2169 				int cs = ctlr->fw_translate_cs(ctlr,
2170 						sb->device_selection);
2171 				if (cs < 0)
2172 					return cs;
2173 				lookup->chip_select = cs;
2174 			} else {
2175 				lookup->chip_select = sb->device_selection;
2176 			}
2177 
2178 			lookup->max_speed_hz = sb->connection_speed;
2179 			lookup->bits_per_word = sb->data_bit_length;
2180 
2181 			if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
2182 				lookup->mode |= SPI_CPHA;
2183 			if (sb->clock_polarity == ACPI_SPI_START_HIGH)
2184 				lookup->mode |= SPI_CPOL;
2185 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
2186 				lookup->mode |= SPI_CS_HIGH;
2187 		}
2188 	} else if (lookup->irq < 0) {
2189 		struct resource r;
2190 
2191 		if (acpi_dev_resource_interrupt(ares, 0, &r))
2192 			lookup->irq = r.start;
2193 	}
2194 
2195 	/* Always tell the ACPI core to skip this resource */
2196 	return 1;
2197 }
2198 
acpi_register_spi_device(struct spi_controller * ctlr,struct acpi_device * adev)2199 static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
2200 					    struct acpi_device *adev)
2201 {
2202 	acpi_handle parent_handle = NULL;
2203 	struct list_head resource_list;
2204 	struct acpi_spi_lookup lookup = {};
2205 	struct spi_device *spi;
2206 	int ret;
2207 
2208 	if (acpi_bus_get_status(adev) || !adev->status.present ||
2209 	    acpi_device_enumerated(adev))
2210 		return AE_OK;
2211 
2212 	lookup.ctlr		= ctlr;
2213 	lookup.irq		= -1;
2214 
2215 	INIT_LIST_HEAD(&resource_list);
2216 	ret = acpi_dev_get_resources(adev, &resource_list,
2217 				     acpi_spi_add_resource, &lookup);
2218 	acpi_dev_free_resource_list(&resource_list);
2219 
2220 	if (ret < 0)
2221 		/* found SPI in _CRS but it points to another controller */
2222 		return AE_OK;
2223 
2224 	if (!lookup.max_speed_hz &&
2225 	    !ACPI_FAILURE(acpi_get_parent(adev->handle, &parent_handle)) &&
2226 	    ACPI_HANDLE(ctlr->dev.parent) == parent_handle) {
2227 		/* Apple does not use _CRS but nested devices for SPI slaves */
2228 		acpi_spi_parse_apple_properties(adev, &lookup);
2229 	}
2230 
2231 	if (!lookup.max_speed_hz)
2232 		return AE_OK;
2233 
2234 	spi = spi_alloc_device(ctlr);
2235 	if (!spi) {
2236 		dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
2237 			dev_name(&adev->dev));
2238 		return AE_NO_MEMORY;
2239 	}
2240 
2241 
2242 	ACPI_COMPANION_SET(&spi->dev, adev);
2243 	spi->max_speed_hz	= lookup.max_speed_hz;
2244 	spi->mode		|= lookup.mode;
2245 	spi->irq		= lookup.irq;
2246 	spi->bits_per_word	= lookup.bits_per_word;
2247 	spi->chip_select	= lookup.chip_select;
2248 
2249 	acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
2250 			  sizeof(spi->modalias));
2251 
2252 	if (spi->irq < 0)
2253 		spi->irq = acpi_dev_gpio_irq_get(adev, 0);
2254 
2255 	acpi_device_set_enumerated(adev);
2256 
2257 	adev->power.flags.ignore_parent = true;
2258 	if (spi_add_device(spi)) {
2259 		adev->power.flags.ignore_parent = false;
2260 		dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
2261 			dev_name(&adev->dev));
2262 		spi_dev_put(spi);
2263 	}
2264 
2265 	return AE_OK;
2266 }
2267 
acpi_spi_add_device(acpi_handle handle,u32 level,void * data,void ** return_value)2268 static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
2269 				       void *data, void **return_value)
2270 {
2271 	struct spi_controller *ctlr = data;
2272 	struct acpi_device *adev;
2273 
2274 	if (acpi_bus_get_device(handle, &adev))
2275 		return AE_OK;
2276 
2277 	return acpi_register_spi_device(ctlr, adev);
2278 }
2279 
2280 #define SPI_ACPI_ENUMERATE_MAX_DEPTH		32
2281 
acpi_register_spi_devices(struct spi_controller * ctlr)2282 static void acpi_register_spi_devices(struct spi_controller *ctlr)
2283 {
2284 	acpi_status status;
2285 	acpi_handle handle;
2286 
2287 	handle = ACPI_HANDLE(ctlr->dev.parent);
2288 	if (!handle)
2289 		return;
2290 
2291 	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
2292 				     SPI_ACPI_ENUMERATE_MAX_DEPTH,
2293 				     acpi_spi_add_device, NULL, ctlr, NULL);
2294 	if (ACPI_FAILURE(status))
2295 		dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
2296 }
2297 #else
acpi_register_spi_devices(struct spi_controller * ctlr)2298 static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
2299 #endif /* CONFIG_ACPI */
2300 
spi_controller_release(struct device * dev)2301 static void spi_controller_release(struct device *dev)
2302 {
2303 	struct spi_controller *ctlr;
2304 
2305 	ctlr = container_of(dev, struct spi_controller, dev);
2306 	kfree(ctlr);
2307 }
2308 
2309 static struct class spi_master_class = {
2310 	.name		= "spi_master",
2311 	.owner		= THIS_MODULE,
2312 	.dev_release	= spi_controller_release,
2313 	.dev_groups	= spi_master_groups,
2314 };
2315 
2316 #ifdef CONFIG_SPI_SLAVE
2317 /**
2318  * spi_slave_abort - abort the ongoing transfer request on an SPI slave
2319  *		     controller
2320  * @spi: device used for the current transfer
2321  */
spi_slave_abort(struct spi_device * spi)2322 int spi_slave_abort(struct spi_device *spi)
2323 {
2324 	struct spi_controller *ctlr = spi->controller;
2325 
2326 	if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
2327 		return ctlr->slave_abort(ctlr);
2328 
2329 	return -ENOTSUPP;
2330 }
2331 EXPORT_SYMBOL_GPL(spi_slave_abort);
2332 
match_true(struct device * dev,void * data)2333 static int match_true(struct device *dev, void *data)
2334 {
2335 	return 1;
2336 }
2337 
slave_show(struct device * dev,struct device_attribute * attr,char * buf)2338 static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
2339 			  char *buf)
2340 {
2341 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2342 						   dev);
2343 	struct device *child;
2344 
2345 	child = device_find_child(&ctlr->dev, NULL, match_true);
2346 	return sprintf(buf, "%s\n",
2347 		       child ? to_spi_device(child)->modalias : NULL);
2348 }
2349 
slave_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2350 static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
2351 			   const char *buf, size_t count)
2352 {
2353 	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
2354 						   dev);
2355 	struct spi_device *spi;
2356 	struct device *child;
2357 	char name[32];
2358 	int rc;
2359 
2360 	rc = sscanf(buf, "%31s", name);
2361 	if (rc != 1 || !name[0])
2362 		return -EINVAL;
2363 
2364 	child = device_find_child(&ctlr->dev, NULL, match_true);
2365 	if (child) {
2366 		/* Remove registered slave */
2367 		device_unregister(child);
2368 		put_device(child);
2369 	}
2370 
2371 	if (strcmp(name, "(null)")) {
2372 		/* Register new slave */
2373 		spi = spi_alloc_device(ctlr);
2374 		if (!spi)
2375 			return -ENOMEM;
2376 
2377 		strlcpy(spi->modalias, name, sizeof(spi->modalias));
2378 
2379 		rc = spi_add_device(spi);
2380 		if (rc) {
2381 			spi_dev_put(spi);
2382 			return rc;
2383 		}
2384 	}
2385 
2386 	return count;
2387 }
2388 
2389 static DEVICE_ATTR_RW(slave);
2390 
2391 static struct attribute *spi_slave_attrs[] = {
2392 	&dev_attr_slave.attr,
2393 	NULL,
2394 };
2395 
2396 static const struct attribute_group spi_slave_group = {
2397 	.attrs = spi_slave_attrs,
2398 };
2399 
2400 static const struct attribute_group *spi_slave_groups[] = {
2401 	&spi_controller_statistics_group,
2402 	&spi_slave_group,
2403 	NULL,
2404 };
2405 
2406 static struct class spi_slave_class = {
2407 	.name		= "spi_slave",
2408 	.owner		= THIS_MODULE,
2409 	.dev_release	= spi_controller_release,
2410 	.dev_groups	= spi_slave_groups,
2411 };
2412 #else
2413 extern struct class spi_slave_class;	/* dummy */
2414 #endif
2415 
2416 /**
2417  * __spi_alloc_controller - allocate an SPI master or slave controller
2418  * @dev: the controller, possibly using the platform_bus
2419  * @size: how much zeroed driver-private data to allocate; the pointer to this
2420  *	memory is in the driver_data field of the returned device, accessible
2421  *	with spi_controller_get_devdata(); the memory is cacheline aligned;
2422  *	drivers granting DMA access to portions of their private data need to
2423  *	round up @size using ALIGN(size, dma_get_cache_alignment()).
2424  * @slave: flag indicating whether to allocate an SPI master (false) or SPI
2425  *	slave (true) controller
2426  * Context: can sleep
2427  *
2428  * This call is used only by SPI controller drivers, which are the
2429  * only ones directly touching chip registers.  It's how they allocate
2430  * an spi_controller structure, prior to calling spi_register_controller().
2431  *
2432  * This must be called from context that can sleep.
2433  *
2434  * The caller is responsible for assigning the bus number and initializing the
2435  * controller's methods before calling spi_register_controller(); and (after
2436  * errors adding the device) calling spi_controller_put() to prevent a memory
2437  * leak.
2438  *
2439  * Return: the SPI controller structure on success, else NULL.
2440  */
__spi_alloc_controller(struct device * dev,unsigned int size,bool slave)2441 struct spi_controller *__spi_alloc_controller(struct device *dev,
2442 					      unsigned int size, bool slave)
2443 {
2444 	struct spi_controller	*ctlr;
2445 	size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
2446 
2447 	if (!dev)
2448 		return NULL;
2449 
2450 	ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
2451 	if (!ctlr)
2452 		return NULL;
2453 
2454 	device_initialize(&ctlr->dev);
2455 	ctlr->bus_num = -1;
2456 	ctlr->num_chipselect = 1;
2457 	ctlr->slave = slave;
2458 	if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
2459 		ctlr->dev.class = &spi_slave_class;
2460 	else
2461 		ctlr->dev.class = &spi_master_class;
2462 	ctlr->dev.parent = dev;
2463 	pm_suspend_ignore_children(&ctlr->dev, true);
2464 	spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
2465 
2466 	return ctlr;
2467 }
2468 EXPORT_SYMBOL_GPL(__spi_alloc_controller);
2469 
devm_spi_release_controller(struct device * dev,void * ctlr)2470 static void devm_spi_release_controller(struct device *dev, void *ctlr)
2471 {
2472 	spi_controller_put(*(struct spi_controller **)ctlr);
2473 }
2474 
2475 /**
2476  * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
2477  * @dev: physical device of SPI controller
2478  * @size: how much zeroed driver-private data to allocate
2479  * @slave: whether to allocate an SPI master (false) or SPI slave (true)
2480  * Context: can sleep
2481  *
2482  * Allocate an SPI controller and automatically release a reference on it
2483  * when @dev is unbound from its driver.  Drivers are thus relieved from
2484  * having to call spi_controller_put().
2485  *
2486  * The arguments to this function are identical to __spi_alloc_controller().
2487  *
2488  * Return: the SPI controller structure on success, else NULL.
2489  */
__devm_spi_alloc_controller(struct device * dev,unsigned int size,bool slave)2490 struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
2491 						   unsigned int size,
2492 						   bool slave)
2493 {
2494 	struct spi_controller **ptr, *ctlr;
2495 
2496 	ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
2497 			   GFP_KERNEL);
2498 	if (!ptr)
2499 		return NULL;
2500 
2501 	ctlr = __spi_alloc_controller(dev, size, slave);
2502 	if (ctlr) {
2503 		ctlr->devm_allocated = true;
2504 		*ptr = ctlr;
2505 		devres_add(dev, ptr);
2506 	} else {
2507 		devres_free(ptr);
2508 	}
2509 
2510 	return ctlr;
2511 }
2512 EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
2513 
2514 #ifdef CONFIG_OF
of_spi_get_gpio_numbers(struct spi_controller * ctlr)2515 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2516 {
2517 	int nb, i, *cs;
2518 	struct device_node *np = ctlr->dev.of_node;
2519 
2520 	if (!np)
2521 		return 0;
2522 
2523 	nb = of_gpio_named_count(np, "cs-gpios");
2524 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2525 
2526 	/* Return error only for an incorrectly formed cs-gpios property */
2527 	if (nb == 0 || nb == -ENOENT)
2528 		return 0;
2529 	else if (nb < 0)
2530 		return nb;
2531 
2532 	cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
2533 			  GFP_KERNEL);
2534 	ctlr->cs_gpios = cs;
2535 
2536 	if (!ctlr->cs_gpios)
2537 		return -ENOMEM;
2538 
2539 	for (i = 0; i < ctlr->num_chipselect; i++)
2540 		cs[i] = -ENOENT;
2541 
2542 	for (i = 0; i < nb; i++)
2543 		cs[i] = of_get_named_gpio(np, "cs-gpios", i);
2544 
2545 	return 0;
2546 }
2547 #else
of_spi_get_gpio_numbers(struct spi_controller * ctlr)2548 static int of_spi_get_gpio_numbers(struct spi_controller *ctlr)
2549 {
2550 	return 0;
2551 }
2552 #endif
2553 
2554 /**
2555  * spi_get_gpio_descs() - grab chip select GPIOs for the master
2556  * @ctlr: The SPI master to grab GPIO descriptors for
2557  */
spi_get_gpio_descs(struct spi_controller * ctlr)2558 static int spi_get_gpio_descs(struct spi_controller *ctlr)
2559 {
2560 	int nb, i;
2561 	struct gpio_desc **cs;
2562 	struct device *dev = &ctlr->dev;
2563 	unsigned long native_cs_mask = 0;
2564 	unsigned int num_cs_gpios = 0;
2565 
2566 	nb = gpiod_count(dev, "cs");
2567 	ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
2568 
2569 	/* No GPIOs at all is fine, else return the error */
2570 	if (nb == 0 || nb == -ENOENT)
2571 		return 0;
2572 	else if (nb < 0)
2573 		return nb;
2574 
2575 	cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
2576 			  GFP_KERNEL);
2577 	if (!cs)
2578 		return -ENOMEM;
2579 	ctlr->cs_gpiods = cs;
2580 
2581 	for (i = 0; i < nb; i++) {
2582 		/*
2583 		 * Most chipselects are active low, the inverted
2584 		 * semantics are handled by special quirks in gpiolib,
2585 		 * so initializing them GPIOD_OUT_LOW here means
2586 		 * "unasserted", in most cases this will drive the physical
2587 		 * line high.
2588 		 */
2589 		cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
2590 						      GPIOD_OUT_LOW);
2591 		if (IS_ERR(cs[i]))
2592 			return PTR_ERR(cs[i]);
2593 
2594 		if (cs[i]) {
2595 			/*
2596 			 * If we find a CS GPIO, name it after the device and
2597 			 * chip select line.
2598 			 */
2599 			char *gpioname;
2600 
2601 			gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
2602 						  dev_name(dev), i);
2603 			if (!gpioname)
2604 				return -ENOMEM;
2605 			gpiod_set_consumer_name(cs[i], gpioname);
2606 			num_cs_gpios++;
2607 			continue;
2608 		}
2609 
2610 		if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
2611 			dev_err(dev, "Invalid native chip select %d\n", i);
2612 			return -EINVAL;
2613 		}
2614 		native_cs_mask |= BIT(i);
2615 	}
2616 
2617 	ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
2618 
2619 	if ((ctlr->flags & SPI_MASTER_GPIO_SS) && num_cs_gpios &&
2620 	    ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
2621 		dev_err(dev, "No unused native chip select available\n");
2622 		return -EINVAL;
2623 	}
2624 
2625 	return 0;
2626 }
2627 
spi_controller_check_ops(struct spi_controller * ctlr)2628 static int spi_controller_check_ops(struct spi_controller *ctlr)
2629 {
2630 	/*
2631 	 * The controller may implement only the high-level SPI-memory like
2632 	 * operations if it does not support regular SPI transfers, and this is
2633 	 * valid use case.
2634 	 * If ->mem_ops is NULL, we request that at least one of the
2635 	 * ->transfer_xxx() method be implemented.
2636 	 */
2637 	if (ctlr->mem_ops) {
2638 		if (!ctlr->mem_ops->exec_op)
2639 			return -EINVAL;
2640 	} else if (!ctlr->transfer && !ctlr->transfer_one &&
2641 		   !ctlr->transfer_one_message) {
2642 		return -EINVAL;
2643 	}
2644 
2645 	return 0;
2646 }
2647 
2648 /**
2649  * spi_register_controller - register SPI master or slave controller
2650  * @ctlr: initialized master, originally from spi_alloc_master() or
2651  *	spi_alloc_slave()
2652  * Context: can sleep
2653  *
2654  * SPI controllers connect to their drivers using some non-SPI bus,
2655  * such as the platform bus.  The final stage of probe() in that code
2656  * includes calling spi_register_controller() to hook up to this SPI bus glue.
2657  *
2658  * SPI controllers use board specific (often SOC specific) bus numbers,
2659  * and board-specific addressing for SPI devices combines those numbers
2660  * with chip select numbers.  Since SPI does not directly support dynamic
2661  * device identification, boards need configuration tables telling which
2662  * chip is at which address.
2663  *
2664  * This must be called from context that can sleep.  It returns zero on
2665  * success, else a negative error code (dropping the controller's refcount).
2666  * After a successful return, the caller is responsible for calling
2667  * spi_unregister_controller().
2668  *
2669  * Return: zero on success, else a negative error code.
2670  */
spi_register_controller(struct spi_controller * ctlr)2671 int spi_register_controller(struct spi_controller *ctlr)
2672 {
2673 	struct device		*dev = ctlr->dev.parent;
2674 	struct boardinfo	*bi;
2675 	int			status;
2676 	int			id, first_dynamic;
2677 
2678 	if (!dev)
2679 		return -ENODEV;
2680 
2681 	/*
2682 	 * Make sure all necessary hooks are implemented before registering
2683 	 * the SPI controller.
2684 	 */
2685 	status = spi_controller_check_ops(ctlr);
2686 	if (status)
2687 		return status;
2688 
2689 	if (ctlr->bus_num >= 0) {
2690 		/* devices with a fixed bus num must check-in with the num */
2691 		mutex_lock(&board_lock);
2692 		id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2693 			ctlr->bus_num + 1, GFP_KERNEL);
2694 		mutex_unlock(&board_lock);
2695 		if (WARN(id < 0, "couldn't get idr"))
2696 			return id == -ENOSPC ? -EBUSY : id;
2697 		ctlr->bus_num = id;
2698 	} else if (ctlr->dev.of_node) {
2699 		/* allocate dynamic bus number using Linux idr */
2700 		id = of_alias_get_id(ctlr->dev.of_node, "spi");
2701 		if (id >= 0) {
2702 			ctlr->bus_num = id;
2703 			mutex_lock(&board_lock);
2704 			id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
2705 				       ctlr->bus_num + 1, GFP_KERNEL);
2706 			mutex_unlock(&board_lock);
2707 			if (WARN(id < 0, "couldn't get idr"))
2708 				return id == -ENOSPC ? -EBUSY : id;
2709 		}
2710 	}
2711 	if (ctlr->bus_num < 0) {
2712 		first_dynamic = of_alias_get_highest_id("spi");
2713 		if (first_dynamic < 0)
2714 			first_dynamic = 0;
2715 		else
2716 			first_dynamic++;
2717 
2718 		mutex_lock(&board_lock);
2719 		id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
2720 			       0, GFP_KERNEL);
2721 		mutex_unlock(&board_lock);
2722 		if (WARN(id < 0, "couldn't get idr"))
2723 			return id;
2724 		ctlr->bus_num = id;
2725 	}
2726 	INIT_LIST_HEAD(&ctlr->queue);
2727 	spin_lock_init(&ctlr->queue_lock);
2728 	spin_lock_init(&ctlr->bus_lock_spinlock);
2729 	mutex_init(&ctlr->bus_lock_mutex);
2730 	mutex_init(&ctlr->io_mutex);
2731 	ctlr->bus_lock_flag = 0;
2732 	init_completion(&ctlr->xfer_completion);
2733 	if (!ctlr->max_dma_len)
2734 		ctlr->max_dma_len = INT_MAX;
2735 
2736 	/* register the device, then userspace will see it.
2737 	 * registration fails if the bus ID is in use.
2738 	 */
2739 	dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
2740 
2741 	if (!spi_controller_is_slave(ctlr)) {
2742 		if (ctlr->use_gpio_descriptors) {
2743 			status = spi_get_gpio_descs(ctlr);
2744 			if (status)
2745 				goto free_bus_id;
2746 			/*
2747 			 * A controller using GPIO descriptors always
2748 			 * supports SPI_CS_HIGH if need be.
2749 			 */
2750 			ctlr->mode_bits |= SPI_CS_HIGH;
2751 		} else {
2752 			/* Legacy code path for GPIOs from DT */
2753 			status = of_spi_get_gpio_numbers(ctlr);
2754 			if (status)
2755 				goto free_bus_id;
2756 		}
2757 	}
2758 
2759 	/*
2760 	 * Even if it's just one always-selected device, there must
2761 	 * be at least one chipselect.
2762 	 */
2763 	if (!ctlr->num_chipselect) {
2764 		status = -EINVAL;
2765 		goto free_bus_id;
2766 	}
2767 
2768 	status = device_add(&ctlr->dev);
2769 	if (status < 0)
2770 		goto free_bus_id;
2771 	dev_dbg(dev, "registered %s %s\n",
2772 			spi_controller_is_slave(ctlr) ? "slave" : "master",
2773 			dev_name(&ctlr->dev));
2774 
2775 	/*
2776 	 * If we're using a queued driver, start the queue. Note that we don't
2777 	 * need the queueing logic if the driver is only supporting high-level
2778 	 * memory operations.
2779 	 */
2780 	if (ctlr->transfer) {
2781 		dev_info(dev, "controller is unqueued, this is deprecated\n");
2782 	} else if (ctlr->transfer_one || ctlr->transfer_one_message) {
2783 		status = spi_controller_initialize_queue(ctlr);
2784 		if (status) {
2785 			device_del(&ctlr->dev);
2786 			goto free_bus_id;
2787 		}
2788 	}
2789 	/* add statistics */
2790 	spin_lock_init(&ctlr->statistics.lock);
2791 
2792 	mutex_lock(&board_lock);
2793 	list_add_tail(&ctlr->list, &spi_controller_list);
2794 	list_for_each_entry(bi, &board_list, list)
2795 		spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
2796 	mutex_unlock(&board_lock);
2797 
2798 	/* Register devices from the device tree and ACPI */
2799 	of_register_spi_devices(ctlr);
2800 	acpi_register_spi_devices(ctlr);
2801 	return status;
2802 
2803 free_bus_id:
2804 	mutex_lock(&board_lock);
2805 	idr_remove(&spi_master_idr, ctlr->bus_num);
2806 	mutex_unlock(&board_lock);
2807 	return status;
2808 }
2809 EXPORT_SYMBOL_GPL(spi_register_controller);
2810 
devm_spi_unregister(struct device * dev,void * res)2811 static void devm_spi_unregister(struct device *dev, void *res)
2812 {
2813 	spi_unregister_controller(*(struct spi_controller **)res);
2814 }
2815 
2816 /**
2817  * devm_spi_register_controller - register managed SPI master or slave
2818  *	controller
2819  * @dev:    device managing SPI controller
2820  * @ctlr: initialized controller, originally from spi_alloc_master() or
2821  *	spi_alloc_slave()
2822  * Context: can sleep
2823  *
2824  * Register a SPI device as with spi_register_controller() which will
2825  * automatically be unregistered and freed.
2826  *
2827  * Return: zero on success, else a negative error code.
2828  */
devm_spi_register_controller(struct device * dev,struct spi_controller * ctlr)2829 int devm_spi_register_controller(struct device *dev,
2830 				 struct spi_controller *ctlr)
2831 {
2832 	struct spi_controller **ptr;
2833 	int ret;
2834 
2835 	ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
2836 	if (!ptr)
2837 		return -ENOMEM;
2838 
2839 	ret = spi_register_controller(ctlr);
2840 	if (!ret) {
2841 		*ptr = ctlr;
2842 		devres_add(dev, ptr);
2843 	} else {
2844 		devres_free(ptr);
2845 	}
2846 
2847 	return ret;
2848 }
2849 EXPORT_SYMBOL_GPL(devm_spi_register_controller);
2850 
__unregister(struct device * dev,void * null)2851 static int __unregister(struct device *dev, void *null)
2852 {
2853 	spi_unregister_device(to_spi_device(dev));
2854 	return 0;
2855 }
2856 
2857 /**
2858  * spi_unregister_controller - unregister SPI master or slave controller
2859  * @ctlr: the controller being unregistered
2860  * Context: can sleep
2861  *
2862  * This call is used only by SPI controller drivers, which are the
2863  * only ones directly touching chip registers.
2864  *
2865  * This must be called from context that can sleep.
2866  *
2867  * Note that this function also drops a reference to the controller.
2868  */
spi_unregister_controller(struct spi_controller * ctlr)2869 void spi_unregister_controller(struct spi_controller *ctlr)
2870 {
2871 	struct spi_controller *found;
2872 	int id = ctlr->bus_num;
2873 
2874 	/* Prevent addition of new devices, unregister existing ones */
2875 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2876 		mutex_lock(&spi_add_lock);
2877 
2878 	device_for_each_child(&ctlr->dev, NULL, __unregister);
2879 
2880 	/* First make sure that this controller was ever added */
2881 	mutex_lock(&board_lock);
2882 	found = idr_find(&spi_master_idr, id);
2883 	mutex_unlock(&board_lock);
2884 	if (ctlr->queued) {
2885 		if (spi_destroy_queue(ctlr))
2886 			dev_err(&ctlr->dev, "queue remove failed\n");
2887 	}
2888 	mutex_lock(&board_lock);
2889 	list_del(&ctlr->list);
2890 	mutex_unlock(&board_lock);
2891 
2892 	device_del(&ctlr->dev);
2893 
2894 	/* Release the last reference on the controller if its driver
2895 	 * has not yet been converted to devm_spi_alloc_master/slave().
2896 	 */
2897 	if (!ctlr->devm_allocated)
2898 		put_device(&ctlr->dev);
2899 
2900 	/* free bus id */
2901 	mutex_lock(&board_lock);
2902 	if (found == ctlr)
2903 		idr_remove(&spi_master_idr, id);
2904 	mutex_unlock(&board_lock);
2905 
2906 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
2907 		mutex_unlock(&spi_add_lock);
2908 }
2909 EXPORT_SYMBOL_GPL(spi_unregister_controller);
2910 
spi_controller_suspend(struct spi_controller * ctlr)2911 int spi_controller_suspend(struct spi_controller *ctlr)
2912 {
2913 	int ret;
2914 
2915 	/* Basically no-ops for non-queued controllers */
2916 	if (!ctlr->queued)
2917 		return 0;
2918 
2919 	ret = spi_stop_queue(ctlr);
2920 	if (ret)
2921 		dev_err(&ctlr->dev, "queue stop failed\n");
2922 
2923 	return ret;
2924 }
2925 EXPORT_SYMBOL_GPL(spi_controller_suspend);
2926 
spi_controller_resume(struct spi_controller * ctlr)2927 int spi_controller_resume(struct spi_controller *ctlr)
2928 {
2929 	int ret;
2930 
2931 	if (!ctlr->queued)
2932 		return 0;
2933 
2934 	ret = spi_start_queue(ctlr);
2935 	if (ret)
2936 		dev_err(&ctlr->dev, "queue restart failed\n");
2937 
2938 	return ret;
2939 }
2940 EXPORT_SYMBOL_GPL(spi_controller_resume);
2941 
__spi_controller_match(struct device * dev,const void * data)2942 static int __spi_controller_match(struct device *dev, const void *data)
2943 {
2944 	struct spi_controller *ctlr;
2945 	const u16 *bus_num = data;
2946 
2947 	ctlr = container_of(dev, struct spi_controller, dev);
2948 	return ctlr->bus_num == *bus_num;
2949 }
2950 
2951 /**
2952  * spi_busnum_to_master - look up master associated with bus_num
2953  * @bus_num: the master's bus number
2954  * Context: can sleep
2955  *
2956  * This call may be used with devices that are registered after
2957  * arch init time.  It returns a refcounted pointer to the relevant
2958  * spi_controller (which the caller must release), or NULL if there is
2959  * no such master registered.
2960  *
2961  * Return: the SPI master structure on success, else NULL.
2962  */
spi_busnum_to_master(u16 bus_num)2963 struct spi_controller *spi_busnum_to_master(u16 bus_num)
2964 {
2965 	struct device		*dev;
2966 	struct spi_controller	*ctlr = NULL;
2967 
2968 	dev = class_find_device(&spi_master_class, NULL, &bus_num,
2969 				__spi_controller_match);
2970 	if (dev)
2971 		ctlr = container_of(dev, struct spi_controller, dev);
2972 	/* reference got in class_find_device */
2973 	return ctlr;
2974 }
2975 EXPORT_SYMBOL_GPL(spi_busnum_to_master);
2976 
2977 /*-------------------------------------------------------------------------*/
2978 
2979 /* Core methods for SPI resource management */
2980 
2981 /**
2982  * spi_res_alloc - allocate a spi resource that is life-cycle managed
2983  *                 during the processing of a spi_message while using
2984  *                 spi_transfer_one
2985  * @spi:     the spi device for which we allocate memory
2986  * @release: the release code to execute for this resource
2987  * @size:    size to alloc and return
2988  * @gfp:     GFP allocation flags
2989  *
2990  * Return: the pointer to the allocated data
2991  *
2992  * This may get enhanced in the future to allocate from a memory pool
2993  * of the @spi_device or @spi_controller to avoid repeated allocations.
2994  */
spi_res_alloc(struct spi_device * spi,spi_res_release_t release,size_t size,gfp_t gfp)2995 void *spi_res_alloc(struct spi_device *spi,
2996 		    spi_res_release_t release,
2997 		    size_t size, gfp_t gfp)
2998 {
2999 	struct spi_res *sres;
3000 
3001 	sres = kzalloc(sizeof(*sres) + size, gfp);
3002 	if (!sres)
3003 		return NULL;
3004 
3005 	INIT_LIST_HEAD(&sres->entry);
3006 	sres->release = release;
3007 
3008 	return sres->data;
3009 }
3010 EXPORT_SYMBOL_GPL(spi_res_alloc);
3011 
3012 /**
3013  * spi_res_free - free an spi resource
3014  * @res: pointer to the custom data of a resource
3015  *
3016  */
spi_res_free(void * res)3017 void spi_res_free(void *res)
3018 {
3019 	struct spi_res *sres = container_of(res, struct spi_res, data);
3020 
3021 	if (!res)
3022 		return;
3023 
3024 	WARN_ON(!list_empty(&sres->entry));
3025 	kfree(sres);
3026 }
3027 EXPORT_SYMBOL_GPL(spi_res_free);
3028 
3029 /**
3030  * spi_res_add - add a spi_res to the spi_message
3031  * @message: the spi message
3032  * @res:     the spi_resource
3033  */
spi_res_add(struct spi_message * message,void * res)3034 void spi_res_add(struct spi_message *message, void *res)
3035 {
3036 	struct spi_res *sres = container_of(res, struct spi_res, data);
3037 
3038 	WARN_ON(!list_empty(&sres->entry));
3039 	list_add_tail(&sres->entry, &message->resources);
3040 }
3041 EXPORT_SYMBOL_GPL(spi_res_add);
3042 
3043 /**
3044  * spi_res_release - release all spi resources for this message
3045  * @ctlr:  the @spi_controller
3046  * @message: the @spi_message
3047  */
spi_res_release(struct spi_controller * ctlr,struct spi_message * message)3048 void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
3049 {
3050 	struct spi_res *res, *tmp;
3051 
3052 	list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
3053 		if (res->release)
3054 			res->release(ctlr, message, res->data);
3055 
3056 		list_del(&res->entry);
3057 
3058 		kfree(res);
3059 	}
3060 }
3061 EXPORT_SYMBOL_GPL(spi_res_release);
3062 
3063 /*-------------------------------------------------------------------------*/
3064 
3065 /* Core methods for spi_message alterations */
3066 
__spi_replace_transfers_release(struct spi_controller * ctlr,struct spi_message * msg,void * res)3067 static void __spi_replace_transfers_release(struct spi_controller *ctlr,
3068 					    struct spi_message *msg,
3069 					    void *res)
3070 {
3071 	struct spi_replaced_transfers *rxfer = res;
3072 	size_t i;
3073 
3074 	/* call extra callback if requested */
3075 	if (rxfer->release)
3076 		rxfer->release(ctlr, msg, res);
3077 
3078 	/* insert replaced transfers back into the message */
3079 	list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
3080 
3081 	/* remove the formerly inserted entries */
3082 	for (i = 0; i < rxfer->inserted; i++)
3083 		list_del(&rxfer->inserted_transfers[i].transfer_list);
3084 }
3085 
3086 /**
3087  * spi_replace_transfers - replace transfers with several transfers
3088  *                         and register change with spi_message.resources
3089  * @msg:           the spi_message we work upon
3090  * @xfer_first:    the first spi_transfer we want to replace
3091  * @remove:        number of transfers to remove
3092  * @insert:        the number of transfers we want to insert instead
3093  * @release:       extra release code necessary in some circumstances
3094  * @extradatasize: extra data to allocate (with alignment guarantees
3095  *                 of struct @spi_transfer)
3096  * @gfp:           gfp flags
3097  *
3098  * Returns: pointer to @spi_replaced_transfers,
3099  *          PTR_ERR(...) in case of errors.
3100  */
spi_replace_transfers(struct spi_message * msg,struct spi_transfer * xfer_first,size_t remove,size_t insert,spi_replaced_release_t release,size_t extradatasize,gfp_t gfp)3101 struct spi_replaced_transfers *spi_replace_transfers(
3102 	struct spi_message *msg,
3103 	struct spi_transfer *xfer_first,
3104 	size_t remove,
3105 	size_t insert,
3106 	spi_replaced_release_t release,
3107 	size_t extradatasize,
3108 	gfp_t gfp)
3109 {
3110 	struct spi_replaced_transfers *rxfer;
3111 	struct spi_transfer *xfer;
3112 	size_t i;
3113 
3114 	/* allocate the structure using spi_res */
3115 	rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
3116 			      struct_size(rxfer, inserted_transfers, insert)
3117 			      + extradatasize,
3118 			      gfp);
3119 	if (!rxfer)
3120 		return ERR_PTR(-ENOMEM);
3121 
3122 	/* the release code to invoke before running the generic release */
3123 	rxfer->release = release;
3124 
3125 	/* assign extradata */
3126 	if (extradatasize)
3127 		rxfer->extradata =
3128 			&rxfer->inserted_transfers[insert];
3129 
3130 	/* init the replaced_transfers list */
3131 	INIT_LIST_HEAD(&rxfer->replaced_transfers);
3132 
3133 	/* assign the list_entry after which we should reinsert
3134 	 * the @replaced_transfers - it may be spi_message.messages!
3135 	 */
3136 	rxfer->replaced_after = xfer_first->transfer_list.prev;
3137 
3138 	/* remove the requested number of transfers */
3139 	for (i = 0; i < remove; i++) {
3140 		/* if the entry after replaced_after it is msg->transfers
3141 		 * then we have been requested to remove more transfers
3142 		 * than are in the list
3143 		 */
3144 		if (rxfer->replaced_after->next == &msg->transfers) {
3145 			dev_err(&msg->spi->dev,
3146 				"requested to remove more spi_transfers than are available\n");
3147 			/* insert replaced transfers back into the message */
3148 			list_splice(&rxfer->replaced_transfers,
3149 				    rxfer->replaced_after);
3150 
3151 			/* free the spi_replace_transfer structure */
3152 			spi_res_free(rxfer);
3153 
3154 			/* and return with an error */
3155 			return ERR_PTR(-EINVAL);
3156 		}
3157 
3158 		/* remove the entry after replaced_after from list of
3159 		 * transfers and add it to list of replaced_transfers
3160 		 */
3161 		list_move_tail(rxfer->replaced_after->next,
3162 			       &rxfer->replaced_transfers);
3163 	}
3164 
3165 	/* create copy of the given xfer with identical settings
3166 	 * based on the first transfer to get removed
3167 	 */
3168 	for (i = 0; i < insert; i++) {
3169 		/* we need to run in reverse order */
3170 		xfer = &rxfer->inserted_transfers[insert - 1 - i];
3171 
3172 		/* copy all spi_transfer data */
3173 		memcpy(xfer, xfer_first, sizeof(*xfer));
3174 
3175 		/* add to list */
3176 		list_add(&xfer->transfer_list, rxfer->replaced_after);
3177 
3178 		/* clear cs_change and delay for all but the last */
3179 		if (i) {
3180 			xfer->cs_change = false;
3181 			xfer->delay_usecs = 0;
3182 			xfer->delay.value = 0;
3183 		}
3184 	}
3185 
3186 	/* set up inserted */
3187 	rxfer->inserted = insert;
3188 
3189 	/* and register it with spi_res/spi_message */
3190 	spi_res_add(msg, rxfer);
3191 
3192 	return rxfer;
3193 }
3194 EXPORT_SYMBOL_GPL(spi_replace_transfers);
3195 
__spi_split_transfer_maxsize(struct spi_controller * ctlr,struct spi_message * msg,struct spi_transfer ** xferp,size_t maxsize,gfp_t gfp)3196 static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
3197 					struct spi_message *msg,
3198 					struct spi_transfer **xferp,
3199 					size_t maxsize,
3200 					gfp_t gfp)
3201 {
3202 	struct spi_transfer *xfer = *xferp, *xfers;
3203 	struct spi_replaced_transfers *srt;
3204 	size_t offset;
3205 	size_t count, i;
3206 
3207 	/* calculate how many we have to replace */
3208 	count = DIV_ROUND_UP(xfer->len, maxsize);
3209 
3210 	/* create replacement */
3211 	srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
3212 	if (IS_ERR(srt))
3213 		return PTR_ERR(srt);
3214 	xfers = srt->inserted_transfers;
3215 
3216 	/* now handle each of those newly inserted spi_transfers
3217 	 * note that the replacements spi_transfers all are preset
3218 	 * to the same values as *xferp, so tx_buf, rx_buf and len
3219 	 * are all identical (as well as most others)
3220 	 * so we just have to fix up len and the pointers.
3221 	 *
3222 	 * this also includes support for the depreciated
3223 	 * spi_message.is_dma_mapped interface
3224 	 */
3225 
3226 	/* the first transfer just needs the length modified, so we
3227 	 * run it outside the loop
3228 	 */
3229 	xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
3230 
3231 	/* all the others need rx_buf/tx_buf also set */
3232 	for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
3233 		/* update rx_buf, tx_buf and dma */
3234 		if (xfers[i].rx_buf)
3235 			xfers[i].rx_buf += offset;
3236 		if (xfers[i].rx_dma)
3237 			xfers[i].rx_dma += offset;
3238 		if (xfers[i].tx_buf)
3239 			xfers[i].tx_buf += offset;
3240 		if (xfers[i].tx_dma)
3241 			xfers[i].tx_dma += offset;
3242 
3243 		/* update length */
3244 		xfers[i].len = min(maxsize, xfers[i].len - offset);
3245 	}
3246 
3247 	/* we set up xferp to the last entry we have inserted,
3248 	 * so that we skip those already split transfers
3249 	 */
3250 	*xferp = &xfers[count - 1];
3251 
3252 	/* increment statistics counters */
3253 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3254 				       transfers_split_maxsize);
3255 	SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
3256 				       transfers_split_maxsize);
3257 
3258 	return 0;
3259 }
3260 
3261 /**
3262  * spi_split_tranfers_maxsize - split spi transfers into multiple transfers
3263  *                              when an individual transfer exceeds a
3264  *                              certain size
3265  * @ctlr:    the @spi_controller for this transfer
3266  * @msg:   the @spi_message to transform
3267  * @maxsize:  the maximum when to apply this
3268  * @gfp: GFP allocation flags
3269  *
3270  * Return: status of transformation
3271  */
spi_split_transfers_maxsize(struct spi_controller * ctlr,struct spi_message * msg,size_t maxsize,gfp_t gfp)3272 int spi_split_transfers_maxsize(struct spi_controller *ctlr,
3273 				struct spi_message *msg,
3274 				size_t maxsize,
3275 				gfp_t gfp)
3276 {
3277 	struct spi_transfer *xfer;
3278 	int ret;
3279 
3280 	/* iterate over the transfer_list,
3281 	 * but note that xfer is advanced to the last transfer inserted
3282 	 * to avoid checking sizes again unnecessarily (also xfer does
3283 	 * potentiall belong to a different list by the time the
3284 	 * replacement has happened
3285 	 */
3286 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
3287 		if (xfer->len > maxsize) {
3288 			ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
3289 							   maxsize, gfp);
3290 			if (ret)
3291 				return ret;
3292 		}
3293 	}
3294 
3295 	return 0;
3296 }
3297 EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
3298 
3299 /*-------------------------------------------------------------------------*/
3300 
3301 /* Core methods for SPI controller protocol drivers.  Some of the
3302  * other core methods are currently defined as inline functions.
3303  */
3304 
__spi_validate_bits_per_word(struct spi_controller * ctlr,u8 bits_per_word)3305 static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
3306 					u8 bits_per_word)
3307 {
3308 	if (ctlr->bits_per_word_mask) {
3309 		/* Only 32 bits fit in the mask */
3310 		if (bits_per_word > 32)
3311 			return -EINVAL;
3312 		if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
3313 			return -EINVAL;
3314 	}
3315 
3316 	return 0;
3317 }
3318 
3319 /**
3320  * spi_setup - setup SPI mode and clock rate
3321  * @spi: the device whose settings are being modified
3322  * Context: can sleep, and no requests are queued to the device
3323  *
3324  * SPI protocol drivers may need to update the transfer mode if the
3325  * device doesn't work with its default.  They may likewise need
3326  * to update clock rates or word sizes from initial values.  This function
3327  * changes those settings, and must be called from a context that can sleep.
3328  * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
3329  * effect the next time the device is selected and data is transferred to
3330  * or from it.  When this function returns, the spi device is deselected.
3331  *
3332  * Note that this call will fail if the protocol driver specifies an option
3333  * that the underlying controller or its driver does not support.  For
3334  * example, not all hardware supports wire transfers using nine bit words,
3335  * LSB-first wire encoding, or active-high chipselects.
3336  *
3337  * Return: zero on success, else a negative error code.
3338  */
spi_setup(struct spi_device * spi)3339 int spi_setup(struct spi_device *spi)
3340 {
3341 	unsigned	bad_bits, ugly_bits;
3342 	int		status;
3343 
3344 	/* check mode to prevent that DUAL and QUAD set at the same time
3345 	 */
3346 	if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
3347 		((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
3348 		dev_err(&spi->dev,
3349 		"setup: can not select dual and quad at the same time\n");
3350 		return -EINVAL;
3351 	}
3352 	/* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
3353 	 */
3354 	if ((spi->mode & SPI_3WIRE) && (spi->mode &
3355 		(SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3356 		 SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
3357 		return -EINVAL;
3358 	/* help drivers fail *cleanly* when they need options
3359 	 * that aren't supported with their current controller
3360 	 * SPI_CS_WORD has a fallback software implementation,
3361 	 * so it is ignored here.
3362 	 */
3363 	bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD);
3364 	/* nothing prevents from working with active-high CS in case if it
3365 	 * is driven by GPIO.
3366 	 */
3367 	if (gpio_is_valid(spi->cs_gpio))
3368 		bad_bits &= ~SPI_CS_HIGH;
3369 	ugly_bits = bad_bits &
3370 		    (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
3371 		     SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
3372 	if (ugly_bits) {
3373 		dev_warn(&spi->dev,
3374 			 "setup: ignoring unsupported mode bits %x\n",
3375 			 ugly_bits);
3376 		spi->mode &= ~ugly_bits;
3377 		bad_bits &= ~ugly_bits;
3378 	}
3379 	if (bad_bits) {
3380 		dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
3381 			bad_bits);
3382 		return -EINVAL;
3383 	}
3384 
3385 	if (!spi->bits_per_word)
3386 		spi->bits_per_word = 8;
3387 
3388 	status = __spi_validate_bits_per_word(spi->controller,
3389 					      spi->bits_per_word);
3390 	if (status)
3391 		return status;
3392 
3393 	if (!spi->max_speed_hz)
3394 		spi->max_speed_hz = spi->controller->max_speed_hz;
3395 
3396 	mutex_lock(&spi->controller->io_mutex);
3397 
3398 	if (spi->controller->setup)
3399 		status = spi->controller->setup(spi);
3400 
3401 	if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
3402 		status = pm_runtime_get_sync(spi->controller->dev.parent);
3403 		if (status < 0) {
3404 			mutex_unlock(&spi->controller->io_mutex);
3405 			pm_runtime_put_noidle(spi->controller->dev.parent);
3406 			dev_err(&spi->controller->dev, "Failed to power device: %d\n",
3407 				status);
3408 			return status;
3409 		}
3410 
3411 		/*
3412 		 * We do not want to return positive value from pm_runtime_get,
3413 		 * there are many instances of devices calling spi_setup() and
3414 		 * checking for a non-zero return value instead of a negative
3415 		 * return value.
3416 		 */
3417 		status = 0;
3418 
3419 		spi_set_cs(spi, false, true);
3420 		pm_runtime_mark_last_busy(spi->controller->dev.parent);
3421 		pm_runtime_put_autosuspend(spi->controller->dev.parent);
3422 	} else {
3423 		spi_set_cs(spi, false, true);
3424 	}
3425 
3426 	mutex_unlock(&spi->controller->io_mutex);
3427 
3428 	if (spi->rt && !spi->controller->rt) {
3429 		spi->controller->rt = true;
3430 		spi_set_thread_rt(spi->controller);
3431 	}
3432 
3433 	dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
3434 			(int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
3435 			(spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
3436 			(spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
3437 			(spi->mode & SPI_3WIRE) ? "3wire, " : "",
3438 			(spi->mode & SPI_LOOP) ? "loopback, " : "",
3439 			spi->bits_per_word, spi->max_speed_hz,
3440 			status);
3441 
3442 	return status;
3443 }
3444 EXPORT_SYMBOL_GPL(spi_setup);
3445 
3446 /**
3447  * spi_set_cs_timing - configure CS setup, hold, and inactive delays
3448  * @spi: the device that requires specific CS timing configuration
3449  * @setup: CS setup time specified via @spi_delay
3450  * @hold: CS hold time specified via @spi_delay
3451  * @inactive: CS inactive delay between transfers specified via @spi_delay
3452  *
3453  * Return: zero on success, else a negative error code.
3454  */
spi_set_cs_timing(struct spi_device * spi,struct spi_delay * setup,struct spi_delay * hold,struct spi_delay * inactive)3455 int spi_set_cs_timing(struct spi_device *spi, struct spi_delay *setup,
3456 		      struct spi_delay *hold, struct spi_delay *inactive)
3457 {
3458 	size_t len;
3459 
3460 	if (spi->controller->set_cs_timing)
3461 		return spi->controller->set_cs_timing(spi, setup, hold,
3462 						      inactive);
3463 
3464 	if ((setup && setup->unit == SPI_DELAY_UNIT_SCK) ||
3465 	    (hold && hold->unit == SPI_DELAY_UNIT_SCK) ||
3466 	    (inactive && inactive->unit == SPI_DELAY_UNIT_SCK)) {
3467 		dev_err(&spi->dev,
3468 			"Clock-cycle delays for CS not supported in SW mode\n");
3469 		return -ENOTSUPP;
3470 	}
3471 
3472 	len = sizeof(struct spi_delay);
3473 
3474 	/* copy delays to controller */
3475 	if (setup)
3476 		memcpy(&spi->controller->cs_setup, setup, len);
3477 	else
3478 		memset(&spi->controller->cs_setup, 0, len);
3479 
3480 	if (hold)
3481 		memcpy(&spi->controller->cs_hold, hold, len);
3482 	else
3483 		memset(&spi->controller->cs_hold, 0, len);
3484 
3485 	if (inactive)
3486 		memcpy(&spi->controller->cs_inactive, inactive, len);
3487 	else
3488 		memset(&spi->controller->cs_inactive, 0, len);
3489 
3490 	return 0;
3491 }
3492 EXPORT_SYMBOL_GPL(spi_set_cs_timing);
3493 
_spi_xfer_word_delay_update(struct spi_transfer * xfer,struct spi_device * spi)3494 static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
3495 				       struct spi_device *spi)
3496 {
3497 	int delay1, delay2;
3498 
3499 	delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
3500 	if (delay1 < 0)
3501 		return delay1;
3502 
3503 	delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
3504 	if (delay2 < 0)
3505 		return delay2;
3506 
3507 	if (delay1 < delay2)
3508 		memcpy(&xfer->word_delay, &spi->word_delay,
3509 		       sizeof(xfer->word_delay));
3510 
3511 	return 0;
3512 }
3513 
__spi_validate(struct spi_device * spi,struct spi_message * message)3514 static int __spi_validate(struct spi_device *spi, struct spi_message *message)
3515 {
3516 	struct spi_controller *ctlr = spi->controller;
3517 	struct spi_transfer *xfer;
3518 	int w_size;
3519 
3520 	if (list_empty(&message->transfers))
3521 		return -EINVAL;
3522 
3523 	/* If an SPI controller does not support toggling the CS line on each
3524 	 * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
3525 	 * for the CS line, we can emulate the CS-per-word hardware function by
3526 	 * splitting transfers into one-word transfers and ensuring that
3527 	 * cs_change is set for each transfer.
3528 	 */
3529 	if ((spi->mode & SPI_CS_WORD) && (!(ctlr->mode_bits & SPI_CS_WORD) ||
3530 					  spi->cs_gpiod ||
3531 					  gpio_is_valid(spi->cs_gpio))) {
3532 		size_t maxsize;
3533 		int ret;
3534 
3535 		maxsize = (spi->bits_per_word + 7) / 8;
3536 
3537 		/* spi_split_transfers_maxsize() requires message->spi */
3538 		message->spi = spi;
3539 
3540 		ret = spi_split_transfers_maxsize(ctlr, message, maxsize,
3541 						  GFP_KERNEL);
3542 		if (ret)
3543 			return ret;
3544 
3545 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3546 			/* don't change cs_change on the last entry in the list */
3547 			if (list_is_last(&xfer->transfer_list, &message->transfers))
3548 				break;
3549 			xfer->cs_change = 1;
3550 		}
3551 	}
3552 
3553 	/* Half-duplex links include original MicroWire, and ones with
3554 	 * only one data pin like SPI_3WIRE (switches direction) or where
3555 	 * either MOSI or MISO is missing.  They can also be caused by
3556 	 * software limitations.
3557 	 */
3558 	if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
3559 	    (spi->mode & SPI_3WIRE)) {
3560 		unsigned flags = ctlr->flags;
3561 
3562 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3563 			if (xfer->rx_buf && xfer->tx_buf)
3564 				return -EINVAL;
3565 			if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
3566 				return -EINVAL;
3567 			if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
3568 				return -EINVAL;
3569 		}
3570 	}
3571 
3572 	/**
3573 	 * Set transfer bits_per_word and max speed as spi device default if
3574 	 * it is not set for this transfer.
3575 	 * Set transfer tx_nbits and rx_nbits as single transfer default
3576 	 * (SPI_NBITS_SINGLE) if it is not set for this transfer.
3577 	 * Ensure transfer word_delay is at least as long as that required by
3578 	 * device itself.
3579 	 */
3580 	message->frame_length = 0;
3581 	list_for_each_entry(xfer, &message->transfers, transfer_list) {
3582 		xfer->effective_speed_hz = 0;
3583 		message->frame_length += xfer->len;
3584 		if (!xfer->bits_per_word)
3585 			xfer->bits_per_word = spi->bits_per_word;
3586 
3587 		if (!xfer->speed_hz)
3588 			xfer->speed_hz = spi->max_speed_hz;
3589 
3590 		if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
3591 			xfer->speed_hz = ctlr->max_speed_hz;
3592 
3593 		if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
3594 			return -EINVAL;
3595 
3596 		/*
3597 		 * SPI transfer length should be multiple of SPI word size
3598 		 * where SPI word size should be power-of-two multiple
3599 		 */
3600 		if (xfer->bits_per_word <= 8)
3601 			w_size = 1;
3602 		else if (xfer->bits_per_word <= 16)
3603 			w_size = 2;
3604 		else
3605 			w_size = 4;
3606 
3607 		/* No partial transfers accepted */
3608 		if (xfer->len % w_size)
3609 			return -EINVAL;
3610 
3611 		if (xfer->speed_hz && ctlr->min_speed_hz &&
3612 		    xfer->speed_hz < ctlr->min_speed_hz)
3613 			return -EINVAL;
3614 
3615 		if (xfer->tx_buf && !xfer->tx_nbits)
3616 			xfer->tx_nbits = SPI_NBITS_SINGLE;
3617 		if (xfer->rx_buf && !xfer->rx_nbits)
3618 			xfer->rx_nbits = SPI_NBITS_SINGLE;
3619 		/* check transfer tx/rx_nbits:
3620 		 * 1. check the value matches one of single, dual and quad
3621 		 * 2. check tx/rx_nbits match the mode in spi_device
3622 		 */
3623 		if (xfer->tx_buf) {
3624 			if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
3625 				xfer->tx_nbits != SPI_NBITS_DUAL &&
3626 				xfer->tx_nbits != SPI_NBITS_QUAD)
3627 				return -EINVAL;
3628 			if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
3629 				!(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
3630 				return -EINVAL;
3631 			if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
3632 				!(spi->mode & SPI_TX_QUAD))
3633 				return -EINVAL;
3634 		}
3635 		/* check transfer rx_nbits */
3636 		if (xfer->rx_buf) {
3637 			if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
3638 				xfer->rx_nbits != SPI_NBITS_DUAL &&
3639 				xfer->rx_nbits != SPI_NBITS_QUAD)
3640 				return -EINVAL;
3641 			if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
3642 				!(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
3643 				return -EINVAL;
3644 			if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
3645 				!(spi->mode & SPI_RX_QUAD))
3646 				return -EINVAL;
3647 		}
3648 
3649 		if (_spi_xfer_word_delay_update(xfer, spi))
3650 			return -EINVAL;
3651 	}
3652 
3653 	message->status = -EINPROGRESS;
3654 
3655 	return 0;
3656 }
3657 
__spi_async(struct spi_device * spi,struct spi_message * message)3658 static int __spi_async(struct spi_device *spi, struct spi_message *message)
3659 {
3660 	struct spi_controller *ctlr = spi->controller;
3661 	struct spi_transfer *xfer;
3662 
3663 	/*
3664 	 * Some controllers do not support doing regular SPI transfers. Return
3665 	 * ENOTSUPP when this is the case.
3666 	 */
3667 	if (!ctlr->transfer)
3668 		return -ENOTSUPP;
3669 
3670 	message->spi = spi;
3671 
3672 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
3673 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
3674 
3675 	trace_spi_message_submit(message);
3676 
3677 	if (!ctlr->ptp_sts_supported) {
3678 		list_for_each_entry(xfer, &message->transfers, transfer_list) {
3679 			xfer->ptp_sts_word_pre = 0;
3680 			ptp_read_system_prets(xfer->ptp_sts);
3681 		}
3682 	}
3683 
3684 	return ctlr->transfer(spi, message);
3685 }
3686 
3687 /**
3688  * spi_async - asynchronous SPI transfer
3689  * @spi: device with which data will be exchanged
3690  * @message: describes the data transfers, including completion callback
3691  * Context: any (irqs may be blocked, etc)
3692  *
3693  * This call may be used in_irq and other contexts which can't sleep,
3694  * as well as from task contexts which can sleep.
3695  *
3696  * The completion callback is invoked in a context which can't sleep.
3697  * Before that invocation, the value of message->status is undefined.
3698  * When the callback is issued, message->status holds either zero (to
3699  * indicate complete success) or a negative error code.  After that
3700  * callback returns, the driver which issued the transfer request may
3701  * deallocate the associated memory; it's no longer in use by any SPI
3702  * core or controller driver code.
3703  *
3704  * Note that although all messages to a spi_device are handled in
3705  * FIFO order, messages may go to different devices in other orders.
3706  * Some device might be higher priority, or have various "hard" access
3707  * time requirements, for example.
3708  *
3709  * On detection of any fault during the transfer, processing of
3710  * the entire message is aborted, and the device is deselected.
3711  * Until returning from the associated message completion callback,
3712  * no other spi_message queued to that device will be processed.
3713  * (This rule applies equally to all the synchronous transfer calls,
3714  * which are wrappers around this core asynchronous primitive.)
3715  *
3716  * Return: zero on success, else a negative error code.
3717  */
spi_async(struct spi_device * spi,struct spi_message * message)3718 int spi_async(struct spi_device *spi, struct spi_message *message)
3719 {
3720 	struct spi_controller *ctlr = spi->controller;
3721 	int ret;
3722 	unsigned long flags;
3723 
3724 	ret = __spi_validate(spi, message);
3725 	if (ret != 0)
3726 		return ret;
3727 
3728 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3729 
3730 	if (ctlr->bus_lock_flag)
3731 		ret = -EBUSY;
3732 	else
3733 		ret = __spi_async(spi, message);
3734 
3735 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3736 
3737 	return ret;
3738 }
3739 EXPORT_SYMBOL_GPL(spi_async);
3740 
3741 /**
3742  * spi_async_locked - version of spi_async with exclusive bus usage
3743  * @spi: device with which data will be exchanged
3744  * @message: describes the data transfers, including completion callback
3745  * Context: any (irqs may be blocked, etc)
3746  *
3747  * This call may be used in_irq and other contexts which can't sleep,
3748  * as well as from task contexts which can sleep.
3749  *
3750  * The completion callback is invoked in a context which can't sleep.
3751  * Before that invocation, the value of message->status is undefined.
3752  * When the callback is issued, message->status holds either zero (to
3753  * indicate complete success) or a negative error code.  After that
3754  * callback returns, the driver which issued the transfer request may
3755  * deallocate the associated memory; it's no longer in use by any SPI
3756  * core or controller driver code.
3757  *
3758  * Note that although all messages to a spi_device are handled in
3759  * FIFO order, messages may go to different devices in other orders.
3760  * Some device might be higher priority, or have various "hard" access
3761  * time requirements, for example.
3762  *
3763  * On detection of any fault during the transfer, processing of
3764  * the entire message is aborted, and the device is deselected.
3765  * Until returning from the associated message completion callback,
3766  * no other spi_message queued to that device will be processed.
3767  * (This rule applies equally to all the synchronous transfer calls,
3768  * which are wrappers around this core asynchronous primitive.)
3769  *
3770  * Return: zero on success, else a negative error code.
3771  */
spi_async_locked(struct spi_device * spi,struct spi_message * message)3772 int spi_async_locked(struct spi_device *spi, struct spi_message *message)
3773 {
3774 	struct spi_controller *ctlr = spi->controller;
3775 	int ret;
3776 	unsigned long flags;
3777 
3778 	ret = __spi_validate(spi, message);
3779 	if (ret != 0)
3780 		return ret;
3781 
3782 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3783 
3784 	ret = __spi_async(spi, message);
3785 
3786 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3787 
3788 	return ret;
3789 
3790 }
3791 EXPORT_SYMBOL_GPL(spi_async_locked);
3792 
3793 /*-------------------------------------------------------------------------*/
3794 
3795 /* Utility methods for SPI protocol drivers, layered on
3796  * top of the core.  Some other utility methods are defined as
3797  * inline functions.
3798  */
3799 
spi_complete(void * arg)3800 static void spi_complete(void *arg)
3801 {
3802 	complete(arg);
3803 }
3804 
__spi_sync(struct spi_device * spi,struct spi_message * message)3805 static int __spi_sync(struct spi_device *spi, struct spi_message *message)
3806 {
3807 	DECLARE_COMPLETION_ONSTACK(done);
3808 	int status;
3809 	struct spi_controller *ctlr = spi->controller;
3810 	unsigned long flags;
3811 
3812 	status = __spi_validate(spi, message);
3813 	if (status != 0)
3814 		return status;
3815 
3816 	message->complete = spi_complete;
3817 	message->context = &done;
3818 	message->spi = spi;
3819 
3820 	SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
3821 	SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
3822 
3823 	/* If we're not using the legacy transfer method then we will
3824 	 * try to transfer in the calling context so special case.
3825 	 * This code would be less tricky if we could remove the
3826 	 * support for driver implemented message queues.
3827 	 */
3828 	if (ctlr->transfer == spi_queued_transfer) {
3829 		spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3830 
3831 		trace_spi_message_submit(message);
3832 
3833 		status = __spi_queued_transfer(spi, message, false);
3834 
3835 		spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3836 	} else {
3837 		status = spi_async_locked(spi, message);
3838 	}
3839 
3840 	if (status == 0) {
3841 		/* Push out the messages in the calling context if we
3842 		 * can.
3843 		 */
3844 		if (ctlr->transfer == spi_queued_transfer) {
3845 			SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
3846 						       spi_sync_immediate);
3847 			SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
3848 						       spi_sync_immediate);
3849 			__spi_pump_messages(ctlr, false);
3850 		}
3851 
3852 		wait_for_completion(&done);
3853 		status = message->status;
3854 	}
3855 	message->context = NULL;
3856 	return status;
3857 }
3858 
3859 /**
3860  * spi_sync - blocking/synchronous SPI data transfers
3861  * @spi: device with which data will be exchanged
3862  * @message: describes the data transfers
3863  * Context: can sleep
3864  *
3865  * This call may only be used from a context that may sleep.  The sleep
3866  * is non-interruptible, and has no timeout.  Low-overhead controller
3867  * drivers may DMA directly into and out of the message buffers.
3868  *
3869  * Note that the SPI device's chip select is active during the message,
3870  * and then is normally disabled between messages.  Drivers for some
3871  * frequently-used devices may want to minimize costs of selecting a chip,
3872  * by leaving it selected in anticipation that the next message will go
3873  * to the same chip.  (That may increase power usage.)
3874  *
3875  * Also, the caller is guaranteeing that the memory associated with the
3876  * message will not be freed before this call returns.
3877  *
3878  * Return: zero on success, else a negative error code.
3879  */
spi_sync(struct spi_device * spi,struct spi_message * message)3880 int spi_sync(struct spi_device *spi, struct spi_message *message)
3881 {
3882 	int ret;
3883 
3884 	mutex_lock(&spi->controller->bus_lock_mutex);
3885 	ret = __spi_sync(spi, message);
3886 	mutex_unlock(&spi->controller->bus_lock_mutex);
3887 
3888 	return ret;
3889 }
3890 EXPORT_SYMBOL_GPL(spi_sync);
3891 
3892 /**
3893  * spi_sync_locked - version of spi_sync with exclusive bus usage
3894  * @spi: device with which data will be exchanged
3895  * @message: describes the data transfers
3896  * Context: can sleep
3897  *
3898  * This call may only be used from a context that may sleep.  The sleep
3899  * is non-interruptible, and has no timeout.  Low-overhead controller
3900  * drivers may DMA directly into and out of the message buffers.
3901  *
3902  * This call should be used by drivers that require exclusive access to the
3903  * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
3904  * be released by a spi_bus_unlock call when the exclusive access is over.
3905  *
3906  * Return: zero on success, else a negative error code.
3907  */
spi_sync_locked(struct spi_device * spi,struct spi_message * message)3908 int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
3909 {
3910 	return __spi_sync(spi, message);
3911 }
3912 EXPORT_SYMBOL_GPL(spi_sync_locked);
3913 
3914 /**
3915  * spi_bus_lock - obtain a lock for exclusive SPI bus usage
3916  * @ctlr: SPI bus master that should be locked for exclusive bus access
3917  * Context: can sleep
3918  *
3919  * This call may only be used from a context that may sleep.  The sleep
3920  * is non-interruptible, and has no timeout.
3921  *
3922  * This call should be used by drivers that require exclusive access to the
3923  * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
3924  * exclusive access is over. Data transfer must be done by spi_sync_locked
3925  * and spi_async_locked calls when the SPI bus lock is held.
3926  *
3927  * Return: always zero.
3928  */
spi_bus_lock(struct spi_controller * ctlr)3929 int spi_bus_lock(struct spi_controller *ctlr)
3930 {
3931 	unsigned long flags;
3932 
3933 	mutex_lock(&ctlr->bus_lock_mutex);
3934 
3935 	spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
3936 	ctlr->bus_lock_flag = 1;
3937 	spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
3938 
3939 	/* mutex remains locked until spi_bus_unlock is called */
3940 
3941 	return 0;
3942 }
3943 EXPORT_SYMBOL_GPL(spi_bus_lock);
3944 
3945 /**
3946  * spi_bus_unlock - release the lock for exclusive SPI bus usage
3947  * @ctlr: SPI bus master that was locked for exclusive bus access
3948  * Context: can sleep
3949  *
3950  * This call may only be used from a context that may sleep.  The sleep
3951  * is non-interruptible, and has no timeout.
3952  *
3953  * This call releases an SPI bus lock previously obtained by an spi_bus_lock
3954  * call.
3955  *
3956  * Return: always zero.
3957  */
spi_bus_unlock(struct spi_controller * ctlr)3958 int spi_bus_unlock(struct spi_controller *ctlr)
3959 {
3960 	ctlr->bus_lock_flag = 0;
3961 
3962 	mutex_unlock(&ctlr->bus_lock_mutex);
3963 
3964 	return 0;
3965 }
3966 EXPORT_SYMBOL_GPL(spi_bus_unlock);
3967 
3968 /* portable code must never pass more than 32 bytes */
3969 #define	SPI_BUFSIZ	max(32, SMP_CACHE_BYTES)
3970 
3971 static u8	*buf;
3972 
3973 /**
3974  * spi_write_then_read - SPI synchronous write followed by read
3975  * @spi: device with which data will be exchanged
3976  * @txbuf: data to be written (need not be dma-safe)
3977  * @n_tx: size of txbuf, in bytes
3978  * @rxbuf: buffer into which data will be read (need not be dma-safe)
3979  * @n_rx: size of rxbuf, in bytes
3980  * Context: can sleep
3981  *
3982  * This performs a half duplex MicroWire style transaction with the
3983  * device, sending txbuf and then reading rxbuf.  The return value
3984  * is zero for success, else a negative errno status code.
3985  * This call may only be used from a context that may sleep.
3986  *
3987  * Parameters to this routine are always copied using a small buffer.
3988  * Performance-sensitive or bulk transfer code should instead use
3989  * spi_{async,sync}() calls with dma-safe buffers.
3990  *
3991  * Return: zero on success, else a negative error code.
3992  */
spi_write_then_read(struct spi_device * spi,const void * txbuf,unsigned n_tx,void * rxbuf,unsigned n_rx)3993 int spi_write_then_read(struct spi_device *spi,
3994 		const void *txbuf, unsigned n_tx,
3995 		void *rxbuf, unsigned n_rx)
3996 {
3997 	static DEFINE_MUTEX(lock);
3998 
3999 	int			status;
4000 	struct spi_message	message;
4001 	struct spi_transfer	x[2];
4002 	u8			*local_buf;
4003 
4004 	/* Use preallocated DMA-safe buffer if we can.  We can't avoid
4005 	 * copying here, (as a pure convenience thing), but we can
4006 	 * keep heap costs out of the hot path unless someone else is
4007 	 * using the pre-allocated buffer or the transfer is too large.
4008 	 */
4009 	if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
4010 		local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
4011 				    GFP_KERNEL | GFP_DMA);
4012 		if (!local_buf)
4013 			return -ENOMEM;
4014 	} else {
4015 		local_buf = buf;
4016 	}
4017 
4018 	spi_message_init(&message);
4019 	memset(x, 0, sizeof(x));
4020 	if (n_tx) {
4021 		x[0].len = n_tx;
4022 		spi_message_add_tail(&x[0], &message);
4023 	}
4024 	if (n_rx) {
4025 		x[1].len = n_rx;
4026 		spi_message_add_tail(&x[1], &message);
4027 	}
4028 
4029 	memcpy(local_buf, txbuf, n_tx);
4030 	x[0].tx_buf = local_buf;
4031 	x[1].rx_buf = local_buf + n_tx;
4032 
4033 	/* do the i/o */
4034 	status = spi_sync(spi, &message);
4035 	if (status == 0)
4036 		memcpy(rxbuf, x[1].rx_buf, n_rx);
4037 
4038 	if (x[0].tx_buf == buf)
4039 		mutex_unlock(&lock);
4040 	else
4041 		kfree(local_buf);
4042 
4043 	return status;
4044 }
4045 EXPORT_SYMBOL_GPL(spi_write_then_read);
4046 
4047 /*-------------------------------------------------------------------------*/
4048 
4049 #if IS_ENABLED(CONFIG_OF)
4050 /* must call put_device() when done with returned spi_device device */
of_find_spi_device_by_node(struct device_node * node)4051 struct spi_device *of_find_spi_device_by_node(struct device_node *node)
4052 {
4053 	struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
4054 
4055 	return dev ? to_spi_device(dev) : NULL;
4056 }
4057 EXPORT_SYMBOL_GPL(of_find_spi_device_by_node);
4058 #endif /* IS_ENABLED(CONFIG_OF) */
4059 
4060 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
4061 /* the spi controllers are not using spi_bus, so we find it with another way */
of_find_spi_controller_by_node(struct device_node * node)4062 static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
4063 {
4064 	struct device *dev;
4065 
4066 	dev = class_find_device_by_of_node(&spi_master_class, node);
4067 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4068 		dev = class_find_device_by_of_node(&spi_slave_class, node);
4069 	if (!dev)
4070 		return NULL;
4071 
4072 	/* reference got in class_find_device */
4073 	return container_of(dev, struct spi_controller, dev);
4074 }
4075 
of_spi_notify(struct notifier_block * nb,unsigned long action,void * arg)4076 static int of_spi_notify(struct notifier_block *nb, unsigned long action,
4077 			 void *arg)
4078 {
4079 	struct of_reconfig_data *rd = arg;
4080 	struct spi_controller *ctlr;
4081 	struct spi_device *spi;
4082 
4083 	switch (of_reconfig_get_state_change(action, arg)) {
4084 	case OF_RECONFIG_CHANGE_ADD:
4085 		ctlr = of_find_spi_controller_by_node(rd->dn->parent);
4086 		if (ctlr == NULL)
4087 			return NOTIFY_OK;	/* not for us */
4088 
4089 		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
4090 			put_device(&ctlr->dev);
4091 			return NOTIFY_OK;
4092 		}
4093 
4094 		spi = of_register_spi_device(ctlr, rd->dn);
4095 		put_device(&ctlr->dev);
4096 
4097 		if (IS_ERR(spi)) {
4098 			pr_err("%s: failed to create for '%pOF'\n",
4099 					__func__, rd->dn);
4100 			of_node_clear_flag(rd->dn, OF_POPULATED);
4101 			return notifier_from_errno(PTR_ERR(spi));
4102 		}
4103 		break;
4104 
4105 	case OF_RECONFIG_CHANGE_REMOVE:
4106 		/* already depopulated? */
4107 		if (!of_node_check_flag(rd->dn, OF_POPULATED))
4108 			return NOTIFY_OK;
4109 
4110 		/* find our device by node */
4111 		spi = of_find_spi_device_by_node(rd->dn);
4112 		if (spi == NULL)
4113 			return NOTIFY_OK;	/* no? not meant for us */
4114 
4115 		/* unregister takes one ref away */
4116 		spi_unregister_device(spi);
4117 
4118 		/* and put the reference of the find */
4119 		put_device(&spi->dev);
4120 		break;
4121 	}
4122 
4123 	return NOTIFY_OK;
4124 }
4125 
4126 static struct notifier_block spi_of_notifier = {
4127 	.notifier_call = of_spi_notify,
4128 };
4129 #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4130 extern struct notifier_block spi_of_notifier;
4131 #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
4132 
4133 #if IS_ENABLED(CONFIG_ACPI)
spi_acpi_controller_match(struct device * dev,const void * data)4134 static int spi_acpi_controller_match(struct device *dev, const void *data)
4135 {
4136 	return ACPI_COMPANION(dev->parent) == data;
4137 }
4138 
acpi_spi_find_controller_by_adev(struct acpi_device * adev)4139 static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
4140 {
4141 	struct device *dev;
4142 
4143 	dev = class_find_device(&spi_master_class, NULL, adev,
4144 				spi_acpi_controller_match);
4145 	if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
4146 		dev = class_find_device(&spi_slave_class, NULL, adev,
4147 					spi_acpi_controller_match);
4148 	if (!dev)
4149 		return NULL;
4150 
4151 	return container_of(dev, struct spi_controller, dev);
4152 }
4153 
acpi_spi_find_device_by_adev(struct acpi_device * adev)4154 static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
4155 {
4156 	struct device *dev;
4157 
4158 	dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
4159 	return to_spi_device(dev);
4160 }
4161 
acpi_spi_notify(struct notifier_block * nb,unsigned long value,void * arg)4162 static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
4163 			   void *arg)
4164 {
4165 	struct acpi_device *adev = arg;
4166 	struct spi_controller *ctlr;
4167 	struct spi_device *spi;
4168 
4169 	switch (value) {
4170 	case ACPI_RECONFIG_DEVICE_ADD:
4171 		ctlr = acpi_spi_find_controller_by_adev(adev->parent);
4172 		if (!ctlr)
4173 			break;
4174 
4175 		acpi_register_spi_device(ctlr, adev);
4176 		put_device(&ctlr->dev);
4177 		break;
4178 	case ACPI_RECONFIG_DEVICE_REMOVE:
4179 		if (!acpi_device_enumerated(adev))
4180 			break;
4181 
4182 		spi = acpi_spi_find_device_by_adev(adev);
4183 		if (!spi)
4184 			break;
4185 
4186 		spi_unregister_device(spi);
4187 		put_device(&spi->dev);
4188 		break;
4189 	}
4190 
4191 	return NOTIFY_OK;
4192 }
4193 
4194 static struct notifier_block spi_acpi_notifier = {
4195 	.notifier_call = acpi_spi_notify,
4196 };
4197 #else
4198 extern struct notifier_block spi_acpi_notifier;
4199 #endif
4200 
spi_init(void)4201 static int __init spi_init(void)
4202 {
4203 	int	status;
4204 
4205 	buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
4206 	if (!buf) {
4207 		status = -ENOMEM;
4208 		goto err0;
4209 	}
4210 
4211 	status = bus_register(&spi_bus_type);
4212 	if (status < 0)
4213 		goto err1;
4214 
4215 	status = class_register(&spi_master_class);
4216 	if (status < 0)
4217 		goto err2;
4218 
4219 	if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
4220 		status = class_register(&spi_slave_class);
4221 		if (status < 0)
4222 			goto err3;
4223 	}
4224 
4225 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
4226 		WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
4227 	if (IS_ENABLED(CONFIG_ACPI))
4228 		WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
4229 
4230 	return 0;
4231 
4232 err3:
4233 	class_unregister(&spi_master_class);
4234 err2:
4235 	bus_unregister(&spi_bus_type);
4236 err1:
4237 	kfree(buf);
4238 	buf = NULL;
4239 err0:
4240 	return status;
4241 }
4242 
4243 /* board_info is normally registered in arch_initcall(),
4244  * but even essential drivers wait till later
4245  *
4246  * REVISIT only boardinfo really needs static linking. the rest (device and
4247  * driver registration) _could_ be dynamically linked (modular) ... costs
4248  * include needing to have boardinfo data structures be much more public.
4249  */
4250 postcore_initcall(spi_init);
4251