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