git:20260225.a4aeb64 to git:20260226.186740f

167 added, 69 removed. Audit C to C.

- # Memory Mgmt Patterns
-
- A comprehensive pattern library and knowledge base for memory-management.
+ # memory-mgmt-patterns
## Knowledge Base
- ### Core Concepts
- - **Fundamentals**: The foundational principles that govern memory-management
- - **Terminology**: Standard vocabulary and definitions used in the domain
- - **Standards**: Industry standards and specifications that apply
- - **Tools**: Common tools and frameworks used for memory-management
+ Embedded memory management patterns for deterministic, fragmentation-free firmware.
- ### Architecture Principles
- - Separation of concerns within memory-management implementations
- - Modularity and reusability of components
- - Scalability considerations for growing systems
- - Integration patterns with adjacent domains
+ ---
- ### Quality Attributes
- - **Correctness**: Implementations must meet functional requirements
- - **Maintainability**: Code and artifacts should be easy to understand and modify
- - **Performance**: Implementations should meet non-functional requirements
- - **Security**: Sensitive data and operations must be properly protected
+ ## Pattern 1: Static FreeRTOS Objects
- ## Patterns
+ Avoid dynamic allocation for RTOS objects. All objects pre-allocated at compile time.
- ### Pattern 1: Structured Approach
- - Start with requirements analysis
- - Design before implementing
- - Validate against acceptance criteria
- - Document decisions and rationale
+ ```c
+ /* Static task */
+ static StackType_t s_sensor_stack[256];
+ static StaticTask_t s_sensor_tcb;
+ static TaskHandle_t s_sensor_handle;
- ### Pattern 2: Iterative Refinement
- - Begin with a minimal viable implementation
- - Gather feedback early and often
- - Refine based on real-world usage
- - Continuously improve based on metrics
+ /* Static queue: 8 messages of 16 bytes each */
+ static uint8_t s_queue_storage[8 * 16];
+ static StaticQueue_t s_queue_struct;
+ static QueueHandle_t s_queue;
- ### Pattern 3: Convention Over Configuration
- - Follow established conventions where they exist
- - Configure only what needs to deviate from defaults
- - Document any non-standard choices
- - Prefer explicit over implicit behavior
+ /* Static semaphore */
+ static StaticSemaphore_t s_sem_struct;
+ static SemaphoreHandle_t s_sem;
- ### Pattern 4: Defense in Depth
- - Validate at multiple levels
- - Handle errors gracefully at each layer
- - Provide meaningful feedback for failures
- - Log important events for debugging
+ void rtos_objects_create(void)
+ {
+ s_sensor_handle = xTaskCreateStatic(
+ sensor_task, "sensor",
+ 256U, NULL, TASK_PRIO_SENSOR,
+ s_sensor_stack, &s_sensor_tcb);
+ configASSERT(s_sensor_handle != NULL);
- ## Anti-Patterns
+ s_queue = xQueueCreateStatic(8, 16, s_queue_storage, &s_queue_struct);
+ configASSERT(s_queue != NULL);
- ### Anti-Pattern 1: Premature Optimization
- - Optimizing before understanding the actual bottleneck
- - Adding complexity without measured need
- - Sacrificing readability for marginal performance gains
+ s_sem = xSemaphoreCreateBinaryStatic(&s_sem_struct);
+ configASSERT(s_sem != NULL);
+ }
+ ```
- ### Anti-Pattern 2: Copy-Paste Without Understanding
- - Duplicating code without understanding its purpose
- - Propagating bugs through mechanical copying
- - Missing opportunities for abstraction
+ Required in `FreeRTOSConfig.h`: `configSUPPORT_STATIC_ALLOCATION 1`.
- ### Anti-Pattern 3: Ignoring Standards
- - Deviating from conventions without clear justification
- - Creating inconsistency across the codebase
- - Making onboarding harder for new contributors
+ ---
- ### Anti-Pattern 4: Over-Engineering
- - Building for hypothetical future requirements
- - Adding abstraction layers without clear benefit
- - Creating complex solutions for simple problems
+ ## Pattern 2: Memory Pool for Variable-Frequency Messages
- ## References
+ When messages arrive at variable rate, a pool prevents heap fragmentation:
- ### Documentation
- - Official documentation for related tools and frameworks
- - Industry standards and specifications
- - Community best practices and guides
+ ```c
+ /* Message pool: 32 messages, 128 bytes each */
+ typedef struct {
+ uint8_t data[120];
+ uint8_t len;
+ uint8_t type;
+ uint16_t seq;
+ } msg_t;
- ### Learning Resources
- - Tutorials and walkthroughs for beginners
- - Advanced guides for experienced practitioners
- - Case studies and real-world examples
+ #define MSG_POOL_SIZE 32U
+ static msg_t s_msg_pool[MSG_POOL_SIZE];
+ static uint32_t s_pool_used_mask = 0U; /* Bitmask: bit N = msg N is in use */
- ### Tools
- - Development tools for memory-management
- - Testing and validation tools
- - Monitoring and observability tools
+ msg_t *msg_alloc(void)
+ {
+ taskENTER_CRITICAL();
+ for (uint32_t i = 0; i < MSG_POOL_SIZE; i++) {
+ if (!(s_pool_used_mask & (1U << i))) {
+ s_pool_used_mask |= (1U << i);
+ taskEXIT_CRITICAL();
+ return &s_msg_pool[i];
+ }
+ }
+ taskEXIT_CRITICAL();
+ return NULL; /* Pool exhausted: caller must handle */
+ }
+
+ void msg_free(msg_t *m)
+ {
+ uint32_t idx = (uint32_t)(m - s_msg_pool);
+ configASSERT(idx < MSG_POOL_SIZE);
+ taskENTER_CRITICAL();
+ s_pool_used_mask &= ~(1U << idx);
+ taskEXIT_CRITICAL();
+ }
+ ```
+
+ ---
+
+ ## Pattern 3: Heap Statistics Monitoring
+
+ ```c
+ /* Log heap stats periodically for detecting slow leak */
+ void heap_monitor_task(void *param)
+ {
+ (void)param;
+ HeapStats_t stats;
+
+ for (;;) {
+ vPortGetHeapStats(&stats);
+
+ char buf[128];
+ snprintf(buf, sizeof(buf),
+ "HEAP free=%lu min=%lu blocks=%lu",
+ (unsigned long)stats.xAvailableHeapSpaceInBytes,
+ (unsigned long)stats.xMinimumEverFreeBytesRemaining,
+ (unsigned long)stats.xNumberOfFreeBlocks);
+ log_info(buf);
+
+ /* Alert if heap falls below 2KB */
+ if (stats.xAvailableHeapSpaceInBytes < 2048U) {
+ log_error("HEAP LOW");
+ }
+
+ vTaskDelay(pdMS_TO_TICKS(30000)); /* Every 30 seconds */
+ }
+ }
+ ```
+
+ `xMinimumEverFreeBytesRemaining` is the all-time low-water mark โ€” use it for sizing.
+
+ ---
+
+ ## Pattern 4: Stack High-Water Mark Audit
+
+ ```c
+ /* Call from a debug task or startup once system is stable */
+ void task_stack_audit(void)
+ {
+ typedef struct {
+ const char *name;
+ TaskHandle_t handle;
+ uint32_t min_expected_words;
+ } task_entry_t;
+
+ const task_entry_t tasks[] = {
+ { "sensor", s_sensor_handle, 32U },
+ { "comm", s_comm_handle, 64U },
+ { "display", s_display_handle, 48U },
+ };
+
+ for (uint32_t i = 0; i < sizeof(tasks)/sizeof(tasks[0]); i++) {
+ UBaseType_t hwm = uxTaskGetStackHighWaterMark(tasks[i].handle);
+ if (hwm < tasks[i].min_expected_words) {
+ /* Stack is close to overflow: increase allocation */
+ configASSERT(0); /* Break in debugger */
+ }
+ }
+ }
+ ```
+
+ ---
+
+ ## Pattern 5: Placing Arrays in Specific SRAM Regions
+
+ ```c
+ /* STM32F4: CCM RAM (0x10000000, 64KB) โ€” no DMA access, CPU-only, fastest */
+ __attribute__((section(".ccm")))
+ static float s_fft_buffer[1024]; /* 4KB in CCM */
+
+ /* STM32F4: SRAM2 (0x2001C000, 16KB) โ€” DMA-accessible backup */
+ __attribute__((section(".sram2")))
+ static uint8_t s_dma_rx_buf[4096];
+
+ /* Core-coupled memory for FreeRTOS idle task stack (avoids main SRAM contention) */
+ __attribute__((section(".ccm")))
+ static StackType_t s_idle_stack[configMINIMAL_STACK_SIZE];
+ ```
+
+ Requires corresponding sections in linker script targeting the CCM/SRAM2 MEMORY regions.
+
+ ---
+
+ ## Anti-Patterns
+
+ - **Calling `malloc` in ISR**: `malloc` is not reentrant and not interrupt-safe. Use a pool.
+ - **Not checking `pvPortMalloc` return value**: returns NULL on heap exhaustion. Dereferencing NULL = HardFault.
+ - **Single heap_4 spanning all SRAM**: if DMA buffers and task stacks share one heap, a DMA overrun can corrupt task stacks silently.
+ - **Stack too small with `printf`**: `printf` with float formatting (`%f`) uses ~1KB of stack. Use integer formatting in embedded code.
+
+ ## References
+
+ - FreeRTOS Heap: freertos.org/a00111.html
+ - ARM MPU: ARM Cortex-M4 Generic User Guide, Chapter 4.5
+ - FreeRTOS `uxTaskGetStackHighWaterMark`: freertos.org/uxTaskGetStackHighWaterMark.html