Chapter 8: Direct Memory Access (DMA) & DMAMUX Driver Development

📚 CMPE2250: Lesson — Direct Memory Access (DMA) & DMAMUX Driver Development

Course Material & Lab Assignment Guide
Target Architecture: STM32G0 Series (ARM Cortex-M0+)


1️⃣ Objectives & Overview

In high-throughput embedded systems, servicing communication lines (such as UART, SPI, or I2C) byte-by-byte using standard interrupt service routines (ISRs) imposes significant CPU overhead. Direct Memory Access (DMA) offloads bulk data transfers between peripherals and memory (or memory to memory) without CPU intervention.

In this activity, you will:

  1. Understand the clock distribution requirements (RCC) for bus masters.
  2. Configure the DMAMUX (DMA Request Multiplexer) crossbar router.
  3. Design and implement a reusable register-level DMA driver library (dma.h and dma.c).
  4. Validate your driver using peripheral-to-memory data transfers paired with UART IDLE line detection.

2️⃣ Hardware Architecture & Bus Interconnect

2.1 The DMA Controller and DMAMUX

In the STM32G0 family, DMA channels are decoupled from fixed peripheral lines through the DMAMUX:

+------------------+       +-------------------+       +---------------+       +----------------+
| Peripherals      |       |      DMAMUX       |       | DMA1 / DMA2   |       | Bus Matrix     |
| (USART, SPI, etc)| ----> |  Channel Routing  | ----> | Channels 1..N | ----> | SRAM &         |
| Hardware Triggers|       | (Table 55 RM0444) |       | (CCR, CNDTR)  |       | Periph Spaces  |
+------------------+       +-------------------+       +---------------+       +----------------+
  • DMAMUX Router: Directs hardware transfer trigger requests from any peripheral trigger output to any available DMA channel.
  • DMA Controller: Orchestrates the actual bus mastering, auto-incrementing memory pointers, counting transfers down to 0, and triggering interrupts upon completion or errors.

3️⃣ Peripheral Clock Setup (RCC Prerequisites)

Important: By architectural convention, the DMA library functions operate only on the channel registers (DMA_Channel_TypeDef) and expect the system clocks to be enabled prior to initialization.

Before any DMA channel or DMAMUX channel register can retain values, its peripheral clock must be activated via the RCC (Reset and Clock Control) registers.

3.1 Enabling DMA and DMAMUX Clocks in main()

Refer to the RCC AHB Peripheral Clock Enable Register (RCC->AHBENR):

  1. DMA1 / DMA2 Clock Enable: Find and set the corresponding enable bits (RCC_AHBENR_DMA1EN, and RCC_AHBENR_DMA2EN if present).
  2. DMAMUX Clock Enable: Set the DMAMUX enable bit (RCC_AHBENR_DMAMUX1EN).
  3. Synchronization Delay: Perform a dummy read or add a brief delay immediately after setting peripheral clock bits to allow the clock distribution to settle before accessing peripheral registers.

4️⃣ DMAMUX Routing Configuration

The DMAMUX assigns a peripheral hardware trigger ID to a given DMA channel.

Each DMAMUX channel configuration register (DMAMUX1_Channelx->CCR) corresponds directly to a DMA channel:

  • DMAMUX1_Channel0 routes requests to DMA1 Channel 1.
  • DMAMUX1_Channel1 routes requests to DMA1 Channel 2, and so on.

4.1 Configuration Procedure

  1. Locate the Request ID in your provided header: dmamux.h (mapped from RM0444 Table 55).
    • Example: For USART2 RX, the ID is DMAMUX_REQ_USART2_RX (value 52).
  2. Write the ID into the DMAREQ_ID[6:0] bitfield in DMAMUX1_Channelx->CCR: \(\text{DMAMUX1\_Channelx->CCR} = \text{Request\_ID} \ \& \ \text{DMAMUX\_CxCR\_DMAREQ\_ID}\)
  3. Verify that synchronization and trigger generator modes remain disabled (default 0) for basic peripheral-driven requests.

5️⃣ DMA Register Model

Each DMA channel is controlled through four core 32-bit registers encapsulated in CMSIS by DMA_Channel_TypeDef:

