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