Introduction to RTOS Part 4 - Memory Management | Digi-Key Electronics

Introduction to RTOS Part 4 - Memory Management | Digi-Key Electronics

Understanding Memory Management in RTOS

Overview of Memory Allocation

  • Effective memory management is crucial when writing code for a Real-Time Operating System (RTOS) to avoid stack overflows and memory leaks.
  • Global and static variables are allocated in a section of memory known as static memory, which cannot be repurposed during program execution.

Types of Memory Allocation

  • Local variables within function calls are stored on the stack, which operates on a last-in-first-out principle, allowing easy management during nested function calls.
  • The stack can grow automatically by allocating additional space from free memory, accommodating local variables and arguments dynamically.

Heap Memory Dynamics

  • The heap is another area for dynamic allocation where programmers explicitly request memory using functions like malloc.
  • Failing to free dynamically allocated memory can lead to memory leaks, causing the heap to grow indefinitely and potentially overlap with the stack.

FreeRTOS Memory Management

  • In FreeRTOS, tasks receive portions of heap memory divided into Task Control Blocks (TCBs) and stacks unique to each task.
  • Proper allocation is critical; insufficient stack size can lead to undefined behavior or processor resets due to overwriting adjacent memory areas.

Static vs Dynamic Allocation in FreeRTOS

  • Newer versions of FreeRTOS allow static allocation for tasks and kernel objects, beneficial in critical applications where leaks could have severe consequences.
  • When dynamically allocating memory, fragmentation may occur if allocations and deallocations happen frequently, complicating overall management.

Heap Allocation Schemes in FreeRTOS

  • FreeRTOS offers various heap management schemes; choosing one is essential when integrating it into your build system.
  • Different heaps (Heap 1 through Heap 5), each with distinct characteristics regarding fragmentation handling and thread safety, cater to different application needs.

Considerations for ESP32

  • The ESP32 has multiple RAM types leading to a more complex heap allocation scheme compared to standard FreeRTOS implementations.

Understanding Stack Overflow in FreeRTOS

Task Creation and Memory Allocation

  • The example demonstrates spawning a task that stores numbers in an array and prints one of them, simplifying the setup by removing unnecessary tasks.
  • A large array of 100 integers is used, which requires 400 bytes. The allocated stack size is only 1 kilobyte, leading to potential overflow due to overhead.

Stack Overflow Detection

  • The stack canary mechanism helps prevent stack overflows by checking known values at the end of the stack; if altered, it triggers a processor reset as a safety measure.
  • To avoid overflow, it's essential to calculate total memory needs for local variables plus overhead; approximately 1200 bytes are required for safe operation.

Adjusting Stack Size

  • Increasing the stack size to around 1500 bytes resolves overflow issues, allowing the program to run without errors.
  • Using uxTaskGetStackHighWaterMark from FreeRTOS API helps monitor remaining stack space; approaching zero indicates imminent overflow risks.

Managing Heap Memory

  • Monitoring heap memory with vPortGetHeapSize provides insights into total available heap space before and after memory allocation using pvPortMalloc.
  • In FreeRTOS, pvPortMalloc should be used instead of standard malloc for thread safety; failure to free allocated memory leads to rapid depletion of heap space.

Error Handling and Memory Management

  • Implementing checks for null returns from malloc or pvPortMalloc prevents crashes when out of heap memory; appropriate error handling is crucial.
  • Properly freeing dynamically allocated memory using vPortFree ensures efficient use of heap space during task execution.

Challenge: Serial Echo Program

  • A challenge is presented to create two tasks mimicking a serial echo program: one listens for input and allocates memory for messages while another prints these messages back.
Video description

Memory management is important in a multi-threaded environment, as threads (or tasks) can quickly consume all of the allocated memory, causing bizarre effects such as overwritten memory locations or random processor resets. The solution to the challenge in the video can be found here: https://www.digikey.com/en/maker/projects/introduction-to-rtos-solution-to-part-4-memory-management/6d4dfcaa1ff84f57a2098da8e6401d9c In this video, we look at various ways to allocate memory to a task and how to monitor memory usage in FreeRTOS. Most C programs rely on 3 different types of memory. Static memory is set aside prior to program execution and used for things like static variables, constants, and global variables. Stack is allowed to grow dynamically and consists of local variables declared at the function level. Finally, heap may also grow dynamically and must be specifically allocated and deallocated by the programmer (e.g. using the malloc() and free() functions, respectively). Whenever we create a new task in FreeRTOS, we must assign it a set amount of stack memory to use out of the global, available heap. Note that each task also requires another section of heap for the Task Control Block (TCB), which stores various attributes about the task, such as its state and priority. We demonstrate ways to monitor the stack in each thread as well as the total amount of heap available to the system. We also show what happens when you overrun the stack or heap! Product Links: https://www.digikey.com/en/products/detail/adafruit-industries-llc/3405/7244967 Related Videos: Introduction to RTOS Part 1 - What is a Real-Time Operating System (RTOS)? - https://youtu.be/F321087yYy4​ Introduction to RTOS Part 2 - Getting Started with FreeRTOS - https://youtu.be/JIr7Xm_riRs​ Introduction to RTOS Part 3 - Task Scheduling - https://youtu.be/95yUbClyf3E​ Introduction to RTOS Part 4 - Memory Management - https://youtu.be/Qske3yZRW5I​ Introduction to RTOS Part 5 - Queue - https://youtu.be/pHJ3lxOoWeI​ Introduction to RTOS Part 6 - Mutex - https://youtu.be/I55auRpbiTs​ Introduction to RTOS Part 7 - https://youtu.be/5JcMtbA9QEE​ Introduction to RTOS Part 8 - https://youtu.be/b1f1Iex0Tso Introduction to RTOS Part 9 - https://youtu.be/qsflCf6ahXU Introduction to RTOS Part 10 - https://youtu.be/hRsWi4HIENc Introduction to RTOS Part 11 - https://youtu.be/C2xKhxROmhA Introduction to RTOS Part 12 - https://youtu.be/LPSHUcH5aQc Related Project Links: https://www.digikey.com/en/maker/projects/introduction-to-rtos-solution-to-part-4-memory-management/6d4dfcaa1ff84f57a2098da8e6401d9c Related Articles: https://www.digikey.com/en/maker/videos/shawn-hymel/getting-started-with-stm32-and-nucleo-part-3-how-to-run-multiple-threads-with-cmsis-rtos-interface Learn more: Maker.io - https://www.digikey.com/en/maker Digi-Key’s Blog – TheCircuit https://www.digikey.com/en/blog Connect with Digi-Key on Facebook https://www.facebook.com/digikey.electronics/ And follow us on Twitter https://twitter.com/digikey