Register Name Purpose Configuration Condition
CCR Channel Configuration Register Controls enable, directions, increment modes, circular mode, priorities, and interrupt enables. Most bits writeable only when EN = 0.
CNDTR Number of Data to Transfer Holds the transfer count ($0$ to $65535$). Decrements after each transfer. Must only be modified when EN = 0.
CPAR Peripheral Address Register Base address of the peripheral register (e.g., &(USART2->RDR)). Writeable when EN = 0.
CMAR Memory Address Register Target/source address of the data buffer in SRAM. Writeable when EN = 0.

6️⃣ Driver Library Design Guide

Your assignment is to implement dma.c according to the definitions in dma.h.

6.1 Header Definitions (dma.h)

Your header exposes the transfer mode enum, the interrupt enable bitmasks, and function prototypes:

typedef enum DMAChannelMode__ {
    DMA_MemToMem,
    DMA_PerToMem,
    DMA_MemToPer,
    DMA_PerToPer,
} DMAChannelMode;

typedef enum DMA_IE__ {
    DMA_EIE  = (1 << DMA_CCR_TEIE_Pos),   // Transfer Error Interrupt Enable
    DMA_HTIE = (1 << DMA_CCR_HTIE_Pos),   // Half Transfer Interrupt Enable
    DMA_TCIE = (1 << DMA_CCR_TCIE_Pos),   // Transfer Complete Interrupt Enable
} DMA_IE;

6.2 Implementation Steps (dma.c)

Step 1: Channel Initialization (DMA_Init)

  • Signature:
    void DMA_Init(DMA_Channel_TypeDef *pChannel, DMAChannelMode mode, uint8_t* memAddr, uint32_t perAddr);
    
  • Requirements & Logic:
    1. Enforce Safe State: Clear the DMA_CCR_EN bit in pChannel->CCR. A channel cannot be modified while enabled.
    2. Set Addresses: Load memAddr into CMAR and perAddr into CPAR (use your helper functions).
    3. Mode Resolution (switch(mode)):
      • DMA_MemToMem:
        • Enable Memory-to-Memory mode (DMA_CCR_MEM2MEM).
        • Clear Direction (DMA_CCR_DIR = 0).
        • Enable Memory Increment (DMA_CCR_MINC) to advance the destination buffer.
        • Enable Peripheral Increment (DMA_CCR_PINC) to advance the source buffer.
      • DMA_PerToMem (e.g., UART Reception):
        • Disable Memory-to-Memory (MEM2MEM = 0).
        • Clear Direction (DIR = 0 $\rightarrow$ read from peripheral into memory).
        • Enable Memory Increment (MINC = 1).
        • Disable Peripheral Increment (PINC = 0), since the peripheral register is a fixed single address.
      • DMA_MemToPer (e.g., UART Transmission):
        • Disable Memory-to-Memory (MEM2MEM = 0).
        • Set Direction (DIR = 1 $\rightarrow$ read from memory into peripheral).
        • Enable Memory Increment (MINC = 1).
        • Disable Peripheral Increment (PINC = 0).
      • DMA_PerToPer:
        • Disable Memory-to-Memory (MEM2MEM = 0).
        • Clear Direction (DIR = 0).
        • Disable both pointer increments (MINC = 0, PINC = 0).
    4. Baseline Interrupt Flags: Enable Transfer Complete (DMA_CCR_TCIE) and Transfer Error (DMA_CCR_TEIE) in CCR.

Step 2: Address Setters (DMA_SetMemoryAddress, DMA_SetPerAddress)

  • Write helper functions to encapsulate hardware register layout:
    • Cast the pointer uint8_t* memAddr to uint32_t and assign it to pChannel->CMAR.
    • Assign the uint32_t perAddr to pChannel->CPAR.

Step 3: Transfer Control (DMA_SetEnable, DMA_StartTransfer)

  • DMA_SetEnable(DMA_Channel_TypeDef *pChannel, uint8_t en):
    • Set or clear DMA_CCR_EN using standard bitwise operators (|= or &= ~).
  • DMA_StartTransfer(DMA_Channel_TypeDef *pChannel, uint16_t size):
    • Any modification to CNDTR while EN = 1 is ignored by the hardware and risks undefined behavior.
    • Sequence:
      1. Disable channel via DMA_SetEnable(pChannel, 0).
      2. Write size into pChannel->CNDTR.
      3. Re-enable channel via DMA_SetEnable(pChannel, 1).

