Home | History | Annotate | Download | only in stm32f4xx
      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 
    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 
    243 static inline void stmI2cPutXfer(struct StmI2cXfer *xfer)
    244 {
    245     if (xfer)
    246         atomicBitsetClearBit(mXfersValid, xfer - mXfers);
    247 }
    248 
    249 static inline void stmI2cAckEnable(struct StmI2cDev *pdev)
    250 {
    251     pdev->cfg->regs->CR1 |= I2C_CR1_ACK;
    252 }
    253 
    254 static inline void stmI2cAckDisable(struct StmI2cDev *pdev)
    255 {
    256     pdev->cfg->regs->CR1 &= ~I2C_CR1_ACK;
    257 }
    258 
    259 static inline void stmI2cDmaEnable(struct StmI2cDev *pdev)
    260 {
    261     pdev->cfg->regs->CR2 |= I2C_CR2_DMAEN;
    262 }
    263 
    264 static inline void stmI2cDmaDisable(struct StmI2cDev *pdev)
    265 {
    266     pdev->cfg->regs->CR2 &= ~I2C_CR2_DMAEN;
    267 }
    268 
    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 
    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 
    287 static inline void stmI2cIrqEnable(struct StmI2cDev *pdev,
    288         uint32_t mask)
    289 {
    290     pdev->cfg->regs->CR2 |= mask;
    291 }
    292 
    293 static inline void stmI2cIrqDisable(struct StmI2cDev *pdev,
    294         uint32_t mask)
    295 {
    296     pdev->cfg->regs->CR2 &= ~mask;
    297 }
    298 
    299 static inline void stmI2cEnable(struct StmI2cDev *pdev)
    300 {
    301     pdev->cfg->regs->CR1 |= I2C_CR1_PE;
    302 }
    303 
    304 static inline void stmI2cDisable(struct StmI2cDev *pdev)
    305 {
    306     pdev->cfg->regs->CR1 &= ~I2C_CR1_PE;
    307 }
    308 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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, err);
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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     int err = 0;
    652 
    653     if (masterState == STM_I2C_MASTER_TX_ADDR ||
    654             masterState == STM_I2C_MASTER_RX_ADDR) {
    655         err = -ENXIO;
    656     } else if (masterState == STM_I2C_MASTER_TX_DATA ||
    657             masterState == STM_I2C_MASTER_RX_DATA) {
    658         stmI2cMasterDmaCancel(pdev);
    659         err = -EIO;
    660     }
    661 
    662     if (err) {
    663         regs->SR1 &= ~I2C_SR1_AF;
    664         stmI2cStopEnable(pdev);
    665         stmI2cMasterTxRxDone(pdev, err);
    666     }
    667 }
    668 
    669 static void stmI2cMasterBusError(struct StmI2cDev *pdev)
    670 {
    671     struct StmI2c *regs = pdev->cfg->regs;
    672 
    673     stmI2cMasterDmaCancel(pdev);
    674     regs->SR1 &= ~I2C_SR1_BERR;
    675     stmI2cMasterTxRxDone(pdev, -EIO);
    676 }
    677 
    678 static void stmI2cMasterArbitrationLoss(struct StmI2cDev *pdev)
    679 {
    680     struct StmI2c *regs = pdev->cfg->regs;
    681 
    682     stmI2cMasterDmaCancel(pdev);
    683     regs->SR1 &= ~I2C_SR1_ARLO;
    684     stmI2cMasterTxRxDone(pdev, -EBUSY);
    685 }
    686 
    687 static void stmI2cMasterUnexpectedError(struct StmI2cDev *pdev)
    688 {
    689     struct StmI2c *regs = pdev->cfg->regs;
    690 
    691     osLog(LOG_ERROR, "Unexpected I2C ERR interrupt: SR1 = %04lX, SR2 = %04lX\n",
    692             regs->SR1, regs->SR2);
    693 
    694     stmI2cMasterDmaCancel(pdev);
    695     regs->SR1 = 0;
    696     stmI2cMasterTxRxDone(pdev, -EIO);
    697 }
    698 
    699 static void stmI2cIsrEvent(struct StmI2cDev *pdev)
    700 {
    701     struct StmI2c *regs = pdev->cfg->regs;
    702     uint16_t sr1 = regs->SR1;
    703 
    704     if (pdev->state.mode == STM_I2C_SLAVE) {
    705         if (sr1 & I2C_SR1_ADDR) {
    706             stmI2cSlaveAddrMatched(pdev);
    707         } else if (sr1 & I2C_SR1_RXNE) {
    708             stmI2cSlaveRxBufNotEmpty(pdev);
    709         } else if (sr1 & I2C_SR1_TXE) {
    710             stmI2cSlaveTxBufEmpty(pdev);
    711         } else if (sr1 & I2C_SR1_BTF) {
    712             if (regs->SR2 & I2C_SR2_TRA)
    713                 stmI2cSlaveTxBufEmpty(pdev);
    714            else
    715                 stmI2cSlaveRxBufNotEmpty(pdev);
    716         } else if (sr1 & I2C_SR1_STOPF) {
    717             stmI2cSlaveStopRxed(pdev);
    718         }
    719         /* TODO: other flags */
    720     } else if (pdev->state.mode == STM_I2C_MASTER) {
    721         if (sr1 & I2C_SR1_SB)
    722             stmI2cMasterSentStart(pdev);
    723         else if (sr1 & I2C_SR1_ADDR)
    724             stmI2cMasterSentAddr(pdev);
    725     }
    726 }
    727 
    728 static void stmI2cIsrError(struct StmI2cDev *pdev)
    729 {
    730     struct StmI2c *regs = pdev->cfg->regs;
    731     uint16_t sr1 = regs->SR1;
    732 
    733     if (pdev->state.mode == STM_I2C_SLAVE) {
    734         if (sr1 & I2C_SR1_AF)
    735             stmI2cSlaveNakRxed(pdev);
    736         /* TODO: other flags */
    737     } else if (pdev->state.mode == STM_I2C_MASTER) {
    738         if (sr1 & I2C_SR1_AF)
    739             stmI2cMasterNakRxed(pdev);
    740         else if (sr1 & I2C_SR1_BERR)
    741             stmI2cMasterBusError(pdev);
    742         else if (sr1 & I2C_SR1_ARLO)
    743             stmI2cMasterArbitrationLoss(pdev);
    744         else
    745             stmI2cMasterUnexpectedError(pdev);
    746     }
    747 }
    748 
    749 #define DECLARE_IRQ_HANDLERS(_n)                \
    750     extern void I2C##_n##_EV_IRQHandler();      \
    751     extern void I2C##_n##_ER_IRQHandler();      \
    752                                                 \
    753     extern void I2C##_n##_EV_IRQHandler()       \
    754     {                                           \
    755         stmI2cIsrEvent(&mStmI2cDevs[_n - 1]);  \
    756     }                                           \
    757                                                 \
    758     extern void I2C##_n##_ER_IRQHandler()       \
    759     {                                           \
    760         stmI2cIsrError(&mStmI2cDevs[_n - 1]);  \
    761     }
    762 
    763 DECLARE_IRQ_HANDLERS(1);
    764 DECLARE_IRQ_HANDLERS(3);
    765 
    766 static inline struct Gpio* stmI2cGpioInit(const struct StmI2cBoardCfg *board, const struct StmI2cGpioCfg *cfg)
    767 {
    768     struct Gpio* gpio = gpioRequest(cfg->gpioNum);
    769     gpioConfigAlt(gpio, board->gpioSpeed, board->gpioPull, GPIO_OUT_OPEN_DRAIN,
    770             cfg->func);
    771 
    772     return gpio;
    773 }
    774 
    775 int i2cMasterRequest(uint32_t busId, uint32_t speed)
    776 {
    777     if (busId >= ARRAY_SIZE(mStmI2cDevs))
    778         return -EINVAL;
    779 
    780     const struct StmI2cBoardCfg *board = boardStmI2cCfg(busId);
    781     if (!board)
    782         return -EINVAL;
    783 
    784     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
    785     struct I2cStmState *state = &pdev->state;
    786     const struct StmI2cCfg *cfg = &mStmI2cCfgs[busId];
    787 
    788     if (state->mode == STM_I2C_DISABLED) {
    789         state->mode = STM_I2C_MASTER;
    790 
    791         pdev->cfg = cfg;
    792         pdev->board = board;
    793         pdev->next = 2;
    794         pdev->last = 1;
    795         atomicBitsetInit(mXfersValid, I2C_MAX_QUEUE_DEPTH);
    796 
    797         pdev->scl = stmI2cGpioInit(board, &board->gpioScl);
    798         pdev->sda = stmI2cGpioInit(board, &board->gpioSda);
    799 
    800         pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, true);
    801 
    802         stmI2cDisable(pdev);
    803 
    804         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, true);
    805         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, false);
    806 
    807         stmI2cIrqEnable(pdev, I2C_CR2_ITEVTEN | I2C_CR2_ITERREN);
    808         stmI2cSpeedSet(pdev, speed);
    809         atomicWriteByte(&state->masterState, STM_I2C_MASTER_IDLE);
    810 
    811         NVIC_EnableIRQ(cfg->irqEr);
    812         NVIC_EnableIRQ(cfg->irqEv);
    813 
    814         stmI2cEnable(pdev);
    815         return 0;
    816     } else {
    817         return -EBUSY;
    818     }
    819 }
    820 
    821 int i2cMasterRelease(uint32_t busId)
    822 {
    823     if (busId >= ARRAY_SIZE(mStmI2cDevs))
    824         return -EINVAL;
    825 
    826     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
    827     struct I2cStmState *state = &pdev->state;
    828     const struct StmI2cCfg *cfg = pdev->cfg;
    829 
    830     if (state->mode == STM_I2C_MASTER) {
    831         if (atomicReadByte(&state->masterState) == STM_I2C_MASTER_IDLE) {
    832             state->mode = STM_I2C_DISABLED;
    833             stmI2cIrqEnable(pdev, I2C_CR2_ITERREN | I2C_CR2_ITEVTEN);
    834             stmI2cDisable(pdev);
    835             pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, false);
    836 
    837             gpioRelease(pdev->scl);
    838             gpioRelease(pdev->sda);
    839 
    840             return 0;
    841         } else {
    842             return -EBUSY;
    843         }
    844     } else {
    845         return -EINVAL;
    846     }
    847 }
    848 
    849 
    850 int i2cMasterTxRx(uint32_t busId, uint32_t addr,
    851         const void *txBuf, size_t txSize, void *rxBuf, size_t rxSize,
    852         I2cCallbackF callback, void *cookie)
    853 {
    854     uint32_t id;
    855 
    856     if (busId >= ARRAY_SIZE(mStmI2cDevs))
    857         return -EINVAL;
    858     else if (addr & 0x80)
    859         return -ENXIO;
    860 
    861     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
    862     struct I2cStmState *state = &pdev->state;
    863 
    864     if (state->mode != STM_I2C_MASTER)
    865         return -EINVAL;
    866 
    867     struct StmI2cXfer *xfer = stmI2cGetXfer();
    868 
    869     if (xfer) {
    870         xfer->busId = busId;
    871         xfer->addr = addr;
    872         xfer->txBuf = txBuf;
    873         xfer->txSize = txSize;
    874         xfer->rxBuf = rxBuf;
    875         xfer->rxSize = rxSize;
    876         xfer->callback = callback;
    877         xfer->cookie = cookie;
    878 
    879         do {
    880             id = atomicAdd32bits(&pdev->last, 1);
    881         } while (!id);
    882 
    883         // after this point the transfer can be picked up by the transfer
    884         // complete interrupt
    885         atomicWrite32bits(&xfer->id, id);
    886 
    887         // only initiate transfer here if we are in IDLE. Otherwise the transfer
    888         // completion interrupt will start the next transfer (not necessarily
    889         // this one)
    890         if (atomicCmpXchgByte((uint8_t *)&state->masterState,
    891                 STM_I2C_MASTER_IDLE, STM_I2C_MASTER_START)) {
    892             // it is possible for this transfer to already be complete by the
    893             // time we get here. if so, transfer->id will have been set to 0.
    894             if (atomicCmpXchg32bits(&xfer->id, id, 0)) {
    895                 pdev->addr = xfer->addr;
    896                 state->tx.cbuf = xfer->txBuf;
    897                 state->tx.offset = 0;
    898                 state->tx.size = xfer->txSize;
    899                 state->tx.callback = xfer->callback;
    900                 state->tx.cookie = xfer->cookie;
    901                 state->rx.buf = xfer->rxBuf;
    902                 state->rx.offset = 0;
    903                 state->rx.size = xfer->rxSize;
    904                 state->rx.callback = NULL;
    905                 state->rx.cookie = NULL;
    906                 state->tid = osGetCurrentTid();
    907                 if (pdev->board->sleepDev >= 0)
    908                     platRequestDevInSleepMode(pdev->board->sleepDev, 12);
    909                 stmI2cPutXfer(xfer);
    910                 stmI2cStartEnable(pdev);
    911             }
    912         }
    913         return 0;
    914     } else {
    915         return -EBUSY;
    916     }
    917 }
    918 
    919 int i2cSlaveRequest(uint32_t busId, uint32_t addr)
    920 {
    921     if (busId >= ARRAY_SIZE(mStmI2cDevs))
    922         return -EINVAL;
    923 
    924     const struct StmI2cBoardCfg *board = boardStmI2cCfg(busId);
    925     if (!board)
    926         return -EINVAL;
    927 
    928     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
    929     const struct StmI2cCfg *cfg = &mStmI2cCfgs[busId];
    930 
    931     if (pdev->state.mode == STM_I2C_DISABLED) {
    932         pdev->state.mode = STM_I2C_SLAVE;
    933 
    934         pdev->addr = addr;
    935         pdev->cfg = cfg;
    936         pdev->board = board;
    937 
    938         pdev->scl = stmI2cGpioInit(board, &board->gpioScl);
    939         pdev->sda = stmI2cGpioInit(board, &board->gpioSda);
    940 
    941         return 0;
    942     } else {
    943         return -EBUSY;
    944     }
    945 }
    946 
    947 int i2cSlaveRelease(uint32_t busId)
    948 {
    949     if (busId >= ARRAY_SIZE(mStmI2cDevs))
    950         return -EINVAL;
    951 
    952     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
    953     const struct StmI2cCfg *cfg = pdev->cfg;
    954 
    955     if (pdev->state.mode == STM_I2C_SLAVE) {
    956         pdev->state.mode = STM_I2C_DISABLED;
    957         stmI2cIrqDisable(pdev, I2C_CR2_ITERREN | I2C_CR2_ITEVTEN);
    958         stmI2cAckDisable(pdev);
    959         stmI2cDisable(pdev);
    960         pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, false);
    961 
    962         gpioRelease(pdev->scl);
    963         gpioRelease(pdev->sda);
    964 
    965         return 0;
    966     } else {
    967         return -EBUSY;
    968     }
    969 }
    970 
    971 void i2cSlaveEnableRx(uint32_t busId, void *rxBuf, size_t rxSize,
    972         I2cCallbackF callback, void *cookie)
    973 {
    974     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
    975     const struct StmI2cCfg *cfg = pdev->cfg;
    976     struct I2cStmState *state = &pdev->state;
    977 
    978     if (pdev->state.mode == STM_I2C_SLAVE) {
    979         state->rx.buf = rxBuf;
    980         state->rx.offset = 0;
    981         state->rx.size = rxSize;
    982         state->rx.callback = callback;
    983         state->rx.cookie = cookie;
    984         state->slaveState = STM_I2C_SLAVE_RX_ARMED;
    985         state->tid = osGetCurrentTid();
    986 
    987         pwrUnitClock(PERIPH_BUS_APB1, cfg->clock, true);
    988         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, true);
    989         pwrUnitReset(PERIPH_BUS_APB1, cfg->clock, false);
    990 
    991         NVIC_EnableIRQ(cfg->irqEr);
    992         NVIC_EnableIRQ(cfg->irqEv);
    993 
    994         stmI2cEnable(pdev);
    995         cfg->regs->OAR1 = I2C_OAR1_ADD7(pdev->addr);
    996         stmI2cIrqEnable(pdev, I2C_CR2_ITERREN | I2C_CR2_ITEVTEN);
    997         stmI2cAckEnable(pdev);
    998     }
    999 }
   1000 
   1001 static int i2cSlaveTx(uint32_t busId, const void *txBuf, uint8_t byte,
   1002         size_t txSize, I2cCallbackF callback, void *cookie)
   1003 {
   1004     struct StmI2cDev *pdev = &mStmI2cDevs[busId];
   1005     struct I2cStmState *state = &pdev->state;
   1006 
   1007     if (pdev->state.mode == STM_I2C_SLAVE) {
   1008         if (state->slaveState == STM_I2C_SLAVE_RX)
   1009             return -EBUSY;
   1010 
   1011         if (txBuf) {
   1012             state->tx.cbuf = txBuf;
   1013             state->tx.preamble = false;
   1014         } else {
   1015             state->tx.byte = byte;
   1016             state->tx.preamble = true;
   1017         }
   1018         state->tx.offset = 0;
   1019         state->tx.size = txSize;
   1020         state->tx.callback = callback;
   1021         state->tx.cookie = cookie;
   1022 
   1023         if (state->slaveState == STM_I2C_SLAVE_TX_ARMED) {
   1024             state->slaveState = STM_I2C_SLAVE_TX;
   1025             stmI2cSlaveTxNextByte(pdev);
   1026             stmI2cIrqEnable(pdev, I2C_CR2_ITBUFEN);
   1027         } else {
   1028             state->slaveState = STM_I2C_SLAVE_TX;
   1029         }
   1030 
   1031         return 0;
   1032     } else {
   1033         return -EBUSY;
   1034     }
   1035 }
   1036 
   1037 int i2cSlaveTxPreamble(uint32_t busId, uint8_t byte, I2cCallbackF callback,
   1038         void *cookie)
   1039 {
   1040     return i2cSlaveTx(busId, NULL, byte, 0, callback, cookie);
   1041 }
   1042 
   1043 int i2cSlaveTxPacket(uint32_t busId, const void *txBuf, size_t txSize,
   1044         I2cCallbackF callback, void *cookie)
   1045 {
   1046     return i2cSlaveTx(busId, txBuf, 0, txSize, callback, cookie);
   1047 }
   1048