+static inline uint32_t
+dma_chctrlb(uint8_t id, bool tx)
+{
+ uint32_t chctrlb = 0;
+
+ /* No complicated actions needed */
+ chctrlb |= SAMD21_DMAC_CHCTRLB_CMD_NOACT << SAMD21_DMAC_CHCTRLB_CMD;
+
+ /* Trigger after each byte transferred */
+ chctrlb |= SAMD21_DMAC_CHCTRLB_TRIGACT_BEAT << SAMD21_DMAC_CHCTRLB_TRIGACT;
+
+ /* Set the trigger source */
+ if (tx)
+ chctrlb |= SAMD21_DMAC_CHCTRLB_TRIGSRC_SERCOM_TX(id) << SAMD21_DMAC_CHCTRLB_TRIGSRC;
+ else
+ chctrlb |= SAMD21_DMAC_CHCTRLB_TRIGSRC_SERCOM_RX(id) << SAMD21_DMAC_CHCTRLB_TRIGSRC;
+
+ /* RX has priority over TX so that we don't drop incoming bytes */
+ if (tx)
+ chctrlb |= SAMD21_DMAC_CHCTRLB_LVL_LVL0 << SAMD21_DMAC_CHCTRLB_LVL;
+ else
+ chctrlb |= SAMD21_DMAC_CHCTRLB_LVL_LVL3 << SAMD21_DMAC_CHCTRLB_LVL;
+
+ /* No events needed */
+ chctrlb |= 0UL << SAMD21_DMAC_CHCTRLB_EVOE;
+ chctrlb |= 0UL << SAMD21_DMAC_CHCTRLB_EVIE;
+
+ /* And no actions either */
+ chctrlb |= SAMD21_DMAC_CHCTRLB_EVACT_NOACT << SAMD21_DMAC_CHCTRLB_EVACT;
+
+ return chctrlb;
+}
+
+static inline uint16_t
+dma_btctrl(bool step, bool tx)
+{
+ uint16_t btctrl = 0;
+
+ /* Always step by 1 */
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_STEPSIZE_X1 << SAMD21_DMAC_DESC_BTCTRL_STEPSIZE;
+
+ /* Step the source if transmit, otherwise step the dest */
+ if (tx)
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_STEPSEL_SRC << SAMD21_DMAC_DESC_BTCTRL_STEPSEL;
+ else
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_STEPSEL_DST << SAMD21_DMAC_DESC_BTCTRL_STEPSEL;
+
+ /* Set the increment if stepping */
+ if (tx) {
+ if (step)
+ btctrl |= 1UL << SAMD21_DMAC_DESC_BTCTRL_SRCINC;
+ else
+ btctrl |= 0UL << SAMD21_DMAC_DESC_BTCTRL_SRCINC;
+ btctrl |= 0UL << SAMD21_DMAC_DESC_BTCTRL_DSTINC;
+ } else {
+ btctrl |= 0UL << SAMD21_DMAC_DESC_BTCTRL_SRCINC;
+ if (step)
+ btctrl |= 1UL << SAMD21_DMAC_DESC_BTCTRL_DSTINC;
+ else
+ btctrl |= 0UL << SAMD21_DMAC_DESC_BTCTRL_DSTINC;
+ }
+
+ /* byte at a time please */
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_BEATSIZE_BYTE << SAMD21_DMAC_DESC_BTCTRL_BEATSIZE;
+
+ /*
+ * Watch for interrupts on RX -- we need to wait for the last byte to get received
+ * to know the SPI bus is idle
+ */
+ if (tx)
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_BLOCKACT_NOACT << SAMD21_DMAC_DESC_BTCTRL_BLOCKACT;
+ else
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_BLOCKACT_INT << SAMD21_DMAC_DESC_BTCTRL_BLOCKACT;
+
+ /* don't need any events */
+ btctrl |= SAMD21_DMAC_DESC_BTCTRL_EVOSEL_DISABLE << SAMD21_DMAC_DESC_BTCTRL_EVOSEL;
+
+ /* And make the descriptor valid */
+ btctrl |= 1UL << SAMD21_DMAC_DESC_BTCTRL_VALID;
+
+ return btctrl;
+}
+
+static void
+spi_run(const void *out, void *in, uint16_t len, uint16_t spi_index, bool step_out, bool step_in)