Memory Management

In embedded systems it is better if tasks do not allocate memories dynamically. This enhances reliability and predictability of an RTOS greatly. This RTOS does not handle dynamic memory allocation and assumes that no tasks request for dynamic memories.

Stack

This RTOS creates and initializes stack memory during the initialization. The RTOS maintains a pool of stacks anticipating future demands for memory. When a task is created the RTOS simply returns an already initialized memory location. In addition, when a task dies, the RTOS returns the memory location to the pool.
for ( i = 0; i < MAXPROCESS-1; ++i){
	TASK_DESCRIPTORS[i].f = NULL;
	TASK_DESCRIPTORS[i].task_state = DEAD;
	TASK_DESCRIPTORS[i].next_task = &TASK_DESCRIPTORS[i+1];
}
					


The above listing shows the memory pool initialization for tasks. And, the following listing shows the task context creation code.
	/* Task terminate after */
	new_task->stack[MAXSTACK-1] = (uint8_t) (uint16_t) Task_Terminate;
	new_task->stack[MAXSTACK-2] = (uint8_t) ( (uint16_t) Task_Terminate >> 8);
	/* address of the task */
	new_task->stack[MAXSTACK-3] = (uint8_t) (uint16_t) kernel_task_create_args.f;
	new_task->stack[MAXSTACK-4] = (uint8_t) ( (uint16_t) kernel_task_create_args.f >> 8);
	/* r31 is saved first in stack[MAXSTACK-5] */
	/* SREG is saved in stack[MAXSTACK-6] */
	new_task->stack[MAXSTACK-6] = _BV(SREG_I);
	/* r1 is the zero register */
	new_task->stack[MAXSTACK-37] = (uint8_t) 0;
	/* r0 is at new_task->stack[MAXSTACK-37] */
	/* stack pointer now should point to new_task->stack[MAXSTACK-38] */
	new_task->sp = &(new_task->stack[MAXSTACK-38]);
	
	/* for memory protection 
	four bytes will be written with special bit patterns.
	If these patterns are over written then stack
	overflow has occurred. Not a full-proof method.
	*/
	new_task->stack[3] = 0b01010101;
	new_task->stack[2] = 0b11001100;
	new_task->stack[1] = 0b00110011;
	new_task->stack[0] = 0b10101010;
				

Heap

This RTOS does not allocate memory from the heap as dynamic allocation of memory is not handled by the kernel.