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