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