Step 4: Tracking Received Bytes (DMA_GetRcvdCount)

  • Mathematical Basis: CNDTR is initialized to the total buffer capacity and decrements by $1$ after every successfully transferred byte. \(\text{Bytes Received} = \text{Total Buffer Size} - \text{CNDTR}\)
  • Implementation Note: Ensure the calculation uses the full buffer allocation size passed into the function.

Step 5: NVIC & Channel Interrupt Configuration (DMA_InterruptEnable)

  • Configure the channel’s interrupt mask:
    1. Apply the bitmask flag (DMA_IE) directly to pChannel->CCR.
    2. Enable the corresponding channel interrupt vector in the Cortex-M NVIC using NVIC_EnableIRQ(irqn).

7️⃣ Laboratory Exercise: Peripheral-to-Memory UART with IDLE Line Detection

To verify your library, configure USART reception where packet sizes are variable and unknown in advance.

7.1 The Problem with Variable-Length Packets

If you configure a DMA channel to receive 64 bytes, but the sender only transmits a 12-byte command, the DMA will wait indefinitely for the remaining 52 bytes without firing the Transfer Complete (TC) interrupt.

7.2 The Solution: UART IDLE Line Detection

The STM32 UART hardware can detect when the receive line becomes idle (no RX traffic for more than one frame duration).

UART RX Line:  ---[ Byte 1 ][ Byte 2 ][ Byte 3 ]---------------------> (IDLE detected!)
                                                 ^
                                                 |-- Fires USART_ISR_IDLE Interrupt!

7.3 Integration Steps for Students

  1. Clock Setup:
    • Enable clocks for GPIOA, USART2, DMA1, and DMAMUX1 in RCC.
  2. DMAMUX Routing:
    • Connect DMAMUX_REQ_USART2_RX to DMAMUX1_Channel0 (which feeds DMA1_Channel1).
  3. DMA Library Call:
    • Call DMA_Init() targeting DMA1_Channel1, setting mode to DMA_PerToMem, pointing to your global RX buffer, and passing the address of USART2->RDR.
    • Enable the DMA channel for a maximum expected buffer size (e.g., 64 bytes).
  4. USART Configuration:
    • Enable USART DMA Reception by setting the DMAR bit in USART2->CR3.
    • Enable the IDLE Line Interrupt by setting the IDLEIE bit in USART2->CR1.
    • Enable USART2_IRQn in the NVIC.
  5. Handling the Interrupt:
    • In USART2_IRQHandler():
      1. Check if the IDLE flag in USART2->ISR is asserted.
      2. Clear the flag by writing USART_ICR_IDLECF to USART2->ICR.
      3. Call your driver function: \(\text{count} = \text{DMA\_GetRcvdCount(DMA1\_Channel1, BUFFER\_SIZE)}\)
      4. Process the received payload up to count.
      5. Reset the transfer for the next packet by calling DMA_StartTransfer(DMA1_Channel1, BUFFER_SIZE).

8️⃣ Verification & Debugging Checklist

Before requesting sign-off or submitting your code, verify these common pitfalls in the IDE debugger:

  • RCC Active: Inspect RCC->AHBENR in the Peripherals View. Are the DMA1EN and DMAMUX1EN bits set to 1?
  • Safe Configuration: Place a breakpoint inside DMA_Init(). Confirm that CCR has EN = 0 before any other bitfield changes.
  • Address Pointers: Check CMAR and CPAR. Does CPAR match the memory address of the peripheral data register (e.g., 0x40004424 for USART2 RDR)?
  • DMAMUX Request Mapping: Check DMAMUX1_Channel0->CCR. Does the lower byte match the ID defined in dmamux.h?
  • Pointer Increment Flags: In Memory-to-Memory transfers, verify that both MINC and PINC are active. In UART-to-Memory transfers, verify that only MINC is active.
  • Interrupt Acknowledgement: When writing an ISR, verify that the corresponding interrupt status flag in DMA1->ISR (e.g., CTCIFx) or USARTx->ICR is cleared to prevent infinite interrupt loops.