1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <stdint.h>
19 #include <string.h>
20 
21 #include <gpio.h>
22 #include <i2c.h>
23 #include <seos.h>
24 #include <util.h>
25 #include <gpio.h>
26 #include <atomicBitset.h>
27 #include <atomic.h>
28 #include <platform.h>
29 
30 #include <plat/inc/cmsis.h>
31 #include <plat/inc/dma.h>
32 #include <plat/inc/gpio.h>
33 #include <plat/inc/i2c.h>
34 #include <plat/inc/pwr.h>
35 #include <plat/inc/plat.h>
36 
37 #include <cpu/inc/barrier.h>
38 
39 #define I2C_VERBOSE_DEBUG       0
40 #define I2C_MAX_QUEUE_DEPTH     5
41 
42 #if I2C_VERBOSE_DEBUG
43 #define i2c_log_debug(x) osLog(LOG_DEBUG, x "\n")
44 #else
45 #define i2c_log_debug(x) do {} while(0)
46 #endif
47 
48 #define I2C_CR1_PE          (1 << 0)
49 #define I2C_CR1_SMBUS       (1 << 1)
50 #define I2C_CR1_SMBTYPE     (1 << 3)
51 #define I2C_CR1_ENARP       (1 << 4)
52 #define I2C_CR1_ENPEC       (1 << 5)
53 #define I2C_CR1_ENGC        (1 << 6)
54 #define I2C_CR1_NOSTRETCH   (1 << 7)
55 #define I2C_CR1_START       (1 << 8)
56 #define I2C_CR1_STOP        (1 << 9)
57 #define I2C_CR1_ACK         (1 << 10)
58 #define I2C_CR1_POS         (1 << 11)
59 #define I2C_CR1_PEC         (1 << 12)
60 #define I2C_CR1_ALERT       (1 << 13)
61 #define I2C_CR1_SWRST       (1 << 15)
62 
63 #define I2C_CR2_FREQ(x)     ((x) & I2C_CR2_FREQ_MASK)
64 #define I2C_CR2_FREQ_MASK   0x3F
65 #define I2C_CR2_ITERREN     (1 << 8)
66 #define I2C_CR2_ITEVTEN     (1 << 9)
67 #define I2C_CR2_ITBUFEN     (1 << 10)
68 #define I2C_CR2_DMAEN       (1 << 11)
69 #define I2C_CR2_LAST        (1 << 12)
70 
71 #define I2C_OAR1_ADD7(x)    (((x) & I2C_OAR1_ADD7_MASK) << 1)
72 #define I2C_OAR1_ADD7_MASK  0x7F
73 #define I2C_OAR1_ADD10(x)   ((x) & I2C_OAR1_ADD10_MASK)
74 #define I2C_OAR1_ADD10_MASK 0x3FF
75 #define I2C_OAR1_ADDMODE    (1 << 15)
76 
77 #define I2C_SR1_SB          (1 << 0)
78 #define I2C_SR1_ADDR        (1 << 1)
79 #define I2C_SR1_BTF         (1 << 2)
80 #define I2C_SR1_ADD10       (1 << 3)
81 #define I2C_SR1_STOPF       (1 << 4)
82 #define I2C_SR1_RXNE        (1 << 6)
83 #define I2C_SR1_TXE         (1 << 7)
84 #define I2C_SR1_BERR        (1 << 8)
85 #define I2C_SR1_ARLO        (1 << 9)
86 #define I2C_SR1_AF          (1 << 10)
87 #define I2C_SR1_OVR         (1 << 11)
88 #define I2C_SR1_PECERR      (1 << 12)
89 #define I2C_SR1_TIMEOUT     (1 << 14)
90 #define I2C_SR1_SMBALERT    (1 << 15)
91 
92 #define I2C_SR2_MSL         (1 << 0)
93 #define I2C_SR2_BUSY        (1 << 1)
94 #define I2C_SR2_TRA         (1 << 2)
95 #define I2C_SR2_GENCALL     (1 << 4)
96 #define I2C_SR2_SMBDEFAULT  (1 << 5)
97 #define I2C_SR2_SMBHOST     (1 << 6)
98 #define I2C_SR2_DUALF       (1 << 7)
99 
100 #define I2C_CCR(x)          ((x) & I2C_CCR_MASK)
101 #define I2C_CCR_MASK        0xFFF
102 #define I2C_CCR_DUTY_16_9   (1 << 14)
103 #define I2C_CCR_FM          (1 << 15)
104 
105 #define I2C_TRISE(x)        ((x) & I2C_TRISE_MASK)
106 #define I2C_TRISE_MASK      0x3F
107 
108 struct StmI2c {
109     volatile uint32_t CR1;
110     volatile uint32_t CR2;
111     volatile uint32_t OAR1;
112     volatile uint32_t OAR2;
113     volatile uint32_t DR;
114     volatile uint32_t SR1;
115     volatile uint32_t SR2;
116     volatile uint32_t CCR;
117     volatile uint32_t TRISE;
118     volatile uint32_t FLTR;
119 };
120 
121 enum StmI2cSpiMasterState
122 {
123     STM_I2C_MASTER_IDLE,
124     STM_I2C_MASTER_START,
125     STM_I2C_MASTER_TX_ADDR,
126     STM_I2C_MASTER_TX_DATA,
127     STM_I2C_MASTER_RX_ADDR,
128     STM_I2C_MASTER_RX_DATA,
129 };
130 
131 struct I2cStmState {
132     struct {
133         union {
134             uint8_t *buf;
135             const uint8_t *cbuf;
136             uint8_t byte;
137         };
138         size_t size;
139         size_t offset;
140         bool preamble;
141 
142         I2cCallbackF callback;
143         void *cookie;
144     } rx, tx;
145 
146     enum {
147         STM_I2C_DISABLED,
148         STM_I2C_SLAVE,
149         STM_I2C_MASTER,
150     } mode;
151 
152     enum {
153         STM_I2C_SLAVE_IDLE,
154         STM_I2C_SLAVE_RX_ARMED,
155         STM_I2C_SLAVE_RX,
156         STM_I2C_SLAVE_TX_ARMED,
157         STM_I2C_SLAVE_TX,
158     } slaveState;
159 
160     // StmI2cSpiMasterState
161     uint8_t masterState;
162     uint16_t tid;
163 };
164 
165 struct StmI2cCfg {
166     struct StmI2c *regs;
167 
168     uint32_t clock;
169 
170     IRQn_Type irqEv;
171     IRQn_Type irqEr;
172 };
173 
174 struct StmI2cDev {
175     const struct StmI2cCfg *cfg;
176     const struct StmI2cBoardCfg *board;
177     struct I2cStmState state;
178 
179     uint32_t next;
180     uint32_t last;
181 
182     struct Gpio *scl;
183     struct Gpio *sda;
184 
185     uint8_t addr;
186 };
187 
188 static const struct StmI2cCfg mStmI2cCfgs[] = {
189     [0] = {
190         .regs = (struct StmI2c *)I2C1_BASE,
191 
192         .clock = PERIPH_APB1_I2C1,
193 
194         .irqEv = I2C1_EV_IRQn,
195         .irqEr = I2C1_ER_IRQn,
196     },
197     [1] = {
198         .regs = (struct StmI2c *)I2C2_BASE,
199 
200         .clock = PERIPH_APB1_I2C2,
201 
202         .irqEv = I2C2_EV_IRQn,
203         .irqEr = I2C2_ER_IRQn,
204     },
205     [2] = {
206         .regs = (struct StmI2c *)I2C3_BASE,
207 
208         .clock = PERIPH_APB1_I2C3,
209 
210         .irqEv = I2C3_EV_IRQn,
211         .irqEr = I2C3_ER_IRQn,
212     },
213 };
214 
215 static struct StmI2cDev mStmI2cDevs[ARRAY_SIZE(mStmI2cCfgs)];
216 
217 struct StmI2cXfer
218 {
219     uint32_t        id;
220     const void     *txBuf;
221     size_t          txSize;
222     void           *rxBuf;
223     size_t          rxSize;
224     I2cCallbackF    callback;
225     void           *cookie;
226     uint8_t         busId; /* for us these are both fine in a uint 8 */
227     uint8_t         addr;
228 };
229 
230 ATOMIC_BITSET_DECL(mXfersValid, I2C_MAX_QUEUE_DEPTH, static);
231 static struct StmI2cXfer mXfers[I2C_MAX_QUEUE_DEPTH] = { };
232 
stmI2cGetXfer(void)233 static inline struct StmI2cXfer *stmI2cGetXfer(void)
234 {
235     int32_t idx = atomicBitsetFindClearAndSet(mXfersValid);
236 
237     if (idx < 0)
238         return NULL;
239     else
240         return mXfers + idx;
241 }
242 
stmI2cPutXfer(struct StmI2cXfer * xfer)243 static inline void stmI2cPutXfer(struct StmI2cXfer *xfer)
244 {
245     if (xfer)
246         atomicBitsetClearBit(mXfersValid, xfer - mXfers);
247 }
248 
stmI2cAckEnable(struct StmI2cDev * pdev)249 static inline void stmI2cAckEnable(struct StmI2cDev *pdev)
250 {
251     pdev->cfg->regs->CR1 |= I2C_CR1_ACK;
252 }
253 
stmI2cAckDisable(struct StmI2cDev * pdev)254 static inline void stmI2cAckDisable(struct StmI2cDev *pdev)
255 {
256     pdev->cfg->regs->CR1 &= ~I2C_CR1_ACK;
257 }
258 
stmI2cDmaEnable(struct StmI2cDev * pdev)259 static inline void stmI2cDmaEnable(struct StmI2cDev *pdev)
260 {
261     pdev->cfg->regs->CR2 |= I2C_CR2_DMAEN;
262 }
263 
stmI2cDmaDisable(struct StmI2cDev * pdev)264 static inline void stmI2cDmaDisable(struct StmI2cDev *pdev)
265 {
266     pdev->cfg->regs->CR2 &= ~I2C_CR2_DMAEN;
267 }
268 
stmI2cStopEnable(struct StmI2cDev * pdev)269 static inline void stmI2cStopEnable(struct StmI2cDev *pdev)
270 {
271     struct StmI2c *regs = pdev->cfg->regs;
272 
273     while (regs->CR1 & (I2C_CR1_STOP | I2C_CR1_START))
274         ;
275     regs->CR1 |= I2C_CR1_STOP;
276 }
277 
stmI2cStartEnable(struct StmI2cDev * pdev)278 static inline void stmI2cStartEnable(struct StmI2cDev *pdev)
279 {
280     struct StmI2c *regs = pdev->cfg->regs;
281 
282     while (regs->CR1 & (I2C_CR1_STOP | I2C_CR1_START))
283         ;
284     regs->CR1 |= I2C_CR1_START;
285 }
286 
stmI2cIrqEnable(struct StmI2cDev * pdev,uint32_t mask)287 static inline void stmI2cIrqEnable(struct StmI2cDev *pdev,
288         uint32_t mask)
289 {
290     pdev->cfg->regs->CR2 |= mask;
291 }
292 
stmI2cIrqDisable(struct StmI2cDev * pdev,uint32_t mask)293 static inline void stmI2cIrqDisable(struct StmI2cDev *pdev,
294         uint32_t mask)
295 {
296     pdev->cfg->regs->CR2 &= ~mask;
297 }
298 
stmI2cEnable(struct StmI2cDev * pdev)299 static inline void stmI2cEnable(struct StmI2cDev *pdev)
300 {
301     pdev->cfg->regs->CR1 |= I2C_CR1_PE;
302 }
303 
stmI2cDisable(struct StmI2cDev * pdev)304 static inline void stmI2cDisable(struct StmI2cDev *pdev)
305 {
306     pdev->cfg->regs->CR1 &= ~I2C_CR1_PE;
307 }
308 
stmI2cSpeedSet(struct StmI2cDev * pdev,const uint32_t speed)309 static inline void stmI2cSpeedSet(struct StmI2cDev *pdev,
310         const uint32_t speed)
311 {
312     struct StmI2c *regs = pdev->cfg->regs;
313     int ccr, ccr_1, ccr_2;
314     int apb1_clk;
315 
316     apb1_clk = pwrGetBusSpeed(PERIPH_BUS_APB1);
317 
318     regs->CR2 = (regs->CR2 & ~I2C_CR2_FREQ_MASK) |
319                  I2C_CR2_FREQ(apb1_clk / 1000000);
320 
321     if (speed <= 100000) {
322         ccr = apb1_clk / (speed * 2);
323         if (ccr < 4)
324             ccr = 4;
325         regs->CCR = I2C_CCR(ccr);
326 
327         regs->TRISE = I2C_TRISE((apb1_clk / 1000000) + 1);
328     } else if (speed <= 400000) {
329         ccr_1 = apb1_clk / (speed * 3);
330         if (ccr_1 == 0 || apb1_clk / (ccr_1 * 3) > speed)
331             ccr_1 ++;
332         ccr_2 = apb1_clk / (speed * 25);
333         if (ccr_2 == 0 || apb1_clk / (ccr_2 * 25) > speed)
334             ccr_2 ++;
335 
336         if ((apb1_clk / (ccr_1 * 3)) > (apb1_clk / (ccr_2 * 25)))
337             regs->CCR = I2C_CCR_FM | I2C_CCR(ccr_1);
338         else
339             regs->CCR = I2C_CCR_FM | I2C_CCR_DUTY_16_9 | I2C_CCR(ccr_2);
340 
341         regs->TRISE = I2C_TRISE(((3*apb1_clk)/10000000) + 1);
342     }
343 }
344 
stmI2cSlaveIdle(struct StmI2cDev * pdev)345 static inline void stmI2cSlaveIdle(struct StmI2cDev *pdev)
346 {
347     struct I2cStmState *state = &pdev->state;
348 
349     state->slaveState = STM_I2C_SLAVE_RX_ARMED;
350     stmI2cAckEnable(pdev);
351     stmI2cIrqDisable(pdev, I2C_CR2_ITBUFEN | I2C_CR2_ITERREN);
352 }
353 
stmI2cInvokeRxCallback(struct I2cStmState * state,size_t tx,size_t rx,int err)354 static inline void stmI2cInvokeRxCallback(struct I2cStmState *state, size_t tx, size_t rx, int err)
355 {
356     uint16_t oldTid = osSetCurrentTid(state->tid);
357     state->rx.callback(state->rx.cookie, tx, rx, err);
358     osSetCurrentTid(oldTid);
359 }
360 
stmI2cInvokeTxCallback(struct I2cStmState * state,size_t tx,size_t rx,int err)361 static inline void stmI2cInvokeTxCallback(struct I2cStmState *state, size_t tx, size_t rx, int err)
362 {
363     uint16_t oldTid = osSetCurrentTid(state->tid);
364     state->tx.callback(state->tx.cookie, tx, rx, err);
365     osSetCurrentTid(oldTid);
366 }
367 
stmI2cSlaveRxDone(struct StmI2cDev * pdev)368 static inline void stmI2cSlaveRxDone(struct StmI2cDev *pdev)
369 {
370     struct I2cStmState *state = &pdev->state;
371     size_t rxOffst = state->rx.offset;
372 
373     state->rx.offset = 0;
374     stmI2cInvokeRxCallback(state, 0, rxOffst, 0);
375 }
376 
stmI2cSlaveTxDone(struct StmI2cDev * pdev)377 static inline void stmI2cSlaveTxDone(struct StmI2cDev *pdev)
378 {
379     struct I2cStmState *state = &pdev->state;
380     size_t txOffst = state->tx.offset;
381 
382     stmI2cSlaveIdle(pdev);
383     stmI2cInvokeTxCallback(state, txOffst, 0, 0);
384 }
385 
stmI2cSlaveTxNextByte(struct StmI2cDev * pdev)386 static void stmI2cSlaveTxNextByte(struct StmI2cDev *pdev)
387 {
388     struct I2cStmState *state = &pdev->state;
389     struct StmI2c *regs = pdev->cfg->regs;
390 
391     if (state->tx.preamble) {
392         regs->DR = state->tx.byte;
393         state->tx.offset++;
394     } else if (state->tx.offset < state->tx.size) {
395         regs->DR = state->tx.cbuf[state->tx.offset];
396         state->tx.offset++;
397     } else {
398         state->slaveState = STM_I2C_SLAVE_TX_ARMED;
399         stmI2cIrqDisable(pdev, I2C_CR2_ITBUFEN);
400         stmI2cInvokeTxCallback(state, state->tx.offset, 0, 0);
401     }
402 }
403 
stmI2cSlaveAddrMatched(struct StmI2cDev * pdev)404 static void stmI2cSlaveAddrMatched(struct StmI2cDev *pdev)
405 {
406     struct I2cStmState *state = &pdev->state;
407     struct StmI2c *regs = pdev->cfg->regs;
408 
409     i2c_log_debug("addr");
410 
411     if (state->slaveState == STM_I2C_SLAVE_RX_ARMED) {
412         state->slaveState = STM_I2C_SLAVE_RX;
413         stmI2cIrqEnable(pdev, I2C_CR2_ITBUFEN | I2C_CR2_ITERREN);
414     } else if (state->slaveState == STM_I2C_SLAVE_TX) {
415         stmI2cIrqEnable(pdev, I2C_CR2_ITBUFEN | I2C_CR2_ITERREN);
416     }
417     /* clear ADDR by doing a dummy reads from SR1 (already read) then SR2 */
418     (void)regs->SR2;
419 }
420 
stmI2cSlaveStopRxed(struct StmI2cDev * pdev)421 static void stmI2cSlaveStopRxed(struct StmI2cDev *pdev)
422 {
423     struct StmI2c *regs = pdev->cfg->regs;
424 
425     i2c_log_debug("stopf");
426 
427     (void)regs->SR1;
428     stmI2cEnable(pdev);
429     /* clear STOPF by doing a dummy read from SR1 and strobing the PE bit */
430 
431     stmI2cSlaveIdle(pdev);
432     stmI2cSlaveRxDone(pdev);
433 }
434 
stmI2cSlaveRxBufNotEmpty(struct StmI2cDev * pdev)435 static inline void stmI2cSlaveRxBufNotEmpty(struct StmI2cDev *pdev)
436 {
437     struct I2cStmState *state = &pdev->state;
438     struct StmI2c *regs = pdev->cfg->regs;
439     uint8_t data = regs->DR;
440 
441     i2c_log_debug("rxne");
442 
443     if (state->rx.offset < state->rx.size) {
444         state->rx.buf[state->rx.offset] = data;
445         state->rx.offset++;
446     } else {
447         stmI2cAckDisable(pdev);
448         /* TODO: error on overflow */
449     }
450 }
451 
stmI2cSlaveTxBufEmpty(struct StmI2cDev * pdev)452 static void stmI2cSlaveTxBufEmpty(struct StmI2cDev *pdev)
453 {
454     struct I2cStmState *state = &pdev->state;
455 
456     i2c_log_debug("txe");
457 
458     if (state->slaveState == STM_I2C_SLAVE_RX) {
459         state->slaveState = STM_I2C_SLAVE_TX_ARMED;
460         stmI2cIrqDisable(pdev, I2C_CR2_ITBUFEN);
461         stmI2cAckDisable(pdev);
462         stmI2cSlaveRxDone(pdev);
463         /* stmI2cTxNextByte() will happen when the task provides a
464            TX buffer; the I2C controller will stretch the clock until then */
465     } else {
466         stmI2cSlaveTxNextByte(pdev);
467     }
468 }
469 
stmI2cSlaveNakRxed(struct StmI2cDev * pdev)470 static void stmI2cSlaveNakRxed(struct StmI2cDev *pdev)
471 {
472     struct I2cStmState *state = &pdev->state;
473     struct StmI2c *regs = pdev->cfg->regs;
474 
475     i2c_log_debug("af");
476 
477     if (state->slaveState == STM_I2C_SLAVE_TX) {
478         state->tx.offset--;
479         /* NACKs seem to be preceded by a spurious TXNE, so adjust the offset to
480            compensate (the corresponding byte written to DR was never actually
481            transmitted) */
482         stmI2cSlaveTxDone(pdev);
483     }
484     regs->SR1 &= ~I2C_SR1_AF;
485 }
486 
stmI2cMasterTxRxDone(struct StmI2cDev * pdev,int err)487 static inline void stmI2cMasterTxRxDone(struct StmI2cDev *pdev, int err)
488 {
489     struct I2cStmState *state = &pdev->state;
490     size_t txOffst = state->tx.offset;
491     size_t rxOffst = state->rx.offset;
492     uint32_t id;
493     int i;
494     struct StmI2cXfer *xfer;
495 
496     if (pdev->board->sleepDev >= 0)
497         platReleaseDevInSleepMode(pdev->board->sleepDev);
498 
499     state->tx.offset = 0;
500     state->rx.offset = 0;
501     stmI2cInvokeTxCallback(state, txOffst, rxOffst, 0);
502 
503     do {
504         id = atomicAdd32bits(&pdev->next, 1);
505     } while (!id);
506 
507     for (i=0; i<I2C_MAX_QUEUE_DEPTH; i++) {
508         xfer = &mXfers[i];
509 
510         if (xfer->busId == (pdev - mStmI2cDevs) &&
511                 atomicCmpXchg32bits(&xfer->id, id, 0)) {
512             pdev->addr = xfer->addr;
513             state->tx.cbuf = xfer->txBuf;
514             state->tx.offset = 0;
515             state->tx.size = xfer->txSize;
516             state->tx.callback = xfer->callback;
517             state->tx.cookie = xfer->cookie;
518             state->rx.buf = xfer->rxBuf;
519             state->rx.offset = 0;
520             state->rx.size = xfer->rxSize;
521             state->rx.callback = NULL;
522             state->rx.cookie = NULL;
523             atomicWriteByte(&state->masterState, STM_I2C_MASTER_START);
524             if (pdev->board->sleepDev >= 0)
525                 platRequestDevInSleepMode(pdev->board->sleepDev, 12);
526             stmI2cPutXfer(xfer);
527             stmI2cStartEnable(pdev);
528             return;
529         }
530     }
531 
532     atomicWriteByte(&state->masterState, STM_I2C_MASTER_IDLE);
533 }
534 
stmI2cMasterDmaTxDone(void * cookie,uint16_t bytesLeft,int err)535 static void stmI2cMasterDmaTxDone(void *cookie, uint16_t bytesLeft, int err)
536 {
537     struct StmI2cDev *pdev = cookie;
538     struct I2cStmState *state = &pdev->state;
539     struct StmI2c *regs = pdev->cfg->regs;
540 
541     state->tx.offset = state->tx.size - bytesLeft;
542     state->tx.size = 0;
543     stmI2cDmaDisable(pdev);
544     if (err == 0 && state->rx.size > 0) {
545         atomicWriteByte(&state->masterState, STM_I2C_MASTER_START);
546         stmI2cStartEnable(pdev);
547     } else {
548         while (!(regs->SR1 & I2C_SR1_BTF))
549             ;
550 
551         stmI2cStopEnable(pdev);
552         stmI2cMasterTxRxDone(pdev, err);
553     }
554 }
555 
stmI2cMasterDmaRxDone(void * cookie,uint16_t bytesLeft,int err)556 static void stmI2cMasterDmaRxDone(void *cookie, uint16_t bytesLeft, int err)
557 {
558     struct StmI2cDev *pdev = cookie;
559     struct I2cStmState *state = &pdev->state;
560 
561     state->rx.offset = state->rx.size - bytesLeft;
562     state->rx.size = 0;
563 
564     stmI2cDmaDisable(pdev);
565     stmI2cStopEnable(pdev);
566     stmI2cMasterTxRxDone(pdev, err);
567 }
568 
stmI2cMasterDmaCancel(struct StmI2cDev * pdev)569 static inline void stmI2cMasterDmaCancel(struct StmI2cDev *pdev)
570 {
571     struct I2cStmState *state = &pdev->state;
572 
573     dmaStop(I2C_DMA_BUS, pdev->board->dmaRx.stream);
574     state->rx.offset = state->rx.size - dmaBytesLeft(I2C_DMA_BUS,
575             pdev->board->dmaRx.stream);
576     dmaStop(I2C_DMA_BUS, pdev->board->dmaTx.stream);
577     state->tx.offset = state->tx.size - dmaBytesLeft(I2C_DMA_BUS,
578             pdev->board->dmaTx.stream);
579 
580     stmI2cDmaDisable(pdev);
581 }
582 
stmI2cMasterStartDma(struct StmI2cDev * pdev,const struct StmI2cDmaCfg * dmaCfg,const void * buf,size_t size,DmaCallbackF callback,bool rx,bool last)583 static inline void stmI2cMasterStartDma(struct StmI2cDev *pdev,
584         const struct StmI2cDmaCfg *dmaCfg, const void *buf,
585         size_t size, DmaCallbackF callback, bool rx, bool last)
586 {
587     struct StmI2c *regs = pdev->cfg->regs;
588     struct dmaMode mode;
589 
590     memset(&mode, 0, sizeof(mode));
591     mode.priority = DMA_PRIORITY_HIGH;
592     mode.direction = rx ? DMA_DIRECTION_PERIPH_TO_MEM :
593             DMA_DIRECTION_MEM_TO_PERIPH;
594     mode.periphAddr = (uintptr_t)&regs->DR;
595     mode.minc = true;
596     mode.channel = dmaCfg->channel;
597 
598     dmaStart(I2C_DMA_BUS, dmaCfg->stream, buf, size, &mode, callback, pdev);
599     if (last)
600         stmI2cIrqEnable(pdev, I2C_CR2_LAST);
601     else
602         stmI2cIrqDisable(pdev, I2C_CR2_LAST);
603     stmI2cDmaEnable(pdev);
604 }
605 
stmI2cMasterSentStart(struct StmI2cDev * pdev)606 static void stmI2cMasterSentStart(struct StmI2cDev *pdev)
607 {
608     struct I2cStmState *state = &pdev->state;
609     struct StmI2c *regs = pdev->cfg->regs;
610 
611     if (atomicReadByte(&state->masterState) == STM_I2C_MASTER_START) {
612         if (state->tx.size > 0) {
613             atomicWriteByte(&state->masterState, STM_I2C_MASTER_TX_ADDR);
614             regs->DR = pdev->addr << 1;
615         } else {
616             atomicWriteByte(&state->masterState, STM_I2C_MASTER_RX_ADDR);
617             stmI2cAckEnable(pdev);
618             regs->DR = (pdev->addr << 1) | 0x01;
619         }
620     }
621 }
622 
stmI2cMasterSentAddr(struct StmI2cDev * pdev)623 static void stmI2cMasterSentAddr(struct StmI2cDev *pdev)
624 {
625     struct I2cStmState *state = &pdev->state;
626     struct StmI2c *regs = pdev->cfg->regs;
627     uint8_t masterState = atomicReadByte(&state->masterState);
628 
629     if (masterState == STM_I2C_MASTER_TX_ADDR) {
630         stmI2cMasterStartDma(pdev, &pdev->board->dmaTx, state->tx.cbuf,
631                 state->tx.size, stmI2cMasterDmaTxDone, false, !!state->rx.size);
632         regs->SR2; // Clear ADDR
633         atomicWriteByte(&state->masterState, STM_I2C_MASTER_TX_DATA);
634     } else if (masterState == STM_I2C_MASTER_RX_ADDR) {
635         if (state->rx.size == 1) // Generate NACK here for 1 byte transfers
636             stmI2cAckDisable(pdev);
637 
638         stmI2cMasterStartDma(pdev, &pdev->board->dmaRx, state->rx.buf,
639                 state->rx.size, stmI2cMasterDmaRxDone, true,
640                 state->rx.size > 1);
641         regs->SR2; // Clear ADDR
642         atomicWriteByte(&state->masterState, STM_I2C_MASTER_RX_DATA);
643     }
644 }
645 
stmI2cMasterNakRxed(struct StmI2cDev * pdev)646 static void stmI2cMasterNakRxed(struct StmI2cDev *pdev)
647 {
648     struct I2cStmState *state = &pdev->state;
649     struct StmI2c *regs = pdev->cfg->regs;
650     uint8_t masterState = atomicReadByte(&state->masterState);
651 
652     if (masterState == STM_I2C_MASTER_TX_ADDR ||
653             masterState == STM_I2C_MASTER_TX_DATA ||
654             masterState == STM_I2C_MASTER_RX_ADDR ||
655             masterState == STM_I2C_MASTER_RX_DATA) {
656         stmI2cMasterDmaCancel(pdev);
657 
658         regs->SR1 &= ~I2C_SR1_AF;
659         stmI2cStopEnable(pdev);
660         stmI2cMasterTxRxDone(pdev, 0);
661     }
662 }
663 
stmI2cMasterBusError(struct StmI2cDev * pdev)664 static void stmI2cMasterBusError(struct StmI2cDev *pdev)
665 {
666     struct StmI2c *regs = pdev->cfg->regs;
667 
668     stmI2cMasterDmaCancel(pdev);
669     regs->SR1 &= ~I2C_SR1_BERR;
670     stmI2cMasterTxRxDone(pdev, -EIO);
671 }
672 
stmI2cMasterArbitrationLoss(struct StmI2cDev * pdev)673 static void stmI2cMasterArbitrationLoss(struct StmI2cDev *pdev)
674 {
675     struct StmI2c *regs = pdev->cfg->regs;
676 
677     stmI2cMasterDmaCancel(pdev);
678     regs->SR1 &= ~I2C_SR1_ARLO;
679     stmI2cMasterTxRxDone(pdev, -EBUSY);
680 }
681 
stmI2cMasterUnexpectedError(struct StmI2cDev * pdev)682 static void stmI2cMasterUnexpectedError(struct StmI2cDev *pdev)
683 {
684     struct StmI2c *regs = pdev->cfg->regs;
685 
686     osLog(LOG_ERROR, "Unexpected I2C ERR interrupt: SR1 = %04lX, SR2 = %04lX\n",
687             regs->SR1, regs->SR2);
688 
689     stmI2cMasterDmaCancel(pdev);
690     regs->SR1 = 0;
691     stmI2cMasterTxRxDone(pdev, -EIO);
692 }
693 
stmI2cIsrEvent(struct StmI2cDev * pdev)694 static void stmI2cIsrEvent(struct StmI2cDev *pdev)
695 {
696     struct StmI2c *regs = pdev->cfg->regs;
697     uint16_t sr1 = regs->SR1;
698 
699     if (pdev->state.mode == STM_I2C_SLAVE) {
700         if (sr1 & I2C_SR1_ADDR) {
701             stmI2cSlaveAddrMatched(pdev);
702         } else if (sr1 & I2C_SR1_RXNE) {
703             stmI2cSlaveRxBufNotEmpty(pdev);
704         } else if (sr1 & I2C_SR1_TXE) {
705             stmI2cSlaveTxBufEmpty(pdev);
706         } else if (sr1 & I2C_SR1_BTF) {
707             if (regs->SR2 & I2C_SR2_TRA)
708                 stmI2cSlaveTxBufEmpty(pdev);
709            else
710                 stmI2cSlaveRxBufNotEmpty(pdev);
711         } else if (sr1 & I2C_SR1_STOPF) {
712             stmI2cSlaveStopRxed(pdev);
713         }
714         /* TODO: other flags */
715     } else if (pdev->state.mode == STM_I2C_MASTER) {
716         if (sr1 & I2C_SR1_SB)
717             stmI2cMasterSentStart(pdev);
718         else if (sr1 & I2C_SR1_ADDR)
719             stmI2cMasterSentAddr(pdev);
720     }
721 }
722 
stmI2cIsrError(struct StmI2cDev * pdev)723 static void stmI2cIsrError(struct StmI2cDev *pdev)
724 {
725     struct StmI2c *regs = pdev->cfg->regs;
726     uint16_t sr1 = regs->SR1;
727 
728     if (pdev->state.mode == STM_I2C_SLAVE) {
729         if (sr1 & I2C_SR1_AF)
730             stmI2cSlaveNakRxed(pdev);
731         /* TODO: other flags */
732     } else if (pdev->state.mode == STM_I2C_MASTER) {
733         if (sr1 & I2C_SR1_AF)
734             stmI2cMasterNakRxed(pdev);
735         else if (sr1 & I2C_SR1_BERR)
736             stmI2cMasterBusError(pdev);
737         else if (sr1 & I2C_SR1_ARLO)
738             stmI2cMasterArbitrationLoss(pdev);
739         else
740             stmI2cMasterUnexpectedError(pdev);
741     }
742 }
743 
744 #define DECLARE_IRQ_HANDLERS(_n)                \
745     extern void I2C##_n##_EV_IRQHandler();      \
746     extern void I2C##_n##_ER_IRQHandler();      \
747                                                 \
748     extern void I2C##_n##_EV_IRQHandler()       \
749     {                                           \
750         stmI2cIsrEvent(&mStmI2cDevs[_n - 1]);  \
751     }                                           \
752                                                 \
753     extern void I2C##_n##_ER_IRQHandler()       \
754     {                                           \
755         stmI2cIsrError(&mStmI2cDevs[_n - 1]);  \
756     }
757 
758 DECLARE_IRQ_HANDLERS(1);
759 DECLARE_IRQ_HANDLERS(3);
760 
stmI2cGpioInit(const struct StmI2cBoardCfg * board,const struct StmI2cGpioCfg * cfg)761 static inline struct Gpio* stmI2cGpioInit(const struct StmI2cBoardCfg *board, const struct StmI2cGpioCfg *cfg)
762 {
763     struct Gpio* gpio = gpioRequest(cfg->gpioNum);
764     gpioConfigAlt(gpio, board->gpioSpeed, board->gpioPull, GPIO_OUT_OPEN_DRAIN,
765             cfg->func);
766 
767     return gpio;
768 }
769 
i2cMasterRequest(uint32_t busId,uint32_t speed)770 int i2cMasterRequest(uint32_t busId, uint32_t speed)
771 {
772     if (busId >= ARRAY_SIZE(mStmI2cDevs))
773         return -EINVAL;
774 
775     const struct StmI2cBoardCfg *board = boardStmI2cCfg(busId);
776     if (!board)
777         return -EINVAL;
778 
779     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
780     struct I2cStmState *state = &pdev->state;
781     const struct StmI2cCfg *cfg = &mStmI2cCfgs[busId];
782 
783     if (state->mode == STM_I2C_DISABLED) {
784         state->mode = STM_I2C_MASTER;
785 
786         pdev->cfg = cfg;
787         pdev->board = board;
788         pdev->next = 2;
789         pdev->last = 1;
790         atomicBitsetInit(mXfersValid, I2C_MAX_QUEUE_DEPTH);
791 
792         pdev->scl = stmI2cGpioInit(board, &board->gpioScl);
793         pdev->sda = stmI2cGpioInit(board, &board->gpioSda);
794 
795         pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, true);
796 
797         stmI2cDisable(pdev);
798 
799         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, true);
800         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, false);
801 
802         stmI2cIrqEnable(pdev, I2C_CR2_ITEVTEN | I2C_CR2_ITERREN);
803         stmI2cSpeedSet(pdev, speed);
804         atomicWriteByte(&state->masterState, STM_I2C_MASTER_IDLE);
805 
806         NVIC_EnableIRQ(cfg->irqEr);
807         NVIC_EnableIRQ(cfg->irqEv);
808 
809         stmI2cEnable(pdev);
810         return 0;
811     } else {
812         return -EBUSY;
813     }
814 }
815 
i2cMasterRelease(uint32_t busId)816 int i2cMasterRelease(uint32_t busId)
817 {
818     if (busId >= ARRAY_SIZE(mStmI2cDevs))
819         return -EINVAL;
820 
821     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
822     struct I2cStmState *state = &pdev->state;
823     const struct StmI2cCfg *cfg = pdev->cfg;
824 
825     if (state->mode == STM_I2C_MASTER) {
826         if (atomicReadByte(&state->masterState) == STM_I2C_MASTER_IDLE) {
827             state->mode = STM_I2C_DISABLED;
828             stmI2cIrqEnable(pdev, I2C_CR2_ITERREN | I2C_CR2_ITEVTEN);
829             stmI2cDisable(pdev);
830             pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, false);
831 
832             gpioRelease(pdev->scl);
833             gpioRelease(pdev->sda);
834 
835             return 0;
836         } else {
837             return -EBUSY;
838         }
839     } else {
840         return -EINVAL;
841     }
842 }
843 
844 
i2cMasterTxRx(uint32_t busId,uint32_t addr,const void * txBuf,size_t txSize,void * rxBuf,size_t rxSize,I2cCallbackF callback,void * cookie)845 int i2cMasterTxRx(uint32_t busId, uint32_t addr,
846         const void *txBuf, size_t txSize, void *rxBuf, size_t rxSize,
847         I2cCallbackF callback, void *cookie)
848 {
849     uint32_t id;
850 
851     if (busId >= ARRAY_SIZE(mStmI2cDevs))
852         return -EINVAL;
853     else if (addr & 0x80)
854         return -ENXIO;
855 
856     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
857     struct I2cStmState *state = &pdev->state;
858 
859     if (state->mode != STM_I2C_MASTER)
860         return -EINVAL;
861 
862     struct StmI2cXfer *xfer = stmI2cGetXfer();
863 
864     if (xfer) {
865         xfer->busId = busId;
866         xfer->addr = addr;
867         xfer->txBuf = txBuf;
868         xfer->txSize = txSize;
869         xfer->rxBuf = rxBuf;
870         xfer->rxSize = rxSize;
871         xfer->callback = callback;
872         xfer->cookie = cookie;
873 
874         do {
875             id = atomicAdd32bits(&pdev->last, 1);
876         } while (!id);
877 
878         // after this point the transfer can be picked up by the transfer
879         // complete interrupt
880         atomicWrite32bits(&xfer->id, id);
881 
882         // only initiate transfer here if we are in IDLE. Otherwise the transfer
883         // completion interrupt will start the next transfer (not necessarily
884         // this one)
885         if (atomicCmpXchgByte((uint8_t *)&state->masterState,
886                 STM_I2C_MASTER_IDLE, STM_I2C_MASTER_START)) {
887             // it is possible for this transfer to already be complete by the
888             // time we get here. if so, transfer->id will have been set to 0.
889             if (atomicCmpXchg32bits(&xfer->id, id, 0)) {
890                 pdev->addr = xfer->addr;
891                 state->tx.cbuf = xfer->txBuf;
892                 state->tx.offset = 0;
893                 state->tx.size = xfer->txSize;
894                 state->tx.callback = xfer->callback;
895                 state->tx.cookie = xfer->cookie;
896                 state->rx.buf = xfer->rxBuf;
897                 state->rx.offset = 0;
898                 state->rx.size = xfer->rxSize;
899                 state->rx.callback = NULL;
900                 state->rx.cookie = NULL;
901                 state->tid = osGetCurrentTid();
902                 if (pdev->board->sleepDev >= 0)
903                     platRequestDevInSleepMode(pdev->board->sleepDev, 12);
904                 stmI2cPutXfer(xfer);
905                 stmI2cStartEnable(pdev);
906             }
907         }
908         return 0;
909     } else {
910         return -EBUSY;
911     }
912 }
913 
i2cSlaveRequest(uint32_t busId,uint32_t addr)914 int i2cSlaveRequest(uint32_t busId, uint32_t addr)
915 {
916     if (busId >= ARRAY_SIZE(mStmI2cDevs))
917         return -EINVAL;
918 
919     const struct StmI2cBoardCfg *board = boardStmI2cCfg(busId);
920     if (!board)
921         return -EINVAL;
922 
923     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
924     const struct StmI2cCfg *cfg = &mStmI2cCfgs[busId];
925 
926     if (pdev->state.mode == STM_I2C_DISABLED) {
927         pdev->state.mode = STM_I2C_SLAVE;
928 
929         pdev->addr = addr;
930         pdev->cfg = cfg;
931         pdev->board = board;
932 
933         pdev->scl = stmI2cGpioInit(board, &board->gpioScl);
934         pdev->sda = stmI2cGpioInit(board, &board->gpioSda);
935 
936         return 0;
937     } else {
938         return -EBUSY;
939     }
940 }
941 
i2cSlaveRelease(uint32_t busId)942 int i2cSlaveRelease(uint32_t busId)
943 {
944     if (busId >= ARRAY_SIZE(mStmI2cDevs))
945         return -EINVAL;
946 
947     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
948     const struct StmI2cCfg *cfg = pdev->cfg;
949 
950     if (pdev->state.mode == STM_I2C_SLAVE) {
951         pdev->state.mode = STM_I2C_DISABLED;
952         stmI2cIrqDisable(pdev, I2C_CR2_ITERREN | I2C_CR2_ITEVTEN);
953         stmI2cAckDisable(pdev);
954         stmI2cDisable(pdev);
955         pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, false);
956 
957         gpioRelease(pdev->scl);
958         gpioRelease(pdev->sda);
959 
960         return 0;
961     } else {
962         return -EBUSY;
963     }
964 }
965 
i2cSlaveEnableRx(uint32_t busId,void * rxBuf,size_t rxSize,I2cCallbackF callback,void * cookie)966 void i2cSlaveEnableRx(uint32_t busId, void *rxBuf, size_t rxSize,
967         I2cCallbackF callback, void *cookie)
968 {
969     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
970     const struct StmI2cCfg *cfg = pdev->cfg;
971     struct I2cStmState *state = &pdev->state;
972 
973     if (pdev->state.mode == STM_I2C_SLAVE) {
974         state->rx.buf = rxBuf;
975         state->rx.offset = 0;
976         state->rx.size = rxSize;
977         state->rx.callback = callback;
978         state->rx.cookie = cookie;
979         state->slaveState = STM_I2C_SLAVE_RX_ARMED;
980         state->tid = osGetCurrentTid();
981 
982         pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, true);
983         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, true);
984         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, false);
985 
986         NVIC_EnableIRQ(cfg->irqEr);
987         NVIC_EnableIRQ(cfg->irqEv);
988 
989         stmI2cEnable(pdev);
990         cfg->regs->OAR1 = I2C_OAR1_ADD7(pdev->addr);
991         stmI2cIrqEnable(pdev, I2C_CR2_ITERREN | I2C_CR2_ITEVTEN);
992         stmI2cAckEnable(pdev);
993     }
994 }
995 
i2cSlaveTx(uint32_t busId,const void * txBuf,uint8_t byte,size_t txSize,I2cCallbackF callback,void * cookie)996 static int i2cSlaveTx(uint32_t busId, const void *txBuf, uint8_t byte,
997         size_t txSize, I2cCallbackF callback, void *cookie)
998 {
999     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
1000     struct I2cStmState *state = &pdev->state;
1001 
1002     if (pdev->state.mode == STM_I2C_SLAVE) {
1003         if (state->slaveState == STM_I2C_SLAVE_RX)
1004             return -EBUSY;
1005 
1006         if (txBuf) {
1007             state->tx.cbuf = txBuf;
1008             state->tx.preamble = false;
1009         } else {
1010             state->tx.byte = byte;
1011             state->tx.preamble = true;
1012         }
1013         state->tx.offset = 0;
1014         state->tx.size = txSize;
1015         state->tx.callback = callback;
1016         state->tx.cookie = cookie;
1017 
1018         if (state->slaveState == STM_I2C_SLAVE_TX_ARMED) {
1019             state->slaveState = STM_I2C_SLAVE_TX;
1020             stmI2cSlaveTxNextByte(pdev);
1021             stmI2cIrqEnable(pdev, I2C_CR2_ITBUFEN);
1022         } else {
1023             state->slaveState = STM_I2C_SLAVE_TX;
1024         }
1025 
1026         return 0;
1027     } else {
1028         return -EBUSY;
1029     }
1030 }
1031 
i2cSlaveTxPreamble(uint32_t busId,uint8_t byte,I2cCallbackF callback,void * cookie)1032 int i2cSlaveTxPreamble(uint32_t busId, uint8_t byte, I2cCallbackF callback,
1033         void *cookie)
1034 {
1035     return i2cSlaveTx(busId, NULL, byte, 0, callback, cookie);
1036 }
1037 
i2cSlaveTxPacket(uint32_t busId,const void * txBuf,size_t txSize,I2cCallbackF callback,void * cookie)1038 int i2cSlaveTxPacket(uint32_t busId, const void *txBuf, size_t txSize,
1039         I2cCallbackF callback, void *cookie)
1040 {
1041     return i2cSlaveTx(busId, txBuf, 0, txSize, callback, cookie);
1042 }
1043