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