1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2018 Exceet Electronics GmbH
4  * Copyright (C) 2018 Bootlin
5  *
6  * Author: Boris Brezillon <boris.brezillon@bootlin.com>
7  */
8 
9 #ifndef __UBOOT__
10 #include <log.h>
11 #include <dm/devres.h>
12 #include <linux/dmaengine.h>
13 #include <linux/pm_runtime.h>
14 #include "internals.h"
15 #else
16 #include <common.h>
17 #include <dm.h>
18 #include <errno.h>
19 #include <malloc.h>
20 #include <spi.h>
21 #include <spi.h>
22 #include <spi-mem.h>
23 #include <dm/device_compat.h>
24 #endif
25 
26 #ifndef __UBOOT__
27 /**
28  * spi_controller_dma_map_mem_op_data() - DMA-map the buffer attached to a
29  *					  memory operation
30  * @ctlr: the SPI controller requesting this dma_map()
31  * @op: the memory operation containing the buffer to map
32  * @sgt: a pointer to a non-initialized sg_table that will be filled by this
33  *	 function
34  *
35  * Some controllers might want to do DMA on the data buffer embedded in @op.
36  * This helper prepares everything for you and provides a ready-to-use
37  * sg_table. This function is not intended to be called from spi drivers.
38  * Only SPI controller drivers should use it.
39  * Note that the caller must ensure the memory region pointed by
40  * op->data.buf.{in,out} is DMA-able before calling this function.
41  *
42  * Return: 0 in case of success, a negative error code otherwise.
43  */
spi_controller_dma_map_mem_op_data(struct spi_controller * ctlr,const struct spi_mem_op * op,struct sg_table * sgt)44 int spi_controller_dma_map_mem_op_data(struct spi_controller *ctlr,
45 				       const struct spi_mem_op *op,
46 				       struct sg_table *sgt)
47 {
48 	struct device *dmadev;
49 
50 	if (!op->data.nbytes)
51 		return -EINVAL;
52 
53 	if (op->data.dir == SPI_MEM_DATA_OUT && ctlr->dma_tx)
54 		dmadev = ctlr->dma_tx->device->dev;
55 	else if (op->data.dir == SPI_MEM_DATA_IN && ctlr->dma_rx)
56 		dmadev = ctlr->dma_rx->device->dev;
57 	else
58 		dmadev = ctlr->dev.parent;
59 
60 	if (!dmadev)
61 		return -EINVAL;
62 
63 	return spi_map_buf(ctlr, dmadev, sgt, op->data.buf.in, op->data.nbytes,
64 			   op->data.dir == SPI_MEM_DATA_IN ?
65 			   DMA_FROM_DEVICE : DMA_TO_DEVICE);
66 }
67 EXPORT_SYMBOL_GPL(spi_controller_dma_map_mem_op_data);
68 
69 /**
70  * spi_controller_dma_unmap_mem_op_data() - DMA-unmap the buffer attached to a
71  *					    memory operation
72  * @ctlr: the SPI controller requesting this dma_unmap()
73  * @op: the memory operation containing the buffer to unmap
74  * @sgt: a pointer to an sg_table previously initialized by
75  *	 spi_controller_dma_map_mem_op_data()
76  *
77  * Some controllers might want to do DMA on the data buffer embedded in @op.
78  * This helper prepares things so that the CPU can access the
79  * op->data.buf.{in,out} buffer again.
80  *
81  * This function is not intended to be called from SPI drivers. Only SPI
82  * controller drivers should use it.
83  *
84  * This function should be called after the DMA operation has finished and is
85  * only valid if the previous spi_controller_dma_map_mem_op_data() call
86  * returned 0.
87  *
88  * Return: 0 in case of success, a negative error code otherwise.
89  */
spi_controller_dma_unmap_mem_op_data(struct spi_controller * ctlr,const struct spi_mem_op * op,struct sg_table * sgt)90 void spi_controller_dma_unmap_mem_op_data(struct spi_controller *ctlr,
91 					  const struct spi_mem_op *op,
92 					  struct sg_table *sgt)
93 {
94 	struct device *dmadev;
95 
96 	if (!op->data.nbytes)
97 		return;
98 
99 	if (op->data.dir == SPI_MEM_DATA_OUT && ctlr->dma_tx)
100 		dmadev = ctlr->dma_tx->device->dev;
101 	else if (op->data.dir == SPI_MEM_DATA_IN && ctlr->dma_rx)
102 		dmadev = ctlr->dma_rx->device->dev;
103 	else
104 		dmadev = ctlr->dev.parent;
105 
106 	spi_unmap_buf(ctlr, dmadev, sgt,
107 		      op->data.dir == SPI_MEM_DATA_IN ?
108 		      DMA_FROM_DEVICE : DMA_TO_DEVICE);
109 }
110 EXPORT_SYMBOL_GPL(spi_controller_dma_unmap_mem_op_data);
111 #endif /* __UBOOT__ */
112 
spi_check_buswidth_req(struct spi_slave * slave,u8 buswidth,bool tx)113 static int spi_check_buswidth_req(struct spi_slave *slave, u8 buswidth, bool tx)
114 {
115 	u32 mode = slave->mode;
116 
117 	switch (buswidth) {
118 	case 1:
119 		return 0;
120 
121 	case 2:
122 		if ((tx && (mode & (SPI_TX_DUAL | SPI_TX_QUAD))) ||
123 		    (!tx && (mode & (SPI_RX_DUAL | SPI_RX_QUAD))))
124 			return 0;
125 
126 		break;
127 
128 	case 4:
129 		if ((tx && (mode & SPI_TX_QUAD)) ||
130 		    (!tx && (mode & SPI_RX_QUAD)))
131 			return 0;
132 
133 		break;
134 	case 8:
135 		if ((tx && (mode & SPI_TX_OCTAL)) ||
136 		    (!tx && (mode & SPI_RX_OCTAL)))
137 			return 0;
138 
139 		break;
140 
141 	default:
142 		break;
143 	}
144 
145 	return -ENOTSUPP;
146 }
147 
spi_mem_default_supports_op(struct spi_slave * slave,const struct spi_mem_op * op)148 bool spi_mem_default_supports_op(struct spi_slave *slave,
149 				 const struct spi_mem_op *op)
150 {
151 	if (spi_check_buswidth_req(slave, op->cmd.buswidth, true))
152 		return false;
153 
154 	if (op->addr.nbytes &&
155 	    spi_check_buswidth_req(slave, op->addr.buswidth, true))
156 		return false;
157 
158 	if (op->dummy.nbytes &&
159 	    spi_check_buswidth_req(slave, op->dummy.buswidth, true))
160 		return false;
161 
162 	if (op->data.dir != SPI_MEM_NO_DATA &&
163 	    spi_check_buswidth_req(slave, op->data.buswidth,
164 				   op->data.dir == SPI_MEM_DATA_OUT))
165 		return false;
166 
167 	return true;
168 }
169 EXPORT_SYMBOL_GPL(spi_mem_default_supports_op);
170 
171 /**
172  * spi_mem_supports_op() - Check if a memory device and the controller it is
173  *			   connected to support a specific memory operation
174  * @slave: the SPI device
175  * @op: the memory operation to check
176  *
177  * Some controllers are only supporting Single or Dual IOs, others might only
178  * support specific opcodes, or it can even be that the controller and device
179  * both support Quad IOs but the hardware prevents you from using it because
180  * only 2 IO lines are connected.
181  *
182  * This function checks whether a specific operation is supported.
183  *
184  * Return: true if @op is supported, false otherwise.
185  */
spi_mem_supports_op(struct spi_slave * slave,const struct spi_mem_op * op)186 bool spi_mem_supports_op(struct spi_slave *slave,
187 			 const struct spi_mem_op *op)
188 {
189 	struct udevice *bus = slave->dev->parent;
190 	struct dm_spi_ops *ops = spi_get_ops(bus);
191 
192 	if (ops->mem_ops && ops->mem_ops->supports_op)
193 		return ops->mem_ops->supports_op(slave, op);
194 
195 	return spi_mem_default_supports_op(slave, op);
196 }
197 EXPORT_SYMBOL_GPL(spi_mem_supports_op);
198 
199 /**
200  * spi_mem_exec_op() - Execute a memory operation
201  * @slave: the SPI device
202  * @op: the memory operation to execute
203  *
204  * Executes a memory operation.
205  *
206  * This function first checks that @op is supported and then tries to execute
207  * it.
208  *
209  * Return: 0 in case of success, a negative error code otherwise.
210  */
spi_mem_exec_op(struct spi_slave * slave,const struct spi_mem_op * op)211 int spi_mem_exec_op(struct spi_slave *slave, const struct spi_mem_op *op)
212 {
213 	struct udevice *bus = slave->dev->parent;
214 	struct dm_spi_ops *ops = spi_get_ops(bus);
215 	unsigned int pos = 0;
216 	const u8 *tx_buf = NULL;
217 	u8 *rx_buf = NULL;
218 	int op_len;
219 	u32 flag;
220 	int ret;
221 	int i;
222 
223 	if (!spi_mem_supports_op(slave, op))
224 		return -ENOTSUPP;
225 
226 	ret = spi_claim_bus(slave);
227 	if (ret < 0)
228 		return ret;
229 
230 	if (ops->mem_ops && ops->mem_ops->exec_op) {
231 #ifndef __UBOOT__
232 		/*
233 		 * Flush the message queue before executing our SPI memory
234 		 * operation to prevent preemption of regular SPI transfers.
235 		 */
236 		spi_flush_queue(ctlr);
237 
238 		if (ctlr->auto_runtime_pm) {
239 			ret = pm_runtime_get_sync(ctlr->dev.parent);
240 			if (ret < 0) {
241 				dev_err(&ctlr->dev,
242 					"Failed to power device: %d\n",
243 					ret);
244 				return ret;
245 			}
246 		}
247 
248 		mutex_lock(&ctlr->bus_lock_mutex);
249 		mutex_lock(&ctlr->io_mutex);
250 #endif
251 		ret = ops->mem_ops->exec_op(slave, op);
252 
253 #ifndef __UBOOT__
254 		mutex_unlock(&ctlr->io_mutex);
255 		mutex_unlock(&ctlr->bus_lock_mutex);
256 
257 		if (ctlr->auto_runtime_pm)
258 			pm_runtime_put(ctlr->dev.parent);
259 #endif
260 
261 		/*
262 		 * Some controllers only optimize specific paths (typically the
263 		 * read path) and expect the core to use the regular SPI
264 		 * interface in other cases.
265 		 */
266 		if (!ret || ret != -ENOTSUPP) {
267 			spi_release_bus(slave);
268 			return ret;
269 		}
270 	}
271 
272 #ifndef __UBOOT__
273 	tmpbufsize = sizeof(op->cmd.opcode) + op->addr.nbytes +
274 		     op->dummy.nbytes;
275 
276 	/*
277 	 * Allocate a buffer to transmit the CMD, ADDR cycles with kmalloc() so
278 	 * we're guaranteed that this buffer is DMA-able, as required by the
279 	 * SPI layer.
280 	 */
281 	tmpbuf = kzalloc(tmpbufsize, GFP_KERNEL | GFP_DMA);
282 	if (!tmpbuf)
283 		return -ENOMEM;
284 
285 	spi_message_init(&msg);
286 
287 	tmpbuf[0] = op->cmd.opcode;
288 	xfers[xferpos].tx_buf = tmpbuf;
289 	xfers[xferpos].len = sizeof(op->cmd.opcode);
290 	xfers[xferpos].tx_nbits = op->cmd.buswidth;
291 	spi_message_add_tail(&xfers[xferpos], &msg);
292 	xferpos++;
293 	totalxferlen++;
294 
295 	if (op->addr.nbytes) {
296 		int i;
297 
298 		for (i = 0; i < op->addr.nbytes; i++)
299 			tmpbuf[i + 1] = op->addr.val >>
300 					(8 * (op->addr.nbytes - i - 1));
301 
302 		xfers[xferpos].tx_buf = tmpbuf + 1;
303 		xfers[xferpos].len = op->addr.nbytes;
304 		xfers[xferpos].tx_nbits = op->addr.buswidth;
305 		spi_message_add_tail(&xfers[xferpos], &msg);
306 		xferpos++;
307 		totalxferlen += op->addr.nbytes;
308 	}
309 
310 	if (op->dummy.nbytes) {
311 		memset(tmpbuf + op->addr.nbytes + 1, 0xff, op->dummy.nbytes);
312 		xfers[xferpos].tx_buf = tmpbuf + op->addr.nbytes + 1;
313 		xfers[xferpos].len = op->dummy.nbytes;
314 		xfers[xferpos].tx_nbits = op->dummy.buswidth;
315 		spi_message_add_tail(&xfers[xferpos], &msg);
316 		xferpos++;
317 		totalxferlen += op->dummy.nbytes;
318 	}
319 
320 	if (op->data.nbytes) {
321 		if (op->data.dir == SPI_MEM_DATA_IN) {
322 			xfers[xferpos].rx_buf = op->data.buf.in;
323 			xfers[xferpos].rx_nbits = op->data.buswidth;
324 		} else {
325 			xfers[xferpos].tx_buf = op->data.buf.out;
326 			xfers[xferpos].tx_nbits = op->data.buswidth;
327 		}
328 
329 		xfers[xferpos].len = op->data.nbytes;
330 		spi_message_add_tail(&xfers[xferpos], &msg);
331 		xferpos++;
332 		totalxferlen += op->data.nbytes;
333 	}
334 
335 	ret = spi_sync(slave, &msg);
336 
337 	kfree(tmpbuf);
338 
339 	if (ret)
340 		return ret;
341 
342 	if (msg.actual_length != totalxferlen)
343 		return -EIO;
344 #else
345 
346 	if (op->data.nbytes) {
347 		if (op->data.dir == SPI_MEM_DATA_IN)
348 			rx_buf = op->data.buf.in;
349 		else
350 			tx_buf = op->data.buf.out;
351 	}
352 
353 	op_len = sizeof(op->cmd.opcode) + op->addr.nbytes + op->dummy.nbytes;
354 
355 	/*
356 	 * Avoid using malloc() here so that we can use this code in SPL where
357 	 * simple malloc may be used. That implementation does not allow free()
358 	 * so repeated calls to this code can exhaust the space.
359 	 *
360 	 * The value of op_len is small, since it does not include the actual
361 	 * data being sent, only the op-code and address. In fact, it should be
362 	 * possible to just use a small fixed value here instead of op_len.
363 	 */
364 	u8 op_buf[op_len];
365 
366 	op_buf[pos++] = op->cmd.opcode;
367 
368 	if (op->addr.nbytes) {
369 		for (i = 0; i < op->addr.nbytes; i++)
370 			op_buf[pos + i] = op->addr.val >>
371 				(8 * (op->addr.nbytes - i - 1));
372 
373 		pos += op->addr.nbytes;
374 	}
375 
376 	if (op->dummy.nbytes)
377 		memset(op_buf + pos, 0xff, op->dummy.nbytes);
378 
379 	/* 1st transfer: opcode + address + dummy cycles */
380 	flag = SPI_XFER_BEGIN;
381 	/* Make sure to set END bit if no tx or rx data messages follow */
382 	if (!tx_buf && !rx_buf)
383 		flag |= SPI_XFER_END;
384 
385 	ret = spi_xfer(slave, op_len * 8, op_buf, NULL, flag);
386 	if (ret)
387 		return ret;
388 
389 	/* 2nd transfer: rx or tx data path */
390 	if (tx_buf || rx_buf) {
391 		ret = spi_xfer(slave, op->data.nbytes * 8, tx_buf,
392 			       rx_buf, SPI_XFER_END);
393 		if (ret)
394 			return ret;
395 	}
396 
397 	spi_release_bus(slave);
398 
399 	for (i = 0; i < pos; i++)
400 		debug("%02x ", op_buf[i]);
401 	debug("| [%dB %s] ",
402 	      tx_buf || rx_buf ? op->data.nbytes : 0,
403 	      tx_buf || rx_buf ? (tx_buf ? "out" : "in") : "-");
404 	for (i = 0; i < op->data.nbytes; i++)
405 		debug("%02x ", tx_buf ? tx_buf[i] : rx_buf[i]);
406 	debug("[ret %d]\n", ret);
407 
408 	if (ret < 0)
409 		return ret;
410 #endif /* __UBOOT__ */
411 
412 	return 0;
413 }
414 EXPORT_SYMBOL_GPL(spi_mem_exec_op);
415 
416 /**
417  * spi_mem_adjust_op_size() - Adjust the data size of a SPI mem operation to
418  *				 match controller limitations
419  * @slave: the SPI device
420  * @op: the operation to adjust
421  *
422  * Some controllers have FIFO limitations and must split a data transfer
423  * operation into multiple ones, others require a specific alignment for
424  * optimized accesses. This function allows SPI mem drivers to split a single
425  * operation into multiple sub-operations when required.
426  *
427  * Return: a negative error code if the controller can't properly adjust @op,
428  *	   0 otherwise. Note that @op->data.nbytes will be updated if @op
429  *	   can't be handled in a single step.
430  */
spi_mem_adjust_op_size(struct spi_slave * slave,struct spi_mem_op * op)431 int spi_mem_adjust_op_size(struct spi_slave *slave, struct spi_mem_op *op)
432 {
433 	struct udevice *bus = slave->dev->parent;
434 	struct dm_spi_ops *ops = spi_get_ops(bus);
435 
436 	if (ops->mem_ops && ops->mem_ops->adjust_op_size)
437 		return ops->mem_ops->adjust_op_size(slave, op);
438 
439 	if (!ops->mem_ops || !ops->mem_ops->exec_op) {
440 		unsigned int len;
441 
442 		len = sizeof(op->cmd.opcode) + op->addr.nbytes +
443 			op->dummy.nbytes;
444 		if (slave->max_write_size && len > slave->max_write_size)
445 			return -EINVAL;
446 
447 		if (op->data.dir == SPI_MEM_DATA_IN) {
448 			if (slave->max_read_size)
449 				op->data.nbytes = min(op->data.nbytes,
450 					      slave->max_read_size);
451 		} else if (slave->max_write_size) {
452 			op->data.nbytes = min(op->data.nbytes,
453 					      slave->max_write_size - len);
454 		}
455 
456 		if (!op->data.nbytes)
457 			return -EINVAL;
458 	}
459 
460 	return 0;
461 }
462 EXPORT_SYMBOL_GPL(spi_mem_adjust_op_size);
463 
464 #ifndef __UBOOT__
to_spi_mem_drv(struct device_driver * drv)465 static inline struct spi_mem_driver *to_spi_mem_drv(struct device_driver *drv)
466 {
467 	return container_of(drv, struct spi_mem_driver, spidrv.driver);
468 }
469 
spi_mem_probe(struct spi_device * spi)470 static int spi_mem_probe(struct spi_device *spi)
471 {
472 	struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
473 	struct spi_mem *mem;
474 
475 	mem = devm_kzalloc(&spi->dev, sizeof(*mem), GFP_KERNEL);
476 	if (!mem)
477 		return -ENOMEM;
478 
479 	mem->spi = spi;
480 	spi_set_drvdata(spi, mem);
481 
482 	return memdrv->probe(mem);
483 }
484 
spi_mem_remove(struct spi_device * spi)485 static int spi_mem_remove(struct spi_device *spi)
486 {
487 	struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
488 	struct spi_mem *mem = spi_get_drvdata(spi);
489 
490 	if (memdrv->remove)
491 		return memdrv->remove(mem);
492 
493 	return 0;
494 }
495 
spi_mem_shutdown(struct spi_device * spi)496 static void spi_mem_shutdown(struct spi_device *spi)
497 {
498 	struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
499 	struct spi_mem *mem = spi_get_drvdata(spi);
500 
501 	if (memdrv->shutdown)
502 		memdrv->shutdown(mem);
503 }
504 
505 /**
506  * spi_mem_driver_register_with_owner() - Register a SPI memory driver
507  * @memdrv: the SPI memory driver to register
508  * @owner: the owner of this driver
509  *
510  * Registers a SPI memory driver.
511  *
512  * Return: 0 in case of success, a negative error core otherwise.
513  */
514 
spi_mem_driver_register_with_owner(struct spi_mem_driver * memdrv,struct module * owner)515 int spi_mem_driver_register_with_owner(struct spi_mem_driver *memdrv,
516 				       struct module *owner)
517 {
518 	memdrv->spidrv.probe = spi_mem_probe;
519 	memdrv->spidrv.remove = spi_mem_remove;
520 	memdrv->spidrv.shutdown = spi_mem_shutdown;
521 
522 	return __spi_register_driver(owner, &memdrv->spidrv);
523 }
524 EXPORT_SYMBOL_GPL(spi_mem_driver_register_with_owner);
525 
526 /**
527  * spi_mem_driver_unregister_with_owner() - Unregister a SPI memory driver
528  * @memdrv: the SPI memory driver to unregister
529  *
530  * Unregisters a SPI memory driver.
531  */
spi_mem_driver_unregister(struct spi_mem_driver * memdrv)532 void spi_mem_driver_unregister(struct spi_mem_driver *memdrv)
533 {
534 	spi_unregister_driver(&memdrv->spidrv);
535 }
536 EXPORT_SYMBOL_GPL(spi_mem_driver_unregister);
537 #endif /* __UBOOT__ */
538