Home Learning Paths ECU Lab Assessments Interview Preparation Arena Pricing Log In Sign Up

Critical Section Implementation

Ccritical_sections.c
#include 
#include "cmsis_gcc.h"   /* __get_PRIMASK, __disable_irq, __enable_irq */

/* Pattern 1: Global interrupt disable/restore (Cortex-M) */
/* Save previous IRQ state (may already be disabled); disable; restore */
typedef uint32_t Critical_t;

static inline Critical_t Critical_Enter(void)
{
    Critical_t primask = __get_PRIMASK();   /* save current IRQ state */
    __disable_irq();                         /* disable all IRQs */
    __DSB();                                 /* data synchronisation barrier */
    return primask;
}

static inline void Critical_Exit(Critical_t saved)
{
    __DSB();
    if (saved == 0u) {
        __enable_irq();  /* only re-enable if IRQs were enabled before */
    }
}

/* Usage: */
volatile uint32_t g_shared_counter = 0u;

void increment_counter_safe(void)
{
    Critical_t state = Critical_Enter();
    g_shared_counter++;           /* atomic within critical section */
    Critical_Exit(state);
}

/* Pattern 2: BASEPRI masking (Cortex-M3/M4/M7) — mask only ISRs below threshold */
/* Allows high-priority safety ISRs to still fire during critical section */
static inline void Critical_EnterWithPriority(uint32_t priority)
{
    __set_BASEPRI(priority << (8u - __NVIC_PRIO_BITS));
    __DSB(); __ISB();
}
static inline void Critical_ExitPriority(void)
{
    __set_BASEPRI(0u);  /* re-enable all ISRs */
}

Cortex-M LDREX/STREX: Lock-Free Atomic Operations

Catomic_ops.c
#include 
#include "cmsis_gcc.h"

/* LDREX/STREX: hardware exclusive monitor — lock-free atomic RMW */
/* Used for: atomic counters, lock-free queues, flag setting */

/* Atomic increment using LDREX/STREX (no interrupt disable needed) */
uint32_t atomic_increment(volatile uint32_t *ptr)
{
    uint32_t old_val, new_val;
    uint32_t result;
    do {
        old_val = __LDREXW(ptr);        /* load exclusive: set monitor */
        new_val = old_val + 1u;
        result  = __STREXW(new_val, ptr); /* store exclusive: 0=success, 1=fail */
        /* If another agent (ISR, other core) modified *ptr: STREX fails, retry */
    } while (result != 0u);
    return old_val;  /* returns previous value */
}

/* Atomic compare-and-swap */
uint32_t atomic_cas(volatile uint32_t *ptr, uint32_t expected, uint32_t new_val)
{
    uint32_t old_val = __LDREXW(ptr);
    if (old_val != expected) {
        __CLREX();  /* clear exclusive monitor without store */
        return old_val;
    }
    if (__STREXW(new_val, ptr) != 0u) {
        return atomic_cas(ptr, expected, new_val);  /* retry on contention */
    }
    return old_val;
}

/* C11 _Atomic (available in GCC for Cortex-M): compiler-generated LDREX/STREX */
#include 
atomic_uint g_event_flags = ATOMIC_VAR_INIT(0u);
void set_event_atomic(uint32_t evt) { atomic_fetch_or(&g_event_flags, evt); }
uint32_t get_and_clear_events(void) { return atomic_exchange(&g_event_flags, 0u); }

Multi-word Data Consistency

Cmultiword_consistency.c
#include 

/* Problem: a 64-bit timestamp cannot be written atomically on 32-bit Cortex-M */
/* If ISR reads between the two 32-bit writes: reads half old, half new */

typedef struct {
    uint32_t lo;   /* lower 32 bits */
    uint32_t hi;   /* upper 32 bits */
} Timestamp64_t;

volatile Timestamp64_t g_timestamp;

/* Writer (task): update 64-bit timestamp */
void update_timestamp(uint64_t new_ts)
{
    Critical_t state = Critical_Enter();
    g_timestamp.lo = (uint32_t)(new_ts & 0xFFFFFFFFu);
    g_timestamp.hi = (uint32_t)(new_ts >> 32u);
    Critical_Exit(state);
}

