PKCtxNew Layer
Function: kctx_new
kctx_newunsigned int kctx_new(void *entry, unsigned int id, unsigned int quota)
{
unsigned int child = alloc_mem_quota(id, quota); //* Allocate memory for the new child thread
kctx_set_eip(child, entry); //* Set the eip of the thread states
kctx_set_esp(child, (void *) &STACK_LOC[child][PAGESIZE]); //* Set the esp of the thread states
return child;
}Purpose: Initializes a new kernel context for a child process by allocating resources, setting the
eip(instruction pointer) to the entry point of the process, and setting theesp(stack pointer) to the top of the designated stack space inSTACK_LOC.Mechanism:
Allocate Memory Quota:
Calls
alloc_mem_quota(id, quota)to designate memory resources for the new child process. Thealloc_mem_quotafunction is responsible for allocating part of the parent process’s quota to the child, and it returns the child process ID if successful.If allocation fails (insufficient resources or quota),
alloc_mem_quotawill returnNUM_IDS, signaling that the process could not be created.
Set Entry Point (EIP):
kctx_set_eip(child, entry)sets theeip(Extended Instruction Pointer) for the child process to the address of theentryfunction. This pointer represents where the CPU should begin executing for the new process.
Set Stack Pointer (ESP):
kctx_set_esp(child, (void *) &STACK_LOC[child][PAGESIZE])sets theesp(Extended Stack Pointer) to the top of the allocated stack for the child process. Since the stack grows downward, the stack pointer starts at the highest address in the stack space (&STACK_LOC[child][PAGESIZE]).
Return Value:
If successful,
kctx_newreturns the child process ID, which identifies the new kernel context created.In case of failure, it returns
NUM_IDS, signaling an error in creating the child context (usually due to memory allocation issues).
Use Case
This function is critical for creating new kernel threads and initializing their execution context. By setting up the eip and esp for the child, it prepares the thread for execution, allowing the OS to manage multiple threads and processes effectively.
Last updated