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, except if no
590 * frequency limit has been set, in this case we return the number of
591 * cycles nevertheless to allow callers to distinguish which operation
592 * would be the fastest at iso-frequency.
593 */
spi_mem_calc_op_duration(struct spi_mem * mem,struct spi_mem_op * op)594 u64 spi_mem_calc_op_duration(struct spi_mem *mem, struct spi_mem_op *op)
595 {
596 u64 ncycles = 0;
597 u64 ps_per_cycles, duration;
598
599 spi_mem_adjust_op_freq(mem, op);
600
601 if (op->max_freq) {
602 ps_per_cycles = 1000000000000ULL;
603 do_div(ps_per_cycles, op->max_freq);
604 } else {
605 /* In this case, the unit is no longer a time unit */
606 ps_per_cycles = 1;
607 }
608
609 ncycles += ((op->cmd.nbytes * 8) / op->cmd.buswidth) / (op->cmd.dtr ? 2 : 1);
610 ncycles += ((op->addr.nbytes * 8) / op->addr.buswidth) / (op->addr.dtr ? 2 : 1);
611
612 /* Dummy bytes are optional for some SPI flash memory operations */
613 if (op->dummy.nbytes)
614 ncycles += ((op->dummy.nbytes * 8) / op->dummy.buswidth) / (op->dummy.dtr ? 2 : 1);
615
616 ncycles += ((op->data.nbytes * 8) / op->data.buswidth) / (op->data.dtr ? 2 : 1);
617
618 /* Derive the duration in ps */
619 duration = ncycles * ps_per_cycles;
620 /* Convert into ns */
621 do_div(duration, 1000);
622
623 return duration;
624 }
625 EXPORT_SYMBOL_GPL(spi_mem_calc_op_duration);
626
spi_mem_no_dirmap_read(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,void * buf)627 static ssize_t spi_mem_no_dirmap_read(struct spi_mem_dirmap_desc *desc,
628 u64 offs, size_t len, void *buf)
629 {
630 struct spi_mem_op op = desc->info.op_tmpl;
631 int ret;
632
633 op.addr.val = desc->info.offset + offs;
634 op.data.buf.in = buf;
635 op.data.nbytes = len;
636 ret = spi_mem_adjust_op_size(desc->mem, &op);
637 if (ret)
638 return ret;
639
640 ret = spi_mem_exec_op(desc->mem, &op);
641 if (ret)
642 return ret;
643
644 return op.data.nbytes;
645 }
646
spi_mem_no_dirmap_write(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,const void * buf)647 static ssize_t spi_mem_no_dirmap_write(struct spi_mem_dirmap_desc *desc,
648 u64 offs, size_t len, const void *buf)
649 {
650 struct spi_mem_op op = desc->info.op_tmpl;
651 int ret;
652
653 op.addr.val = desc->info.offset + offs;
654 op.data.buf.out = buf;
655 op.data.nbytes = len;
656 ret = spi_mem_adjust_op_size(desc->mem, &op);
657 if (ret)
658 return ret;
659
660 ret = spi_mem_exec_op(desc->mem, &op);
661 if (ret)
662 return ret;
663
664 return op.data.nbytes;
665 }
666
667 /**
668 * spi_mem_dirmap_create() - Create a direct mapping descriptor
669 * @mem: SPI mem device this direct mapping should be created for
670 * @info: direct mapping information
671 *
672 * This function is creating a direct mapping descriptor which can then be used
673 * to access the memory using spi_mem_dirmap_read() or spi_mem_dirmap_write().
674 * If the SPI controller driver does not support direct mapping, this function
675 * falls back to an implementation using spi_mem_exec_op(), so that the caller
676 * doesn't have to bother implementing a fallback on his own.
677 *
678 * Return: a valid pointer in case of success, and ERR_PTR() otherwise.
679 */
680 struct spi_mem_dirmap_desc *
spi_mem_dirmap_create(struct spi_mem * mem,const struct spi_mem_dirmap_info * info)681 spi_mem_dirmap_create(struct spi_mem *mem,
682 const struct spi_mem_dirmap_info *info)
683 {
684 struct spi_controller *ctlr = mem->spi->controller;
685 struct spi_mem_dirmap_desc *desc;
686 int ret = -ENOTSUPP;
687
688 /* Make sure the number of address cycles is between 1 and 8 bytes. */
689 if (!info->op_tmpl.addr.nbytes || info->op_tmpl.addr.nbytes > 8)
690 return ERR_PTR(-EINVAL);
691
692 /* data.dir should either be SPI_MEM_DATA_IN or SPI_MEM_DATA_OUT. */
693 if (info->op_tmpl.data.dir == SPI_MEM_NO_DATA)
694 return ERR_PTR(-EINVAL);
695
696 desc = kzalloc(sizeof(*desc), GFP_KERNEL);
697 if (!desc)
698 return ERR_PTR(-ENOMEM);
699
700 desc->mem = mem;
701 desc->info = *info;
702 if (ctlr->mem_ops && ctlr->mem_ops->dirmap_create)
703 ret = ctlr->mem_ops->dirmap_create(desc);
704
705 if (ret) {
706 desc->nodirmap = true;
707 if (!spi_mem_supports_op(desc->mem, &desc->info.op_tmpl))
708 ret = -EOPNOTSUPP;
709 else
710 ret = 0;
711 }
712
713 if (ret) {
714 kfree(desc);
715 return ERR_PTR(ret);
716 }
717
718 return desc;
719 }
720 EXPORT_SYMBOL_GPL(spi_mem_dirmap_create);
721
722 /**
723 * spi_mem_dirmap_destroy() - Destroy a direct mapping descriptor
724 * @desc: the direct mapping descriptor to destroy
725 *
726 * This function destroys a direct mapping descriptor previously created by
727 * spi_mem_dirmap_create().
728 */
spi_mem_dirmap_destroy(struct spi_mem_dirmap_desc * desc)729 void spi_mem_dirmap_destroy(struct spi_mem_dirmap_desc *desc)
730 {
731 struct spi_controller *ctlr = desc->mem->spi->controller;
732
733 if (!desc->nodirmap && ctlr->mem_ops && ctlr->mem_ops->dirmap_destroy)
734 ctlr->mem_ops->dirmap_destroy(desc);
735
736 kfree(desc);
737 }
738 EXPORT_SYMBOL_GPL(spi_mem_dirmap_destroy);
739
devm_spi_mem_dirmap_release(struct device * dev,void * res)740 static void devm_spi_mem_dirmap_release(struct device *dev, void *res)
741 {
742 struct spi_mem_dirmap_desc *desc = *(struct spi_mem_dirmap_desc **)res;
743
744 spi_mem_dirmap_destroy(desc);
745 }
746
747 /**
748 * devm_spi_mem_dirmap_create() - Create a direct mapping descriptor and attach
749 * it to a device
750 * @dev: device the dirmap desc will be attached to
751 * @mem: SPI mem device this direct mapping should be created for
752 * @info: direct mapping information
753 *
754 * devm_ variant of the spi_mem_dirmap_create() function. See
755 * spi_mem_dirmap_create() for more details.
756 *
757 * Return: a valid pointer in case of success, and ERR_PTR() otherwise.
758 */
759 struct spi_mem_dirmap_desc *
devm_spi_mem_dirmap_create(struct device * dev,struct spi_mem * mem,const struct spi_mem_dirmap_info * info)760 devm_spi_mem_dirmap_create(struct device *dev, struct spi_mem *mem,
761 const struct spi_mem_dirmap_info *info)
762 {
763 struct spi_mem_dirmap_desc **ptr, *desc;
764
765 ptr = devres_alloc(devm_spi_mem_dirmap_release, sizeof(*ptr),
766 GFP_KERNEL);
767 if (!ptr)
768 return ERR_PTR(-ENOMEM);
769
770 desc = spi_mem_dirmap_create(mem, info);
771 if (IS_ERR(desc)) {
772 devres_free(ptr);
773 } else {
774 *ptr = desc;
775 devres_add(dev, ptr);
776 }
777
778 return desc;
779 }
780 EXPORT_SYMBOL_GPL(devm_spi_mem_dirmap_create);
781
devm_spi_mem_dirmap_match(struct device * dev,void * res,void * data)782 static int devm_spi_mem_dirmap_match(struct device *dev, void *res, void *data)
783 {
784 struct spi_mem_dirmap_desc **ptr = res;
785
786 if (WARN_ON(!ptr || !*ptr))
787 return 0;
788
789 return *ptr == data;
790 }
791
792 /**
793 * devm_spi_mem_dirmap_destroy() - Destroy a direct mapping descriptor attached
794 * to a device
795 * @dev: device the dirmap desc is attached to
796 * @desc: the direct mapping descriptor to destroy
797 *
798 * devm_ variant of the spi_mem_dirmap_destroy() function. See
799 * spi_mem_dirmap_destroy() for more details.
800 */
devm_spi_mem_dirmap_destroy(struct device * dev,struct spi_mem_dirmap_desc * desc)801 void devm_spi_mem_dirmap_destroy(struct device *dev,
802 struct spi_mem_dirmap_desc *desc)
803 {
804 devres_release(dev, devm_spi_mem_dirmap_release,
805 devm_spi_mem_dirmap_match, desc);
806 }
807 EXPORT_SYMBOL_GPL(devm_spi_mem_dirmap_destroy);
808
809 /**
810 * spi_mem_dirmap_read() - Read data through a direct mapping
811 * @desc: direct mapping descriptor
812 * @offs: offset to start reading from. Note that this is not an absolute
813 * offset, but the offset within the direct mapping which already has
814 * its own offset
815 * @len: length in bytes
816 * @buf: destination buffer. This buffer must be DMA-able
817 *
818 * This function reads data from a memory device using a direct mapping
819 * previously instantiated with spi_mem_dirmap_create().
820 *
821 * Return: the amount of data read from the memory device or a negative error
822 * code. Note that the returned size might be smaller than @len, and the caller
823 * is responsible for calling spi_mem_dirmap_read() again when that happens.
824 */
spi_mem_dirmap_read(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,void * buf)825 ssize_t spi_mem_dirmap_read(struct spi_mem_dirmap_desc *desc,
826 u64 offs, size_t len, void *buf)
827 {
828 struct spi_controller *ctlr = desc->mem->spi->controller;
829 ssize_t ret;
830
831 if (desc->info.op_tmpl.data.dir != SPI_MEM_DATA_IN)
832 return -EINVAL;
833
834 if (!len)
835 return 0;
836
837 if (desc->nodirmap) {
838 ret = spi_mem_no_dirmap_read(desc, offs, len, buf);
839 } else if (ctlr->mem_ops && ctlr->mem_ops->dirmap_read) {
840 ret = spi_mem_access_start(desc->mem);
841 if (ret)
842 return ret;
843
844 ret = ctlr->mem_ops->dirmap_read(desc, offs, len, buf);
845
846 spi_mem_access_end(desc->mem);
847 } else {
848 ret = -ENOTSUPP;
849 }
850
851 return ret;
852 }
853 EXPORT_SYMBOL_GPL(spi_mem_dirmap_read);
854
855 /**
856 * spi_mem_dirmap_write() - Write data through a direct mapping
857 * @desc: direct mapping descriptor
858 * @offs: offset to start writing from. Note that this is not an absolute
859 * offset, but the offset within the direct mapping which already has
860 * its own offset
861 * @len: length in bytes
862 * @buf: source buffer. This buffer must be DMA-able
863 *
864 * This function writes data to a memory device using a direct mapping
865 * previously instantiated with spi_mem_dirmap_create().
866 *
867 * Return: the amount of data written to the memory device or a negative error
868 * code. Note that the returned size might be smaller than @len, and the caller
869 * is responsible for calling spi_mem_dirmap_write() again when that happens.
870 */
spi_mem_dirmap_write(struct spi_mem_dirmap_desc * desc,u64 offs,size_t len,const void * buf)871 ssize_t spi_mem_dirmap_write(struct spi_mem_dirmap_desc *desc,
872 u64 offs, size_t len, const void *buf)
873 {
874 struct spi_controller *ctlr = desc->mem->spi->controller;
875 ssize_t ret;
876
877 if (desc->info.op_tmpl.data.dir != SPI_MEM_DATA_OUT)
878 return -EINVAL;
879
880 if (!len)
881 return 0;
882
883 if (desc->nodirmap) {
884 ret = spi_mem_no_dirmap_write(desc, offs, len, buf);
885 } else if (ctlr->mem_ops && ctlr->mem_ops->dirmap_write) {
886 ret = spi_mem_access_start(desc->mem);
887 if (ret)
888 return ret;
889
890 ret = ctlr->mem_ops->dirmap_write(desc, offs, len, buf);
891
892 spi_mem_access_end(desc->mem);
893 } else {
894 ret = -ENOTSUPP;
895 }
896
897 return ret;
898 }
899 EXPORT_SYMBOL_GPL(spi_mem_dirmap_write);
900
to_spi_mem_drv(struct device_driver * drv)901 static inline struct spi_mem_driver *to_spi_mem_drv(struct device_driver *drv)
902 {
903 return container_of(drv, struct spi_mem_driver, spidrv.driver);
904 }
905
spi_mem_read_status(struct spi_mem * mem,const struct spi_mem_op * op,u16 * status)906 static int spi_mem_read_status(struct spi_mem *mem,
907 const struct spi_mem_op *op,
908 u16 *status)
909 {
910 const u8 *bytes = (u8 *)op->data.buf.in;
911 int ret;
912
913 ret = spi_mem_exec_op(mem, op);
914 if (ret)
915 return ret;
916
917 if (op->data.nbytes > 1)
918 *status = ((u16)bytes[0] << 8) | bytes[1];
919 else
920 *status = bytes[0];
921
922 return 0;
923 }
924
925 /**
926 * spi_mem_poll_status() - Poll memory device status
927 * @mem: SPI memory device
928 * @op: the memory operation to execute
929 * @mask: status bitmask to ckeck
930 * @match: (status & mask) expected value
931 * @initial_delay_us: delay in us before starting to poll
932 * @polling_delay_us: time to sleep between reads in us
933 * @timeout_ms: timeout in milliseconds
934 *
935 * This function polls a status register and returns when
936 * (status & mask) == match or when the timeout has expired.
937 *
938 * Return: 0 in case of success, -ETIMEDOUT in case of error,
939 * -EOPNOTSUPP if not supported.
940 */
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)941 int spi_mem_poll_status(struct spi_mem *mem,
942 const struct spi_mem_op *op,
943 u16 mask, u16 match,
944 unsigned long initial_delay_us,
945 unsigned long polling_delay_us,
946 u16 timeout_ms)
947 {
948 struct spi_controller *ctlr = mem->spi->controller;
949 int ret = -EOPNOTSUPP;
950 int read_status_ret;
951 u16 status;
952
953 if (op->data.nbytes < 1 || op->data.nbytes > 2 ||
954 op->data.dir != SPI_MEM_DATA_IN)
955 return -EINVAL;
956
957 if (ctlr->mem_ops && ctlr->mem_ops->poll_status && !spi_get_csgpiod(mem->spi, 0)) {
958 ret = spi_mem_access_start(mem);
959 if (ret)
960 return ret;
961
962 ret = ctlr->mem_ops->poll_status(mem, op, mask, match,
963 initial_delay_us, polling_delay_us,
964 timeout_ms);
965
966 spi_mem_access_end(mem);
967 }
968
969 if (ret == -EOPNOTSUPP) {
970 if (!spi_mem_supports_op(mem, op))
971 return ret;
972
973 if (initial_delay_us < 10)
974 udelay(initial_delay_us);
975 else
976 usleep_range((initial_delay_us >> 2) + 1,
977 initial_delay_us);
978
979 ret = read_poll_timeout(spi_mem_read_status, read_status_ret,
980 (read_status_ret || ((status) & mask) == match),
981 polling_delay_us, timeout_ms * 1000, false, mem,
982 op, &status);
983 if (read_status_ret)
984 return read_status_ret;
985 }
986
987 return ret;
988 }
989 EXPORT_SYMBOL_GPL(spi_mem_poll_status);
990
spi_mem_probe(struct spi_device * spi)991 static int spi_mem_probe(struct spi_device *spi)
992 {
993 struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
994 struct spi_controller *ctlr = spi->controller;
995 struct spi_mem *mem;
996
997 mem = devm_kzalloc(&spi->dev, sizeof(*mem), GFP_KERNEL);
998 if (!mem)
999 return -ENOMEM;
1000
1001 mem->spi = spi;
1002
1003 if (ctlr->mem_ops && ctlr->mem_ops->get_name)
1004 mem->name = ctlr->mem_ops->get_name(mem);
1005 else
1006 mem->name = dev_name(&spi->dev);
1007
1008 if (IS_ERR_OR_NULL(mem->name))
1009 return PTR_ERR_OR_ZERO(mem->name);
1010
1011 spi_set_drvdata(spi, mem);
1012
1013 return memdrv->probe(mem);
1014 }
1015
spi_mem_remove(struct spi_device * spi)1016 static void spi_mem_remove(struct spi_device *spi)
1017 {
1018 struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
1019 struct spi_mem *mem = spi_get_drvdata(spi);
1020
1021 if (memdrv->remove)
1022 memdrv->remove(mem);
1023 }
1024
spi_mem_shutdown(struct spi_device * spi)1025 static void spi_mem_shutdown(struct spi_device *spi)
1026 {
1027 struct spi_mem_driver *memdrv = to_spi_mem_drv(spi->dev.driver);
1028 struct spi_mem *mem = spi_get_drvdata(spi);
1029
1030 if (memdrv->shutdown)
1031 memdrv->shutdown(mem);
1032 }
1033
1034 /**
1035 * spi_mem_driver_register_with_owner() - Register a SPI memory driver
1036 * @memdrv: the SPI memory driver to register
1037 * @owner: the owner of this driver
1038 *
1039 * Registers a SPI memory driver.
1040 *
1041 * Return: 0 in case of success, a negative error core otherwise.
1042 */
1043
spi_mem_driver_register_with_owner(struct spi_mem_driver * memdrv,struct module * owner)1044 int spi_mem_driver_register_with_owner(struct spi_mem_driver *memdrv,
1045 struct module *owner)
1046 {
1047 memdrv->spidrv.probe = spi_mem_probe;
1048 memdrv->spidrv.remove = spi_mem_remove;
1049 memdrv->spidrv.shutdown = spi_mem_shutdown;
1050
1051 return __spi_register_driver(owner, &memdrv->spidrv);
1052 }
1053 EXPORT_SYMBOL_GPL(spi_mem_driver_register_with_owner);
1054
1055 /**
1056 * spi_mem_driver_unregister() - Unregister a SPI memory driver
1057 * @memdrv: the SPI memory driver to unregister
1058 *
1059 * Unregisters a SPI memory driver.
1060 */
spi_mem_driver_unregister(struct spi_mem_driver * memdrv)1061 void spi_mem_driver_unregister(struct spi_mem_driver *memdrv)
1062 {
1063 spi_unregister_driver(&memdrv->spidrv);
1064 }
1065 EXPORT_SYMBOL_GPL(spi_mem_driver_unregister);
1066