/* Reader (ISR or task): read 64-bit timestamp consistently */
uint64_t read_timestamp(void)
{
    uint32_t lo, hi1, hi2;
    /* Double-read technique: detect roll-over during read */
    do {
        hi1 = g_timestamp.hi;   /* read hi first */
        lo  = g_timestamp.lo;   /* read lo */
        hi2 = g_timestamp.hi;   /* read hi again */
    } while (hi1 != hi2);       /* if hi changed: lo may be from new epoch; retry */

    return ((uint64_t)hi1 << 32u) | (uint64_t)lo;
}

Summary

Critical sections and atomic operations solve the same problem (concurrent access to shared data) at different granularities. Interrupt disable/restore is safe but blocks all ISRs — use it only for short, fast operations. BASEPRI masking (Cortex-M3/M4) is more surgical: it only masks ISRs below the priority threshold, allowing safety-critical ISRs to still fire. LDREX/STREX provides lock-free atomicity for single-word operations without disabling any interrupts — the hardware exclusive monitor detects concurrent modification and forces a retry. For multi-word data shared with ISRs, the double-read technique avoids a full critical section when only the reader needs to detect torn reads.

🔬 Deep Dive — Core Concepts Expanded

This section builds on the foundational concepts covered above with additional technical depth, edge cases, and configuration nuances that separate competent engineers from experts. When working on production ECU projects, the details covered here are the ones most commonly responsible for integration delays and late-phase defects.

Key principles to reinforce:

  • Configuration over coding: In AUTOSAR and automotive middleware environments, correctness is largely determined by ARXML configuration, not application code. A correctly implemented algorithm can produce wrong results due to a single misconfigured parameter.
  • Traceability as a first-class concern: Every configuration decision should be traceable to a requirement, safety goal, or architecture decision. Undocumented configuration choices are a common source of regression defects when ECUs are updated.
  • Cross-module dependencies: In tightly integrated automotive software stacks, changing one module's configuration often requires corresponding updates in dependent modules. Always perform a dependency impact analysis before submitting configuration changes.

🏭 How This Topic Appears in Production Projects

  • Project integration phase: The concepts covered in this lesson are most commonly encountered during ECU integration testing — when multiple software components from different teams are combined for the first time. Issues that were invisible in unit tests frequently surface at this stage.
  • Supplier/OEM interface: This is a topic that frequently appears in technical discussions between Tier-1 ECU suppliers and OEM system integrators. Engineers who can speak fluently about these details earn credibility and are often brought into critical design review meetings.
  • Automotive tool ecosystem: Vector CANoe/CANalyzer, dSPACE tools, and ETAS INCA are the standard tools used to validate and measure the correct behaviour of the systems described in this lesson. Familiarity with these tools alongside the conceptual knowledge dramatically accelerates debugging in real projects.

⚠️ Common Mistakes and How to Avoid Them

  1. Assuming default configuration is correct: Automotive software tools ship with default configurations that are designed to compile and link, not to meet project-specific requirements. Every configuration parameter needs to be consciously set. 'It compiled' is not the same as 'it is correctly configured'.
  2. Skipping documentation of configuration rationale: In a 3-year ECU project with team turnover, undocumented configuration choices become tribal knowledge that disappears when engineers leave. Document why a parameter is set to a specific value, not just what it is set to.
  3. Testing only the happy path: Automotive ECUs must behave correctly under fault conditions, voltage variations, and communication errors. Always test the error handling paths as rigorously as the nominal operation. Many production escapes originate in untested error branches.
  4. Version mismatches between teams: In a multi-team project, the BSW team, SWC team, and system integration team may use different versions of the same ARXML file. Version management of all ARXML files in a shared repository is mandatory, not optional.

📊 Industry Note

Engineers who master both the theoretical concepts and the practical toolchain skills covered in this course are among the most sought-after professionals in the automotive software industry. The combination of AUTOSAR standards knowledge, safety engineering understanding, and hands-on configuration experience commands premium salaries at OEMs and Tier-1 suppliers globally.

← PreviousInterrupt Handling & Priority SchemesNext →Timer/Counter Programming