1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Copyright (C) 2018 Texas Instruments Incorporated - http://www.ti.com/
4 */
5
6 #include <log.h>
7 #include <malloc.h>
8 #include <spi.h>
9 #include <spi-mem.h>
10
spi_mem_exec_op(struct spi_slave * slave,const struct spi_mem_op * op)11 int spi_mem_exec_op(struct spi_slave *slave,
12 const struct spi_mem_op *op)
13 {
14 unsigned int pos = 0;
15 const u8 *tx_buf = NULL;
16 u8 *rx_buf = NULL;
17 u8 *op_buf;
18 int op_len;
19 u32 flag;
20 int ret;
21 int i;
22
23 if (op->data.nbytes) {
24 if (op->data.dir == SPI_MEM_DATA_IN)
25 rx_buf = op->data.buf.in;
26 else
27 tx_buf = op->data.buf.out;
28 }
29
30 op_len = sizeof(op->cmd.opcode) + op->addr.nbytes + op->dummy.nbytes;
31 op_buf = calloc(1, op_len);
32
33 ret = spi_claim_bus(slave);
34 if (ret < 0)
35 return ret;
36
37 op_buf[pos++] = op->cmd.opcode;
38
39 if (op->addr.nbytes) {
40 for (i = 0; i < op->addr.nbytes; i++)
41 op_buf[pos + i] = op->addr.val >>
42 (8 * (op->addr.nbytes - i - 1));
43
44 pos += op->addr.nbytes;
45 }
46
47 if (op->dummy.nbytes)
48 memset(op_buf + pos, 0xff, op->dummy.nbytes);
49
50 /* 1st transfer: opcode + address + dummy cycles */
51 flag = SPI_XFER_BEGIN;
52 /* Make sure to set END bit if no tx or rx data messages follow */
53 if (!tx_buf && !rx_buf)
54 flag |= SPI_XFER_END;
55
56 ret = spi_xfer(slave, op_len * 8, op_buf, NULL, flag);
57 if (ret)
58 return ret;
59
60 /* 2nd transfer: rx or tx data path */
61 if (tx_buf || rx_buf) {
62 ret = spi_xfer(slave, op->data.nbytes * 8, tx_buf,
63 rx_buf, SPI_XFER_END);
64 if (ret)
65 return ret;
66 }
67
68 spi_release_bus(slave);
69
70 for (i = 0; i < pos; i++)
71 debug("%02x ", op_buf[i]);
72 debug("| [%dB %s] ",
73 tx_buf || rx_buf ? op->data.nbytes : 0,
74 tx_buf || rx_buf ? (tx_buf ? "out" : "in") : "-");
75 for (i = 0; i < op->data.nbytes; i++)
76 debug("%02x ", tx_buf ? tx_buf[i] : rx_buf[i]);
77 debug("[ret %d]\n", ret);
78
79 free(op_buf);
80
81 if (ret < 0)
82 return ret;
83
84 return 0;
85 }
86
spi_mem_adjust_op_size(struct spi_slave * slave,struct spi_mem_op * op)87 int spi_mem_adjust_op_size(struct spi_slave *slave,
88 struct spi_mem_op *op)
89 {
90 unsigned int len;
91
92 len = sizeof(op->cmd.opcode) + op->addr.nbytes + op->dummy.nbytes;
93 if (slave->max_write_size && len > slave->max_write_size)
94 return -EINVAL;
95
96 if (op->data.dir == SPI_MEM_DATA_IN && slave->max_read_size)
97 op->data.nbytes = min(op->data.nbytes,
98 slave->max_read_size);
99 else if (slave->max_write_size)
100 op->data.nbytes = min(op->data.nbytes,
101 slave->max_write_size - len);
102
103 if (!op->data.nbytes)
104 return -EINVAL;
105
106 return 0;
107 }
108