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