xref: /linux/drivers/spi/spi-mem.c (revision 95d3481af6dc90fd7175a7643fd108cdcb808ce5)
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 #include <linux/dmaengine.h>
9 #include <linux/iopoll.h>
10 #include <linux/pm_runtime.h>
11 #include <linux/spi/spi.h>
12 #include <linux/spi/spi-mem.h>
13 #include <linux/sched/task_stack.h>
14 
15 #include "internals.h"
16 
17 #define SPI_MEM_MAX_BUSWIDTH		8
18 
19 /**
20  * spi_controller_dma_map_mem_op_data() - DMA-map the buffer attached to a
21  *					  memory operation
22  * @ctlr: the SPI controller requesting this dma_map()
23  * @op: the memory operation containing the buffer to map
24  * @sgt: a pointer to a non-initialized sg_table that will be filled by this
25  *	 function
26  *
27  * Some controllers might want to do DMA on the data buffer embedded in @op.
28  * This helper prepares everything for you and provides a ready-to-use
29  * sg_table. This function is not intended to be called from spi drivers.
30  * Only SPI controller drivers should use it.
31  * Note that the caller must ensure the memory region pointed by
32  * op->data.buf.{in,out} is DMA-able before calling this function.
33  *
34  * Return: 0 in case of success, a negative error code otherwise.
35  */
spi_controller_dma_map_mem_op_data(struct spi_controller * ctlr,const struct spi_mem_op * op,struct sg_table * sgt)36 int spi_controller_dma_map_mem_op_data(struct spi_controller *ctlr,
37 				       const struct spi_mem_op *op,
38 				       struct sg_table *sgt)
39 {
40 	struct device *dmadev;
41 
42 	if (!op->data.nbytes)
43 		return -EINVAL;
44 
45 	if (op->data.dir == SPI_MEM_DATA_OUT && ctlr->dma_tx)
46 		dmadev = ctlr->dma_tx->device->dev;
47 	else if (op->data.dir == SPI_MEM_DATA_IN && ctlr->dma_rx)
48 		dmadev = ctlr->dma_rx->device->dev;
49 	else
50 		dmadev = ctlr->dev.parent;
51 
52 	if (!dmadev)
53 		return -EINVAL;
54 
55 	return spi_map_buf(ctlr, dmadev, sgt, op->data.buf.in, op->data.nbytes,
56 			   op->data.dir == SPI_MEM_DATA_IN ?
57 			   DMA_FROM_DEVICE : DMA_TO_DEVICE);
58 }
59 EXPORT_SYMBOL_GPL(spi_controller_dma_map_mem_op_data);
60 
61 /**
62  * spi_controller_dma_unmap_mem_op_data() - DMA-unmap the buffer attached to a
63  *					    memory operation
64  * @ctlr: the SPI controller requesting this dma_unmap()
65  * @op: the memory operation containing the buffer to unmap
66  * @sgt: a pointer to an sg_table previously initialized by
67  *	 spi_controller_dma_map_mem_op_data()
68  *
69  * Some controllers might want to do DMA on the data buffer embedded in @op.
70  * This helper prepares things so that the CPU can access the
71  * op->data.buf.{in,out} buffer again.
72  *
73  * This function is not intended to be called from SPI drivers. Only SPI
74  * controller drivers should use it.
75  *
76  * This function should be called after the DMA operation has finished and is
77  * only valid if the previous spi_controller_dma_map_mem_op_data() call
78  * returned 0.
79  *
80  * Return: 0 in case of success, a negative error code otherwise.
81  */
spi_controller_dma_unmap_mem_op_data(struct spi_controller * ctlr,const struct spi_mem_op * op,struct sg_table * sgt)82 void spi_controller_dma_unmap_mem_op_data(struct spi_controller *ctlr,
83 					  const struct spi_mem_op *op,
84 					  struct sg_table *sgt)
85 {
86 	struct device *dmadev;
87 
88 	if (!op->data.nbytes)
89 		return;
90 
91 	if (op->data.dir == SPI_MEM_DATA_OUT && ctlr->dma_tx)
92 		dmadev = ctlr->dma_tx->device->dev;
93 	else if (op->data.dir == SPI_MEM_DATA_IN && ctlr->dma_rx)
94 		dmadev = ctlr->dma_rx->device->dev;
95 	else
96 		dmadev = ctlr->dev.parent;
97 
98 	spi_unmap_buf(ctlr, dmadev, sgt,
99 		      op->data.dir == SPI_MEM_DATA_IN ?
100 		      DMA_FROM_DEVICE : DMA_TO_DEVICE);
101 }
102 EXPORT_SYMBOL_GPL(spi_controller_dma_unmap_mem_op_data);
103 
spi_check_buswidth_req(struct spi_mem * mem,u8 buswidth,bool tx)104 static int spi_check_buswidth_req(struct spi_mem *mem, u8 buswidth, bool tx)
105 {
106 	u32 mode = mem->spi->mode;
107 
108 	switch (buswidth) {
109 	case 1:
110 		return 0;
111 
112 	case 2:
113 		if ((tx &&
114 		     (mode & (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL))) ||
115 		    (!tx &&
116 		     (mode & (SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL))))
117 			return 0;
118 
119 		break;
120 
121 	case 4:
122 		if ((tx && (mode & (SPI_TX_QUAD | SPI_TX_OCTAL))) ||
123 		    (!tx && (mode & (SPI_RX_QUAD | SPI_RX_OCTAL))))
124 			return 0;
125 
126 		break;
127 
128 	case 8:
129 		if ((tx && (mode & SPI_TX_OCTAL)) ||
130 		    (!tx && (mode & SPI_RX_OCTAL)))
131 			return 0;
132 
133 		break;
134 
135 	default:
136 		break;
137 	}
138 
139 	return -ENOTSUPP;
140 }
141 
spi_mem_check_buswidth(struct spi_mem * mem,const struct spi_mem_op * op)142 static bool spi_mem_check_buswidth(struct spi_mem *mem,
143 				   const struct spi_mem_op *op)
144 {
145 	if (spi_check_buswidth_req(mem, op->cmd.buswidth, true))
146 		return false;
147 
148 	if (op->addr.nbytes &&
149 	    spi_check_buswidth_req(mem, op->addr.buswidth, true))
150 		return false;
151 
152 	if (op->dummy.nbytes &&
153 	    spi_check_buswidth_req(mem, op->dummy.buswidth, true))
154 		return false;
155 
156 	if (op->data.dir != SPI_MEM_NO_DATA &&
157 	    spi_check_buswidth_req(mem, op->data.buswidth,
158 				   op->data.dir == SPI_MEM_DATA_OUT))
159 		return false;
160 
161 	return true;
162 }
163 
spi_mem_default_supports_op(struct spi_mem * mem,const struct spi_mem_op * op)164 bool spi_mem_default_supports_op(struct spi_mem *mem,
165 				 const struct spi_mem_op *op)
166 {
167 	struct spi_controller *ctlr = mem->spi->controller;
168 	bool op_is_dtr =
169 		op->cmd.dtr || op->addr.dtr || op->dummy.dtr || op->data.dtr;
170 
171 	if (op_is_dtr) {
172 		if (!spi_mem_controller_is_capable(ctlr, dtr))
173 			return false;
174 
175 		if (op->data.swap16 && !spi_mem_controller_is_capable(ctlr, swap16))
176 			return false;
177 
178 		if (op->cmd.nbytes != 2)
179 			return false;
180 	} else {
181 		if (op->cmd.nbytes != 1)
182 			return false;
183 	}
184 
185 	if (op->data.ecc) {
186 		if (!spi_mem_controller_is_capable(ctlr, ecc))
187 			return false;
188 	}
189 
190 	if (op->max_freq && mem->spi->controller->min_speed_hz &&
191 	    op->max_freq < mem->spi->controller->min_speed_hz)
192 		return false;
193 
194 	if (op->max_freq &&
195 	    op->max_freq < mem->spi->max_speed_hz) {
196 		if (!spi_mem_controller_is_capable(ctlr, per_op_freq))
197 			return false;
198 	}
199 
200 	return spi_mem_check_buswidth(mem, op);
201 }
202 EXPORT_SYMBOL_GPL(spi_mem_default_supports_op);
203 
spi_mem_buswidth_is_valid(u8 buswidth)204 static bool spi_mem_buswidth_is_valid(u8 buswidth)
205 {
206 	if (hweight8(buswidth) > 1 || buswidth > SPI_MEM_MAX_BUSWIDTH)
207 		return false;
208 
209 	return true;
210 }
211 
spi_mem_check_op(const struct spi_mem_op * op)212 static int spi_mem_check_op(const struct spi_mem_op *op)
213 {
214 	if (!op->cmd.buswidth || !op->cmd.nbytes)
215 		return -EINVAL;
216 
217 	if ((op->addr.nbytes && !op->addr.buswidth) ||
218 	    (op->dummy.nbytes && !op->dummy.buswidth) ||
219 	    (op->data.nbytes && !op->data.buswidth))
220 		return -EINVAL;
221 
222 	if (!spi_mem_buswidth_is_valid(op->cmd.buswidth) ||
223 	    !spi_mem_buswidth_is_valid(op->addr.buswidth) ||
224 	    !spi_mem_buswidth_is_valid(op->dummy.buswidth) ||
225 	    !spi_mem_buswidth_is_valid(op->data.buswidth))
226 		return -EINVAL;
227 
228 	/* Buffers must be DMA-able. */
229 	if (WARN_ON_ONCE(op->data.dir == SPI_MEM_DATA_IN &&
230 			 object_is_on_stack(op->data.buf.in)))
231 		return -EINVAL;
232 
233 	if (WARN_ON_ONCE(op->data.dir == SPI_MEM_DATA_OUT &&
234 			 object_is_on_stack(op->data.buf.out)))
235 		return -EINVAL;
236 
237 	return 0;
238 }
239 
spi_mem_internal_supports_op(struct spi_mem * mem,const struct spi_mem_op * op)240 static bool spi_mem_internal_supports_op(struct spi_mem *mem,
241 					 const struct spi_mem_op *op)
242 {
243 	struct spi_controller *ctlr = mem->spi->controller;
244 
245 	if (ctlr->mem_ops && ctlr->mem_ops->supports_op)
246 		return ctlr->mem_ops->supports_op(mem, op);
247 
248 	return spi_mem_default_supports_op(mem, op);
249 }
250 
251 /**
252  * spi_mem_supports_op() - Check if a memory device and the controller it is
253  *			   connected to support a specific memory operation
254  * @mem: the SPI memory
255  * @op: the memory operation to check
256  *
257  * Some controllers are only supporting Single or Dual IOs, others might only
258  * support specific opcodes, or it can even be that the controller and device
259  * both support Quad IOs but the hardware prevents you from using it because
260  * only 2 IO lines are connected.
261  *
262  * This function checks whether a specific operation is supported.
263  *
264  * Return: true if @op is supported, false otherwise.
265  */
spi_mem_supports_op(struct spi_mem * mem,const struct spi_mem_op * op)266 bool spi_mem_supports_op(struct spi_mem *mem, const struct spi_mem_op *op)
267 {
268 	if (spi_mem_check_op(op))
269 		return false;
270 
271 	return spi_mem_internal_supports_op(mem, op);
272 }
273 EXPORT_SYMBOL_GPL(spi_mem_supports_op);
274 
spi_mem_access_start(struct spi_mem * mem)275 static int spi_mem_access_start(struct spi_mem *mem)
276 {
277 	struct spi_controller *ctlr = mem->spi->controller;
278 
279 	/*
280 	 * Flush the message queue before executing our SPI memory
281 	 * operation to prevent preemption of regular SPI transfers.
282 	 */
283 	spi_flush_queue(ctlr);
284 
285 	if (ctlr->auto_runtime_pm) {
286 		int ret;
287 
288 		ret = pm_runtime_resume_and_get(ctlr->dev.parent);
289 		if (ret < 0) {
290 			dev_err(&ctlr->dev, "Failed to power device: %d\n",
291 				ret);
292 			return ret;
293 		}
294 	}
295 
296 	mutex_lock(&ctlr->bus_lock_mutex);
297 	mutex_lock(&ctlr->io_mutex);
298 
299 	return 0;
300 }
301 
spi_mem_access_end(struct spi_mem * mem)302 static void spi_mem_access_end(struct spi_mem *mem)
303 {
304 	struct spi_controller *ctlr = mem->spi->controller;
305 
306 	mutex_unlock(&ctlr->io_mutex);
307 	mutex_unlock(&ctlr->bus_lock_mutex);
308 
309 	if (ctlr->auto_runtime_pm)
310 		pm_runtime_put(ctlr->dev.parent);
311 }
312 
spi_mem_add_op_stats(struct spi_statistics __percpu * pcpu_stats,const struct spi_mem_op * op,int exec_op_ret)313 static void spi_mem_add_op_stats(struct spi_statistics __percpu *pcpu_stats,
314 				 const struct spi_mem_op *op, int exec_op_ret)
315 {
316 	struct spi_statistics *stats;
317 	u64 len, l2len;
318 
319 	get_cpu();
320 	stats = this_cpu_ptr(pcpu_stats);
321 	u64_stats_update_begin(&stats->syncp);
322 
323 	/*
324 	 * We do not have the concept of messages or transfers. Let's consider
325 	 * that one operation is equivalent to one message and one transfer.
326 	 */
327 	u64_stats_inc(&stats->messages);
328 	u64_stats_inc(&stats->transfers);
329 
330 	/* Use the sum of all lengths as bytes count and histogram value. */
331 	len = op->cmd.nbytes + op->addr.nbytes;
332 	len += op->dummy.nbytes + op->data.nbytes;
333 	u64_stats_add(&stats->bytes, len);
334 	l2len = min(fls(len), SPI_STATISTICS_HISTO_SIZE) - 1;
335 	u64_stats_inc(&stats->transfer_bytes_histo[l2len]);
336 
337 	/* Only account for data bytes as transferred bytes. */
338 	if (op->data.nbytes && op->data.dir == SPI_MEM_DATA_OUT)
339 		u64_stats_add(&stats->bytes_tx, op->data.nbytes);
340 	if (op->data.nbytes && op->data.dir == SPI_MEM_DATA_IN)
341 		u64_stats_add(&stats->bytes_rx, op->data.nbytes);
342 
343 	/*
344 	 * A timeout is not an error, following the same behavior as
345 	 * spi_transfer_one_message().
346 	 */
347 	if (exec_op_ret == -ETIMEDOUT)
348 		u64_stats_inc(&stats->timedout);
349 	else if (exec_op_ret)
350 		u64_stats_inc(&stats->errors);
351 
352 	u64_stats_update_end(&stats->syncp);
353 	put_cpu();
354 }
355 
356 /**
357  * spi_mem_exec_op() - Execute a memory operation
358  * @mem: the SPI memory
359  * @op: the memory operation to execute
360  *
361  * Executes a memory operation.
362  *
363  * This function first checks that @op is supported and then tries to execute
364  * it.
365  *
366  * Return: 0 in case of success, a negative error code otherwise.
367  */
spi_mem_exec_op(struct spi_mem * mem,const struct spi_mem_op * op)368 int spi_mem_exec_op(struct spi_mem *mem, const struct spi_mem_op *op)
369 {
370 	unsigned int tmpbufsize, xferpos = 0, totalxferlen = 0;
371 	struct spi_controller *ctlr = mem->spi->controller;
372 	struct spi_transfer xfers[4] = { };
373 	struct spi_message msg;
374 	u8 *tmpbuf;
375 	int ret;
376 
377 	/* Make sure the operation frequency is correct before going futher */
378 	spi_mem_adjust_op_freq(mem, (struct spi_mem_op *)op);
379 
380 	dev_vdbg(&mem->spi->dev, "[cmd: 0x%02x][%dB addr: %#8llx][%2dB dummy][%4dB data %s] %d%c-%d%c-%d%c-%d%c @ %uHz\n",
381 		 op->cmd.opcode,
382 		 op->addr.nbytes, (op->addr.nbytes ? op->addr.val : 0),
383 		 op->dummy.nbytes,
384 		 op->data.nbytes, (op->data.nbytes ? (op->data.dir == SPI_MEM_DATA_IN ? " read" : "write") : "     "),
385 		 op->cmd.buswidth, op->cmd.dtr ? 'D' : 'S',
386 		 op->addr.buswidth, op->addr.dtr ? 'D' : 'S',
387 		 op->dummy.buswidth, op->dummy.dtr ? 'D' : 'S',
388 		 op->data.buswidth, op->data.dtr ? 'D' : 'S',
389 		 op->max_freq ? op->max_freq : mem->spi->max_speed_hz);
390 
391 	ret = spi_mem_check_op(op);
392 	if (ret)
393 		return ret;
394 
395 	if (!spi_mem_internal_supports_op(mem, op))
396 		return -EOPNOTSUPP;
397 
398 	if (ctlr->mem_ops && ctlr->mem_ops->exec_op && !spi_get_csgpiod(mem->spi, 0)) {
399 		ret = spi_mem_access_start(mem);
400 		if (ret)
401 			return ret;
402 
403 		ret = ctlr->mem_ops->exec_op(mem, op);
404 
405 		spi_mem_access_end(mem);
406 
407 		/*
408 		 * Some controllers only optimize specific paths (typically the
409 		 * read path) and expect the core to use the regular SPI
410 		 * interface in other cases.
411 		 */
412 		if (!ret || (ret != -ENOTSUPP && ret != -EOPNOTSUPP)) {
413 			spi_mem_add_op_stats(ctlr->pcpu_statistics, op, ret);
414 			spi_mem_add_op_stats(mem->spi->pcpu_statistics, op, ret);
415 
416 			return ret;
417 		}
418 	}
419 
420 	tmpbufsize = op->cmd.nbytes + op->addr.nbytes + op->dummy.nbytes;
421 
422 	/*
423 	 * Allocate a buffer to transmit the CMD, ADDR cycles with kmalloc() so
424 	 * we're guaranteed that this buffer is DMA-able, as required by the
425 	 * SPI layer.
426 	 */
427 	tmpbuf = kzalloc(tmpbufsize, GFP_KERNEL | GFP_DMA);
428 	if (!tmpbuf)
429 		return -ENOMEM;
430 
431 	spi_message_init(&msg);
432 
433 	tmpbuf[0] = op->cmd.opcode;
434 	xfers[xferpos].tx_buf = tmpbuf;
435 	xfers[xferpos].len = op->cmd.nbytes;
436 	xfers[xferpos].tx_nbits = op->cmd.buswidth;
437 	xfers[xferpos].speed_hz = op->max_freq;
438 	spi_message_add_tail(&xfers[xferpos], &msg);
439 	xferpos++;
440 	totalxferlen++;
441 
442 	if (op->addr.nbytes) {
443 		int i;
444 
445 		for (i = 0; i < op->addr.nbytes; i++)
446 			tmpbuf[i + 1] = op->addr.val >>
447 					(8 * (op->addr.nbytes - i - 1));
448 
449 		xfers[xferpos].tx_buf = tmpbuf + 1;
450 		xfers[xferpos].len = op->addr.nbytes;
451 		xfers[xferpos].tx_nbits = op->addr.buswidth;
452 		xfers[xferpos].speed_hz = op->max_freq;
453 		spi_message_add_tail(&xfers[xferpos], &msg);
454 		xferpos++;
455 		totalxferlen += op->addr.nbytes;
456 	}
457 
458 	if (op->dummy.nbytes) {
459 		memset(tmpbuf + op->addr.nbytes + 1, 0xff, op->dummy.nbytes);
460 		xfers[xferpos].tx_buf = tmpbuf + op->addr.nbytes + 1;
461 		xfers[xferpos].len = op->dummy.nbytes;
462 		xfers[xferpos].tx_nbits = op->dummy.buswidth;
463 		xfers[xferpos].dummy_data = 1;
464 		xfers[xferpos].speed_hz = op->max_freq;
465 		spi_message_add_tail(&xfers[xferpos], &msg);
466 		xferpos++;
467 		totalxferlen += op->dummy.nbytes;
468 	}
469 
470 	if (op->data.nbytes) {
471 		if (op->data.dir == SPI_MEM_DATA_IN) {
472 			xfers[xferpos].rx_buf = op->data.buf.in;
473 			xfers[xferpos].rx_nbits = op->data.buswidth;
474 		} else {
475 			xfers[xferpos].tx_buf = op->data.buf.out;
476 			xfers[xferpos].tx_nbits = op->data.buswidth;
477 		}
478 
479 		xfers[xferpos].len = op->data.nbytes;
480 		xfers[xferpos].speed_hz = op->max_freq;
481 		spi_message_add_tail(&xfers[xferpos], &msg);
482 		xferpos++;
483 		totalxferlen += op->data.nbytes;
484 	}
485 
486 	ret = spi_sync(mem->spi, &msg);
487 
488 	kfree(tmpbuf);
489 
490 	if (ret)
491 		return ret;
492 
493 	if (msg.actual_length != totalxferlen)
494 		return -EIO;
495 
496 	return 0;
497 }
498 EXPORT_SYMBOL_GPL(spi_mem_exec_op);
499 
500 /**
501  * spi_mem_get_name() - Return the SPI mem device name to be used by the
502  *			upper layer if necessary
503  * @mem: the SPI memory
504  *
505  * This function allows SPI mem users to retrieve the SPI mem device name.
506  * It is useful if the upper layer needs to expose a custom name for
507  * compatibility reasons.
508  *
509  * Return: a string containing the name of the memory device to be used
510  *	   by the SPI mem user
511  */
spi_mem_get_name(struct spi_mem * mem)512 const char *spi_mem_get_name(struct spi_mem *mem)
513 {
514 	return mem->name;
515 }
516 EXPORT_SYMBOL_GPL(spi_mem_get_name);
517 
518 /**
519  * spi_mem_adjust_op_size() - Adjust the data size of a SPI mem operation to
520  *			      match controller limitations
521  * @mem: the SPI memory
522  * @op: the operation to adjust
523  *
524  * Some controllers have FIFO limitations and must split a data transfer
525  * operation into multiple ones, others require a specific alignment for
526  * optimized accesses. This function allows SPI mem drivers to split a single
527  * operation into multiple sub-operations when required.
528  *
529  * Return: a negative error code if the controller can't properly adjust @op,
530  *	   0 otherwise. Note that @op->data.nbytes will be updated if @op
531  *	   can't be handled in a single step.
532  */
spi_mem_adjust_op_size(struct spi_mem * mem,struct spi_mem_op * op)533 int spi_mem_adjust_op_size(struct spi_mem *mem, struct spi_mem_op *op)
534 {
535 	struct spi_controller *ctlr = mem->spi->controller;
536 	size_t len;
537 
538 	if (ctlr->mem_ops && ctlr->mem_ops->adjust_op_size)
539 		return ctlr->mem_ops->adjust_op_size(mem, op);
540 
541 	if (!ctlr->mem_ops || !ctlr->mem_ops->exec_op) {
542 		len = op->cmd.nbytes + op->addr.nbytes + op->dummy.nbytes;
543 
544 		if (len > spi_max_transfer_size(mem->spi))
545 			return -EINVAL;
546 
547 		op->data.nbytes = min3((size_t)op->data.nbytes,
548 				       spi_max_transfer_size(mem->spi),
549 				       spi_max_message_size(mem->spi) -
550 				       len);
551 		if (!op->data.nbytes)
552 			return -EINVAL;
553 	}
554 
555 	return 0;
556 }
557 EXPORT_SYMBOL_GPL(spi_mem_adjust_op_size);
558 
559 /**
560  * spi_mem_adjust_op_freq() - Adjust the frequency of a SPI mem operation to
561  *			      match controller, PCB and chip limitations
562  * @mem: the SPI memory
563  * @op: the operation to adjust
564  *
565  * Some chips have per-op frequency limitations and must adapt the maximum
566  * speed. This function allows SPI mem drivers to set @op->max_freq to the
567  * maximum supported value.
568  */
spi_mem_adjust_op_freq(struct spi_mem * mem,struct spi_mem_op * op)569 void spi_mem_adjust_op_freq(struct spi_mem *mem, struct spi_mem_op *op)
570 {
571 	if (!op->max_freq || op->max_freq > mem->spi->max_speed_hz)
572 		op->max_freq = mem->spi->max_speed_hz;
573 }
574 EXPORT_SYMBOL_GPL(spi_mem_adjust_op_freq);
575 
576 /**
577  * spi_mem_calc_op_duration() - Derives the theoretical length (in ns) of an
578  *			        operation. This helps finding the best variant
579  *			        among a list of possible choices.
580  * @op: the operation to benchmark
581  *
582  * Some chips have per-op frequency limitations, PCBs usually have their own
583  * limitations as well, and controllers can support dual, quad or even octal
584  * modes, sometimes in DTR. All these combinations make it impossible to
585  * statically list the best combination for all situations. If we want something
586  * accurate, all these combinations should be rated (eg. with a time estimate)
587  * and the best pick should be taken based on these calculations.
588  *
589  * Returns a ns estimate for the time this op would take.
590  */
spi_mem_calc_op_duration(struct spi_mem_op * op)591 u64 spi_mem_calc_op_duration(struct spi_mem_op *op)
592 {
593 	u64 ncycles = 0;
594 	u32 ns_per_cycles;
595 
596 	ns_per_cycles = 1000000000 / op->max_freq;
597 	ncycles += ((op->cmd.nbytes * 8) / op->cmd.buswidth) / (op->cmd.dtr ? 2 : 1);
598 	ncycles += ((op->addr.nbytes * 8) / op->addr.buswidth) / (op->addr.dtr ? 2 : 1);
599 
600 	/* Dummy bytes are optional for some SPI flash memory operations */
601 	if (op->dummy.nbytes)
602 		ncycles += ((op->dummy.nbytes * 8) / op->dummy.buswidth) / (op->dummy.dtr ? 2 : 1);
603 
604 	ncycles += ((op->data.nbytes * 8) / op->data.buswidth) / (op->data.dtr ? 2 : 1);
605 
606 	return ncycles * ns_per_cycles;
607 }
608 EXPORT_SYMBOL_GPL(spi_mem_calc_op_duration);
609 
spi_mem_no_dirmap_read(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,void * buf)610 static ssize_t spi_mem_no_dirmap_read(struct spi_mem_dirmap_desc *desc,
611 				      u64 offs, size_t len, void *buf)
612 {
613 	struct spi_mem_op op = desc->info.op_tmpl;
614 	int ret;
615 
616 	op.addr.val = desc->info.offset + offs;
617 	op.data.buf.in = buf;
618 	op.data.nbytes = len;
619 	ret = spi_mem_adjust_op_size(desc->mem, &op);
620 	if (ret)
621 		return ret;
622 
623 	ret = spi_mem_exec_op(desc->mem, &op);
624 	if (ret)
625 		return ret;
626 
627 	return op.data.nbytes;
628 }
629 
spi_mem_no_dirmap_write(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,const void * buf)630 static ssize_t spi_mem_no_dirmap_write(struct spi_mem_dirmap_desc *desc,
631 				       u64 offs, size_t len, const void *buf)
632 {
633 	struct spi_mem_op op = desc->info.op_tmpl;
634 	int ret;
635 
636 	op.addr.val = desc->info.offset + offs;
637 	op.data.buf.out = buf;
638 	op.data.nbytes = len;
639 	ret = spi_mem_adjust_op_size(desc->mem, &op);
640 	if (ret)
641 		return ret;
642 
643 	ret = spi_mem_exec_op(desc->mem, &op);
644 	if (ret)
645 		return ret;
646 
647 	return op.data.nbytes;
648 }
649 
650 /**
651  * spi_mem_dirmap_create() - Create a direct mapping descriptor
652  * @mem: SPI mem device this direct mapping should be created for
653  * @info: direct mapping information
654  *
655  * This function is creating a direct mapping descriptor which can then be used
656  * to access the memory using spi_mem_dirmap_read() or spi_mem_dirmap_write().
657  * If the SPI controller driver does not support direct mapping, this function
658  * falls back to an implementation using spi_mem_exec_op(), so that the caller
659  * doesn't have to bother implementing a fallback on his own.
660  *
661  * Return: a valid pointer in case of success, and ERR_PTR() otherwise.
662  */
663 struct spi_mem_dirmap_desc *
spi_mem_dirmap_create(struct spi_mem * mem,const struct spi_mem_dirmap_info * info)664 spi_mem_dirmap_create(struct spi_mem *mem,
665 		      const struct spi_mem_dirmap_info *info)
666 {
667 	struct spi_controller *ctlr = mem->spi->controller;
668 	struct spi_mem_dirmap_desc *desc;
669 	int ret = -ENOTSUPP;
670 
671 	/* Make sure the number of address cycles is between 1 and 8 bytes. */
672 	if (!info->op_tmpl.addr.nbytes || info->op_tmpl.addr.nbytes > 8)
673 		return ERR_PTR(-EINVAL);
674 
675 	/* data.dir should either be SPI_MEM_DATA_IN or SPI_MEM_DATA_OUT. */
676 	if (info->op_tmpl.data.dir == SPI_MEM_NO_DATA)
677 		return ERR_PTR(-EINVAL);
678 
679 	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
680 	if (!desc)
681 		return ERR_PTR(-ENOMEM);
682 
683 	desc->mem = mem;
684 	desc->info = *info;
685 	if (ctlr->mem_ops && ctlr->mem_ops->dirmap_create)
686 		ret = ctlr->mem_ops->dirmap_create(desc);
687 
688 	if (ret) {
689 		desc->nodirmap = true;
690 		if (!spi_mem_supports_op(desc->mem, &desc->info.op_tmpl))
691 			ret = -EOPNOTSUPP;
692 		else
693 			ret = 0;
694 	}
695 
696 	if (ret) {
697 		kfree(desc);
698 		return ERR_PTR(ret);
699 	}
700 
701 	return desc;
702 }
703 EXPORT_SYMBOL_GPL(spi_mem_dirmap_create);
704 
705 /**
706  * spi_mem_dirmap_destroy() - Destroy a direct mapping descriptor
707  * @desc: the direct mapping descriptor to destroy
708  *
709  * This function destroys a direct mapping descriptor previously created by
710  * spi_mem_dirmap_create().
711  */
spi_mem_dirmap_destroy(struct spi_mem_dirmap_desc * desc)712 void spi_mem_dirmap_destroy(struct spi_mem_dirmap_desc *desc)
713 {
714 	struct spi_controller *ctlr = desc->mem->spi->controller;
715 
716 	if (!desc->nodirmap && ctlr->mem_ops && ctlr->mem_ops->dirmap_destroy)
717 		ctlr->mem_ops->dirmap_destroy(desc);
718 
719 	kfree(desc);
720 }
721 EXPORT_SYMBOL_GPL(spi_mem_dirmap_destroy);
722 
devm_spi_mem_dirmap_release(struct device * dev,void * res)723 static void devm_spi_mem_dirmap_release(struct device *dev, void *res)
724 {
725 	struct spi_mem_dirmap_desc *desc = *(struct spi_mem_dirmap_desc **)res;
726 
727 	spi_mem_dirmap_destroy(desc);
728 }
729 
730 /**
731  * devm_spi_mem_dirmap_create() - Create a direct mapping descriptor and attach
732  *				  it to a device
733  * @dev: device the dirmap desc will be attached to
734  * @mem: SPI mem device this direct mapping should be created for
735  * @info: direct mapping information
736  *
737  * devm_ variant of the spi_mem_dirmap_create() function. See
738  * spi_mem_dirmap_create() for more details.
739  *
740  * Return: a valid pointer in case of success, and ERR_PTR() otherwise.
741  */
742 struct spi_mem_dirmap_desc *
devm_spi_mem_dirmap_create(struct device * dev,struct spi_mem * mem,const struct spi_mem_dirmap_info * info)743 devm_spi_mem_dirmap_create(struct device *dev, struct spi_mem *mem,
744 			   const struct spi_mem_dirmap_info *info)
745 {
746 	struct spi_mem_dirmap_desc **ptr, *desc;
747 
748 	ptr = devres_alloc(devm_spi_mem_dirmap_release, sizeof(*ptr),
749 			   GFP_KERNEL);
750 	if (!ptr)
751 		return ERR_PTR(-ENOMEM);
752 
753 	desc = spi_mem_dirmap_create(mem, info);
754 	if (IS_ERR(desc)) {
755 		devres_free(ptr);
756 	} else {
757 		*ptr = desc;
758 		devres_add(dev, ptr);
759 	}
760 
761 	return desc;
762 }
763 EXPORT_SYMBOL_GPL(devm_spi_mem_dirmap_create);
764 
devm_spi_mem_dirmap_match(struct device * dev,void * res,void * data)765 static int devm_spi_mem_dirmap_match(struct device *dev, void *res, void *data)
766 {
767 	struct spi_mem_dirmap_desc **ptr = res;
768 
769 	if (WARN_ON(!ptr || !*ptr))
770 		return 0;
771 
772 	return *ptr == data;
773 }
774 
775 /**
776  * devm_spi_mem_dirmap_destroy() - Destroy a direct mapping descriptor attached
777  *				   to a device
778  * @dev: device the dirmap desc is attached to
779  * @desc: the direct mapping descriptor to destroy
780  *
781  * devm_ variant of the spi_mem_dirmap_destroy() function. See
782  * spi_mem_dirmap_destroy() for more details.
783  */
devm_spi_mem_dirmap_destroy(struct device * dev,struct spi_mem_dirmap_desc * desc)784 void devm_spi_mem_dirmap_destroy(struct device *dev,
785 				 struct spi_mem_dirmap_desc *desc)
786 {
787 	devres_release(dev, devm_spi_mem_dirmap_release,
788 		       devm_spi_mem_dirmap_match, desc);
789 }
790 EXPORT_SYMBOL_GPL(devm_spi_mem_dirmap_destroy);
791 
792 /**
793  * spi_mem_dirmap_read() - Read data through a direct mapping
794  * @desc: direct mapping descriptor
795  * @offs: offset to start reading from. Note that this is not an absolute
796  *	  offset, but the offset within the direct mapping which already has
797  *	  its own offset
798  * @len: length in bytes
799  * @buf: destination buffer. This buffer must be DMA-able
800  *
801  * This function reads data from a memory device using a direct mapping
802  * previously instantiated with spi_mem_dirmap_create().
803  *
804  * Return: the amount of data read from the memory device or a negative error
805  * code. Note that the returned size might be smaller than @len, and the caller
806  * is responsible for calling spi_mem_dirmap_read() again when that happens.
807  */
spi_mem_dirmap_read(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,void * buf)808 ssize_t spi_mem_dirmap_read(struct spi_mem_dirmap_desc *desc,
809 			    u64 offs, size_t len, void *buf)
810 {
811 	struct spi_controller *ctlr = desc->mem->spi->controller;
812 	ssize_t ret;
813 
814 	if (desc->info.op_tmpl.data.dir != SPI_MEM_DATA_IN)
815 		return -EINVAL;
816 
817 	if (!len)
818 		return 0;
819 
820 	if (desc->nodirmap) {
821 		ret = spi_mem_no_dirmap_read(desc, offs, len, buf);
822 	} else if (ctlr->mem_ops && ctlr->mem_ops->dirmap_read) {
823 		ret = spi_mem_access_start(desc->mem);
824 		if (ret)
825 			return ret;
826 
827 		ret = ctlr->mem_ops->dirmap_read(desc, offs, len, buf);
828 
829 		spi_mem_access_end(desc->mem);
830 	} else {
831 		ret = -ENOTSUPP;
832 	}
833 
834 	return ret;
835 }
836 EXPORT_SYMBOL_GPL(spi_mem_dirmap_read);
837 
838 /**
839  * spi_mem_dirmap_write() - Write data through a direct mapping
840  * @desc: direct mapping descriptor
841  * @offs: offset to start writing from. Note that this is not an absolute
842  *	  offset, but the offset within the direct mapping which already has
843  *	  its own offset
844  * @len: length in bytes
845  * @buf: source buffer. This buffer must be DMA-able
846  *
847  * This function writes data to a memory device using a direct mapping
848  * previously instantiated with spi_mem_dirmap_create().
849  *
850  * Return: the amount of data written to the memory device or a negative error
851  * code. Note that the returned size might be smaller than @len, and the caller
852  * is responsible for calling spi_mem_dirmap_write() again when that happens.
853  */
spi_mem_dirmap_write(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,const void * buf)854 ssize_t spi_mem_dirmap_write(struct spi_mem_dirmap_desc *desc,
855 			     u64 offs, size_t len, const void *buf)
856 {
857 	struct spi_controller *ctlr = desc->mem->spi->controller;
858 	ssize_t ret;
859 
860 	if (desc->info.op_tmpl.data.dir != SPI_MEM_DATA_OUT)
861 		return -EINVAL;
862 
863 	if (!len)
864 		return 0;
865 
866 	if (desc->nodirmap) {
867 		ret = spi_mem_no_dirmap_write(desc, offs, len, buf);
868 	} else if (ctlr->mem_ops && ctlr->mem_ops->dirmap_write) {
869 		ret = spi_mem_access_start(desc->mem);
870 		if (ret)
871 			return ret;
872 
873 		ret = ctlr->mem_ops->dirmap_write(desc, offs, len, buf);
874 
875 		spi_mem_access_end(desc->mem);
876 	} else {
877 		ret = -ENOTSUPP;
878 	}
879 
880 	return ret;
881 }
882 EXPORT_SYMBOL_GPL(spi_mem_dirmap_write);
883 
to_spi_mem_drv(struct device_driver * drv)884 static inline struct spi_mem_driver *to_spi_mem_drv(struct device_driver *drv)
885 {
886 	return container_of(drv, struct spi_mem_driver, spidrv.driver);
887 }
888 
spi_mem_read_status(struct spi_mem * mem,const struct spi_mem_op * op,u16 * status)889 static int spi_mem_read_status(struct spi_mem *mem,
890 			       const struct spi_mem_op *op,
891 			       u16 *status)
892 {
893 	const u8 *bytes = (u8 *)op->data.buf.in;
894 	int ret;
895 
896 	ret = spi_mem_exec_op(mem, op);
897 	if (ret)
898 		return ret;
899 
900 	if (op->data.nbytes > 1)
901 		*status = ((u16)bytes[0] << 8) | bytes[1];
902 	else
903 		*status = bytes[0];
904 
905 	return 0;
906 }
907 
908 /**
909  * spi_mem_poll_status() - Poll memory device status
910  * @mem: SPI memory device
911  * @op: the memory operation to execute
912  * @mask: status bitmask to ckeck
913  * @match: (status & mask) expected value
914  * @initial_delay_us: delay in us before starting to poll
915  * @polling_delay_us: time to sleep between reads in us
916  * @timeout_ms: timeout in milliseconds
917  *
918  * This function polls a status register and returns when
919  * (status & mask) == match or when the timeout has expired.
920  *
921  * Return: 0 in case of success, -ETIMEDOUT in case of error,
922  *         -EOPNOTSUPP if not supported.
923  */
spi_mem_poll_status(struct spi_mem * mem,const struct spi_mem_op * op,u16 mask,u16 match,unsigned long initial_delay_us,unsigned long polling_delay_us,u16 timeout_ms)924 int spi_mem_poll_status(struct spi_mem *mem,
925 			const struct spi_mem_op *op,
926 			u16 mask, u16 match,
927 			unsigned long initial_delay_us,
928 			unsigned long polling_delay_us,
929 			u16 timeout_ms)
930 {
931 	struct spi_controller *ctlr = mem->spi->controller;
932 	int ret = -EOPNOTSUPP;
933 	int read_status_ret;
934 	u16 status;
935 
936 	if (op->data.nbytes < 1 || op->data.nbytes > 2 ||
937 	    op->data.dir != SPI_MEM_DATA_IN)
938 		return -EINVAL;
939 
940 	if (ctlr->mem_ops && ctlr->mem_ops->poll_status && !spi_get_csgpiod(mem->spi, 0)) {
941 		ret = spi_mem_access_start(mem);
942 		if (ret)
943 			return ret;
944 
945 		ret = ctlr->mem_ops->poll_status(mem, op, mask, match,
946 						 initial_delay_us, polling_delay_us,
947 						 timeout_ms);
948 
949 		spi_mem_access_end(mem);
950 	}
951 
952 	if (ret == -EOPNOTSUPP) {
953 		if (!spi_mem_supports_op(mem, op))
954 			return ret;
955 
956 		if (initial_delay_us < 10)
957 			udelay(initial_delay_us);
958 		else
959 			usleep_range((initial_delay_us >> 2) + 1,
960 				     initial_delay_us);
961 
962 		ret = read_poll_timeout(spi_mem_read_status, read_status_ret,
963 					(read_status_ret || ((status) & mask) == match),
964 					polling_delay_us, timeout_ms * 1000, false, mem,
965 					op, &status);
966 		if (read_status_ret)
967 			return read_status_ret;
968 	}
969 
970 	return ret;
971 }
972 EXPORT_SYMBOL_GPL(spi_mem_poll_status);
973 
spi_mem_probe(struct spi_device * spi)974 static int spi_mem_probe(struct spi_device *spi)
975 {
976 	struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
977 	struct spi_controller *ctlr = spi->controller;
978 	struct spi_mem *mem;
979 
980 	mem = devm_kzalloc(&spi->dev, sizeof(*mem), GFP_KERNEL);
981 	if (!mem)
982 		return -ENOMEM;
983 
984 	mem->spi = spi;
985 
986 	if (ctlr->mem_ops && ctlr->mem_ops->get_name)
987 		mem->name = ctlr->mem_ops->get_name(mem);
988 	else
989 		mem->name = dev_name(&spi->dev);
990 
991 	if (IS_ERR_OR_NULL(mem->name))
992 		return PTR_ERR_OR_ZERO(mem->name);
993 
994 	spi_set_drvdata(spi, mem);
995 
996 	return memdrv->probe(mem);
997 }
998 
spi_mem_remove(struct spi_device * spi)999 static void spi_mem_remove(struct spi_device *spi)
1000 {
1001 	struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
1002 	struct spi_mem *mem = spi_get_drvdata(spi);
1003 
1004 	if (memdrv->remove)
1005 		memdrv->remove(mem);
1006 }
1007 
spi_mem_shutdown(struct spi_device * spi)1008 static void spi_mem_shutdown(struct spi_device *spi)
1009 {
1010 	struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
1011 	struct spi_mem *mem = spi_get_drvdata(spi);
1012 
1013 	if (memdrv->shutdown)
1014 		memdrv->shutdown(mem);
1015 }
1016 
1017 /**
1018  * spi_mem_driver_register_with_owner() - Register a SPI memory driver
1019  * @memdrv: the SPI memory driver to register
1020  * @owner: the owner of this driver
1021  *
1022  * Registers a SPI memory driver.
1023  *
1024  * Return: 0 in case of success, a negative error core otherwise.
1025  */
1026 
spi_mem_driver_register_with_owner(struct spi_mem_driver * memdrv,struct module * owner)1027 int spi_mem_driver_register_with_owner(struct spi_mem_driver *memdrv,
1028 				       struct module *owner)
1029 {
1030 	memdrv->spidrv.probe = spi_mem_probe;
1031 	memdrv->spidrv.remove = spi_mem_remove;
1032 	memdrv->spidrv.shutdown = spi_mem_shutdown;
1033 
1034 	return __spi_register_driver(owner, &memdrv->spidrv);
1035 }
1036 EXPORT_SYMBOL_GPL(spi_mem_driver_register_with_owner);
1037 
1038 /**
1039  * spi_mem_driver_unregister() - Unregister a SPI memory driver
1040  * @memdrv: the SPI memory driver to unregister
1041  *
1042  * Unregisters a SPI memory driver.
1043  */
spi_mem_driver_unregister(struct spi_mem_driver * memdrv)1044 void spi_mem_driver_unregister(struct spi_mem_driver *memdrv)
1045 {
1046 	spi_unregister_driver(&memdrv->spidrv);
1047 }
1048 EXPORT_SYMBOL_GPL(spi_mem_driver_unregister);
1049