summaryrefslogtreecommitdiff
path: root/kc/core
diff options
context:
space:
mode:
authorAda Christine <adachristine18@gmail.com>2026-05-26 21:32:27 +0000
committerAda Christine <adachristine18@gmail.com>2026-05-26 21:32:27 +0000
commita10aabfcd52f702057316018cd7847ab2bfe4aa1 (patch)
treecc4652d2b602798934e8a48b4939cfb20eda1989 /kc/core
parent90c29fdde317c39384011a6ba97077c138f13ad6 (diff)
we're bringing kjarna back and not doing the crazy stuff with trying to have task management during efi. that was a bit extra.kjarna
Diffstat (limited to 'kc/core')
-rw-r--r--kc/core/Makefile10
-rw-r--r--kc/core/cpu/arch_thread.c81
-rw-r--r--kc/core/cpu/arch_thread.h12
-rw-r--r--kc/core/cpu/cpu.c4
-rw-r--r--kc/core/cpu/cpu_task.S54
-rw-r--r--kc/core/cpu/cpu_thread.S57
-rw-r--r--kc/core/cpu/exceptions.h4
-rw-r--r--kc/core/i8042.c18
-rw-r--r--kc/core/kc_main.c4
-rw-r--r--kc/core/memory.h2
-rw-r--r--kc/core/memory/memory.c24
-rw-r--r--kc/core/memory/page_early.c12
-rw-r--r--kc/core/panic.c6
-rw-r--r--kc/core/pic8259.c12
-rw-r--r--kc/core/pit8253.c6
-rw-r--r--kc/core/stdio.c (renamed from kc/core/kstdio.c)8
-rw-r--r--kc/core/task.c439
-rw-r--r--kc/core/task.h35
-rw-r--r--kc/core/video.c6
-rw-r--r--kc/core/vm_tree.c538
20 files changed, 736 insertions, 596 deletions
diff --git a/kc/core/Makefile b/kc/core/Makefile
index dbbeef1..730eba7 100644
--- a/kc/core/Makefile
+++ b/kc/core/Makefile
@@ -1,22 +1,20 @@
include ../../defaults.mk
include ../defaults.mk
-VPATH := ../../lib ../ cpu/ memory/
+VPATH := ../../lib ../../lib/libc ../ cpu/ memory/
TARGET := kernel.os
.DEFAULT: $(TARGET)
-CPPFLAGS += -I../../api -I../api -I../../lib -I.
+CPPFLAGS += -I../../api -I../api -I../../lib/api -I. -Icpu/
CFLAGS += -mcmodel=small -Wno-unused-const-variable -Wno-unused-function -fvisibility=hidden -g
-LDSCRIPT := ../kc.ld
-
AOBJS := entry_x86_64.o reloc_x86_64.o dynamic_x86_64.o
-COBJS := mmu.o cpu_task.o irq.o exceptions.o cpu.o msr.o mmu.o port.o
+COBJS := mmu.o cpu_thread.o irq.o exceptions.o cpu.o msr.o mmu.o port.o arch_thread.o
POBJS := pic8259.o pic8259_isr.o pit8253.o i8042.o
GOBJS := serial.o kc_main.o memory.o vm_tree.o panic.o task.o \
kcc_memory.o page_early.o page_stack.o video.o
-LOBJS := kprintf.o memset.o memcpy.o memmove.o memcmp.o kstdio.o string.o
+LOBJS := printf.o memset.o memcpy.o memmove.o memcmp.o stdio.o string.o
OBJS := $(AOBJS) $(COBJS) $(POBJS) $(GOBJS) $(LOBJS)
DEPS := $(patsubst %.o,%.d,$(OBJS))
diff --git a/kc/core/cpu/arch_thread.c b/kc/core/cpu/arch_thread.c
new file mode 100644
index 0000000..c0d707a
--- /dev/null
+++ b/kc/core/cpu/arch_thread.c
@@ -0,0 +1,81 @@
+#include <stdint.h>
+#include <stddef.h>
+#include <stdnoreturn.h>
+
+#include <libc/stdio.h>
+
+#include "task.h"
+
+struct arch_register_context
+{
+ uint64_t
+ r15,
+ r14,
+ r13,
+ r12,
+ r11,
+ r10,
+ r9,
+ r8,
+ rsi,
+ rdi,
+ rdx,
+ rcx,
+ rbx,
+ rax,
+ rbp,
+ rsp;
+};
+
+extern uint64_t *get_tss_rsp0(void);
+
+struct arch_thread_context
+{
+ struct arch_register_context register_context;
+ void *return_address;
+};
+
+extern void arch_swap_thread_stack(
+ void * volatile *outgoing_stack,
+ void *incoming_stack);
+
+extern void arch_begin_thread(
+ void *(func)(void *),
+ void *params);
+
+void arch_create_thread(
+ struct kc_thread *thread,
+ void *(*func)(void *),
+ void *params)
+{
+ uintptr_t stack_pointer = (uintptr_t)thread->kernel_stack_pointer;
+ struct arch_thread_context *context = (struct arch_thread_context *)
+ (stack_pointer -= sizeof(*context));
+ thread->kernel_stack_pointer = (void *)stack_pointer;
+
+ context->return_address = (void *)arch_begin_thread;
+ context->register_context.rdi = (uint64_t)func;
+ context->register_context.rsi = (uint64_t)params;
+ context->register_context.rdx = (uint64_t)thread;
+ context->register_context.rsp = (uint64_t)&context->return_address;
+}
+
+void arch_swap_thread(
+ struct kc_thread *outgoing,
+ struct kc_thread *incoming)
+{
+ arch_swap_thread_stack(&outgoing->kernel_stack_pointer, incoming->kernel_stack_pointer);
+}
+
+void *arch_idle_loop(void *)
+{
+ for (;;) __asm__ ("hlt");
+ return nullptr;
+}
+
+noreturn void arch_terminate_thread(union kc_thread_result result, struct kc_thread *)
+{
+ kct_terminate(result);
+ for (;;) __asm__ ("hlt");
+}
+
diff --git a/kc/core/cpu/arch_thread.h b/kc/core/cpu/arch_thread.h
new file mode 100644
index 0000000..2b8d0fb
--- /dev/null
+++ b/kc/core/cpu/arch_thread.h
@@ -0,0 +1,12 @@
+#pragma once
+
+void * arch_idle_loop(void *);
+
+void arch_create_thread(
+ struct kc_thread *thread,
+ void *(kc_thread_func)(void *),
+ void *params);
+
+void arch_swap_thread(
+ struct kc_thread *outgoing,
+ struct kc_thread *incoming);
diff --git a/kc/core/cpu/cpu.c b/kc/core/cpu/cpu.c
index da55d38..226c9cf 100644
--- a/kc/core/cpu/cpu.c
+++ b/kc/core/cpu/cpu.c
@@ -10,7 +10,7 @@
#include <stddef.h>
#include <stdint.h>
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
#define GDT_ENTRIES 16
#define IDT_ENTRIES 256
@@ -53,7 +53,7 @@ uint64_t *get_tss_rsp0(void)
static void syscall_entry(void)
{
- kprintf("system call\n");
+ printf("system call\n");
halt();
}
diff --git a/kc/core/cpu/cpu_task.S b/kc/core/cpu/cpu_task.S
deleted file mode 100644
index a411028..0000000
--- a/kc/core/cpu/cpu_task.S
+++ /dev/null
@@ -1,54 +0,0 @@
-/* thread switching routines for x86_64
-* adapted from:
-* https://wiki.osdev.org/Brendan%27s_Multi-tasking_Tutorial
-*
-*
-*/
-
-.hidden cpu_set_thread
-.global cpu_set_thread
-.type cpu_set_thread, @function
-cpu_set_thread:
- /* x86_64 SysV ABI
- * must save the following registers to the stack:
- * rbx, rsp, rbp, r12, r13, r14, r15
- * the following are the parameters for switching tasks
- * rdi: pointer to control block of thread being switched to
- * rsi: pointer to control block of the current thread
- * rdx: pointer to this cpu's task state segment rsp0 field
- */
- // test for attempt to switch to same thread
- cmp %rdi,%rsi
- je .Lnothing
- // test for a NULL origin thread
- test %rsi,%rsi
- // skip saving the state for a NULL origin thread
- jz .Lnull_thread
- push %rbx
- push %r12
- push %r13
- push %r14
- push %r15
- push %rbp
- /* the current task will be in rsi */
- mov %rsp, 0(%rsi) // save the stack pointer for the current task
-.Lnull_thread:
- mov 0(%rdi),%rsp // new stack is the next's task's stack
- mov 8(%rdi),%rbx // top of the next task's kernel stack
- mov %rbx,0(%rdx) // save the esp0 to the tss
- mov 16(%rdi),%rax // page map for the next task
- mov %cr3, %rcx // in case we need to change the page map
- cmp %rax,%rcx
- je .Lfinish
- mov %rax,%cr3 // if the page maps are not the same, reload
-.Lfinish:
- pop %rbp // get all the registers off the new task's stack
- pop %r15
- pop %r14
- pop %r13
- pop %r12
- pop %rbx
-.Lnothing: // do nothing if the threads are the same
- ret // leave into the new task
-.size cpu_set_thread, . - cpu_set_thread
-
diff --git a/kc/core/cpu/cpu_thread.S b/kc/core/cpu/cpu_thread.S
new file mode 100644
index 0000000..c4d04e1
--- /dev/null
+++ b/kc/core/cpu/cpu_thread.S
@@ -0,0 +1,57 @@
+.section .text
+
+.extern arch_terminate_thread
+
+.global arch_begin_thread
+arch_begin_thread:
+ movq %rdi, %rax
+ movq %rsi, %rdi
+ pushq %rdx
+ pushq %rbp
+ movq %rsp, %rbp
+ andq $-16, %rsp
+ callq *%rax
+ movq %rax, %rdi
+ movq 8(%rbp), %rsi
+ callq arch_terminate_thread
+
+.global arch_swap_thread_stack
+arch_swap_thread_stack:
+ pushq %rsp
+ pushq %rbp
+ pushq %rax
+ pushq %rbx
+ pushq %rcx
+ pushq %rdx
+ pushq %rdi
+ pushq %rsi
+ pushq %r8
+ pushq %r9
+ pushq %r10
+ pushq %r11
+ pushq %r12
+ pushq %r13
+ pushq %r14
+ pushq %r15
+ movq %rsp, (%rdi)
+ .Lenter_thread:
+ movq %rsi, %rsp
+ popq %r15
+ popq %r14
+ popq %r13
+ popq %r12
+ popq %r11
+ popq %r10
+ popq %r9
+ popq %r8
+ popq %rsi
+ popq %rdi
+ popq %rdx
+ popq %rcx
+ popq %rbx
+ popq %rax
+ popq %rbp
+ popq %rsp
+ retq
+
+
diff --git a/kc/core/cpu/exceptions.h b/kc/core/cpu/exceptions.h
index 7babb65..14a2088 100644
--- a/kc/core/cpu/exceptions.h
+++ b/kc/core/cpu/exceptions.h
@@ -21,7 +21,7 @@
#ifndef __ASSEMBLER__
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
struct isr_context_param_regs
{
@@ -53,7 +53,7 @@ struct isr_context
static inline void print_exception_context(struct isr_context *context)
{
- kprintf(
+ printf(
"exception %#hhx:%x context:\n"
"interrupt entry state:\n"
"rip: %#hx:%p rflags: %#0.16lx\n"
diff --git a/kc/core/i8042.c b/kc/core/i8042.c
index 0ba12dc..f6b63b0 100644
--- a/kc/core/i8042.c
+++ b/kc/core/i8042.c
@@ -2,7 +2,7 @@
#include "port.h"
#include "i8042.h"
#include "pic8259.h"
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
static void i8042_init(void);
static void i8042_enable(void) {}
@@ -99,21 +99,21 @@ static void i8042_set_config(void)
i8042_command(0x20);
uint8_t config_byte;
i8042_read(&config_byte);
- kprintf("i8042: current config: %#0.2x\n", config_byte);
+ printf("i8042: current config: %#0.2x\n", config_byte);
config_byte &= 0xfc;
if (config_byte & (0x1 << 5))
{
maybe_dual_channel = true;
}
config_byte |= 0x01;
- kprintf("i8042: new config: %#0.2x\n", config_byte);
+ printf("i8042: new config: %#0.2x\n", config_byte);
i8042_command(0x60);
i8042_write(config_byte);
i8042_command(0xaa);
uint8_t bist_result;
if (i8042_read(&bist_result) && bist_result != 0x55)
{
- kprintf("i8042: warning: error self-testing device. aborting.\n");
+ printf("i8042: warning: error self-testing device. aborting.\n");
return;
}
@@ -124,11 +124,11 @@ static void i8042_set_config(void)
uint8_t config_byte;
if (i8042_read(&config_byte) && config_byte & (0x1 << 5))
{
- kprintf("i8042: single-channel controller detected\n");
+ printf("i8042: single-channel controller detected\n");
}
else
{
- kprintf("i8042: dual-channel controller detected\n");
+ printf("i8042: dual-channel controller detected\n");
is_dual_channel = true;
}
}
@@ -136,7 +136,7 @@ static void i8042_set_config(void)
outb(PS2_COMMAND, 0xab);
if (inb(PS2_DATA) != 0x00)
{
- kprintf("i8042: failed testing port a\n");
+ printf("i8042: failed testing port a\n");
}
else
{
@@ -147,7 +147,7 @@ static void i8042_set_config(void)
outb(PS2_COMMAND, 0xa9);
if (inb(PS2_DATA) != 0x00)
{
- kprintf("i8042: failed testing port b\n");
+ printf("i8042: failed testing port b\n");
}
else
{
@@ -162,7 +162,7 @@ static void i8042_set_config(void)
i8042_write(0xff);
if(inb(PS2_DATA) == 0xfa && inb(PS2_DATA) == 0xaa)
{
- kprintf("i8042: detected device on channel, type %#0.2x\n", inb(PS2_DATA));
+ printf("i8042: detected device on channel, type %#0.2x\n", inb(PS2_DATA));
}
}
diff --git a/kc/core/kc_main.c b/kc/core/kc_main.c
index 9a84727..4f70d00 100644
--- a/kc/core/kc_main.c
+++ b/kc/core/kc_main.c
@@ -10,7 +10,7 @@
#include "i8042.h"
#include <kernel/entry.h>
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
#include <stdbool.h>
#include <stddef.h>
@@ -27,7 +27,7 @@ unsigned long kc_main(struct kc_boot_data *data)
cpu_init();
serial_init();
video_init();
- kprintf("sophia starting, boot data %#lx\n", boot_data);
+ printf("sophia starting, boot data %#lx\n", boot_data);
memory_init();
pic8259_init();
pit8253_timer_source.init();
diff --git a/kc/core/memory.h b/kc/core/memory.h
index 6f70e57..425c2cd 100644
--- a/kc/core/memory.h
+++ b/kc/core/memory.h
@@ -4,7 +4,7 @@
#include <kernel/memory/paging.h>
#include <kernel/memory/range.h>
-#include <lib/kstring.h>
+#include <libc/string.h>
#include <core/memory.h>
diff --git a/kc/core/memory/memory.c b/kc/core/memory/memory.c
index ee0d9ca..7071018 100644
--- a/kc/core/memory/memory.c
+++ b/kc/core/memory/memory.c
@@ -20,7 +20,7 @@
#include <kc.h>
#include <core/memory.h>
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
#define align_next(x, a) (x + a - 1) & ~(a - 1)
@@ -89,7 +89,7 @@ struct vm_tree *vm_get_tree(void)
void page_init(void)
{
- kprintf("initializing page frame allocator\n");
+ printf("initializing page frame allocator\n");
page_early_init();
page_stack_init();
}
@@ -98,7 +98,7 @@ void page_init_final(void)
{
if (current_alloc_func == boot_page_alloc)
{
- kprintf("finishing page frame allocator initialization\n");
+ printf("finishing page frame allocator initialization\n");
page_early_final();
current_alloc_func = page_stack_alloc;
}
@@ -176,7 +176,7 @@ static void *map_tableset(void *vaddr, uint64_t *tables[TABLESET_COUNT])
}
else
{
- kprintf("error: failed allocating memory for page table\n");
+ printf("error: failed allocating memory for page table\n");
PANIC(OUT_OF_MEMORY);
}
}
@@ -380,7 +380,7 @@ static void temp_page_unmap(void *vaddr)
static void vm_init(void)
{
- kprintf("initializing vm state\n");
+ printf("initializing vm state\n");
struct kc_boot_data *boot_data = get_boot_data();
struct vm_core_static_state *states = &vm_state.statics[0];
@@ -433,7 +433,7 @@ static void vm_init(void)
vm_state.zero_page = page_alloc(PAGE_ALLOC_CONV);
if (!vm_state.zero_page)
{
- kprintf("failed allocating for zero page\n");
+ printf("failed allocating for zero page\n");
PANIC(GENERAL_PANIC);
}
@@ -441,7 +441,7 @@ static void vm_init(void)
if (!zero_temp)
{
- kprintf("failed mapping zero page for initialization\n");
+ printf("failed mapping zero page for initialization\n");
PANIC(GENERAL_PANIC);
}
@@ -492,7 +492,7 @@ void *heap_alloc(size_t size)
if ((void *)-1ULL == heap_root)
{
struct vm_tree_node *heap_node = &vm_state.statics[HEAP_VM_STATE].node;
- kprintf("initializing heap at %#lx of %zu bytes\n",
+ printf("initializing heap at %#lx of %zu bytes\n",
heap_node->key.address, heap_node->key.size);
heap_root = NULL;
header = (struct heap_header *)heap_node->key.address;
@@ -650,7 +650,7 @@ int anonymous_page_handler(
if (!paddr)
{
- kprintf("got zero from page_alloc :|\n");
+ printf("got zero from page_alloc :|\n");
PANIC(OUT_OF_MEMORY);
}
page_map_at(
@@ -676,14 +676,14 @@ void page_fault_handler(struct isr_context *context)
if (!node)
{
print_exception_context(context);
- kprintf("error: page fault in unmanaged address %#lx\n", address);
+ printf("error: page fault in unmanaged address %#lx\n", address);
PANIC(UNHANDLED_FAULT);
}
if (!node->object->handler)
{
print_exception_context(context);
- kprintf("error: vm object at %p has no fault handler\n");
+ printf("error: vm object at %p has no fault handler\n");
PANIC(UNHANDLED_FAULT);
}
@@ -693,7 +693,7 @@ void page_fault_handler(struct isr_context *context)
void general_protection_handler(struct isr_context *context)
{
//TODO: implement #gp handler
- kprintf("general protection violation\n");
+ printf("general protection violation\n");
print_exception_context(context);
PANIC(UNHANDLED_FAULT);
}
diff --git a/kc/core/memory/page_early.c b/kc/core/memory/page_early.c
index 9ac90d2..989f82a 100644
--- a/kc/core/memory/page_early.c
+++ b/kc/core/memory/page_early.c
@@ -1,7 +1,7 @@
#include "page_early.h"
#include "panic.h"
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
static struct page_early_state
{
@@ -13,20 +13,20 @@ early_state;
void page_early_init(void)
{
- kprintf("initializing early page frame allocator\n");
+ printf("initializing early page frame allocator\n");
struct kc_boot_data *boot_data = get_boot_data();
early_state.first = &boot_data->memory.entries[0];
early_state.last = &boot_data->memory.entries[boot_data->memory.count];
early_state.current = early_state.first;
- /*kprintf("memory ranges\n");
+ /*printf("memory ranges\n");
struct memory_range *current = early_state.first;
do
{
- kprintf("base %#0.16lx size %#0.16lx type %d\n", current->base, current->size, current->type);
+ printf("base %#0.16lx size %#0.16lx type %d\n", current->base, current->size, current->type);
current++;
}
while (current != early_state.last);
@@ -37,7 +37,7 @@ void page_early_final(void)
{
if (early_state.first)
{
- kprintf("finalizing early page allocator\n");
+ printf("finalizing early page allocator\n");
for (struct memory_range *current = early_state.first;
current < early_state.last;
current++)
@@ -101,7 +101,7 @@ kc_phys_addr page_early_alloc(enum page_alloc_flags type)
early_state.current++;
}
- kprintf("error: early allocator has run out of memory\n");
+ printf("error: early allocator has run out of memory\n");
PANIC(OUT_OF_MEMORY);
}
diff --git a/kc/core/panic.c b/kc/core/panic.c
index 7844487..02c58c7 100644
--- a/kc/core/panic.c
+++ b/kc/core/panic.c
@@ -1,6 +1,6 @@
#include "panic.h"
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
#include <stdbool.h>
@@ -13,12 +13,12 @@ static char const *reason_strings[] = {
noreturn void panic(const char *file, int line, enum panic_reason reason)
{
- // TODO: kprintf() and friends
+ // TODO: printf() and friends
if (reason > sizeof(reason_strings) / sizeof(*reason_strings))
{
reason = 0;
}
- kprintf(
+ printf(
"kernel panic:%s:%u %s\n",
file,
line,
diff --git a/kc/core/pic8259.c b/kc/core/pic8259.c
index 4ddd2e1..792d0bd 100644
--- a/kc/core/pic8259.c
+++ b/kc/core/pic8259.c
@@ -4,7 +4,7 @@
#include <stdbool.h>
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
#define ICW1_ICW4 0x1
#define ICW1_SINGLE 0x2
@@ -28,7 +28,7 @@ void pic8259_irq_install(uint8_t irq, pic8259_handler_func h)
{
if (irq_handlers[irq])
{
- kprintf("attempt to overwrite irq handler for %u\n", irq);
+ printf("attempt to overwrite irq handler for %u\n", irq);
return;
}
irq_handlers[irq] = h;
@@ -43,7 +43,7 @@ static void wait(void)
void pic8259_init(void)
{
- kprintf("initializing legacy pic\n");
+ printf("initializing legacy pic\n");
// basic init. not gonna fret with this too much
outb(PIC_PRI_CMD, ICW1_INIT|ICW1_ICW4);
wait();
@@ -171,7 +171,7 @@ void pic8259_irq_begin(uint8_t irq)
// check for spurious activations
if (irq_is_spurious(irq))
{
- kprintf("spurious activation of irq%hhu\n", irq);
+ printf("spurious activation of irq%hhu\n", irq);
return;
}
@@ -181,12 +181,12 @@ void pic8259_irq_begin(uint8_t irq)
if (result)
{
- kprintf("error handling irq%hhu: % d\n", irq, result);
+ printf("error handling irq%hhu: % d\n", irq, result);
}
}
else
{
- kprintf("unhandled irq%hhu\n", irq);
+ printf("unhandled irq%hhu\n", irq);
}
pic8259_irq_end(irq);
diff --git a/kc/core/pit8253.c b/kc/core/pit8253.c
index 360808f..31cf349 100644
--- a/kc/core/pit8253.c
+++ b/kc/core/pit8253.c
@@ -5,7 +5,7 @@
#include <stdatomic.h>
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
#define PIT8253_DATA0 0x40
#define PIT8253_CMD 0x43
@@ -82,9 +82,9 @@ void pit8253_set_frequency(uint32_t frequency)
if (d > UINT16_MAX)
{
- kprintf("warning: %uHz is too slow for 8253 pit\n", PIT_HZ/d);
+ printf("warning: %uHz is too slow for 8253 pit\n", PIT_HZ/d);
d = UINT16_MAX;
- kprintf("warning: set timer to minimum frequency\n");
+ printf("warning: set timer to minimum frequency\n");
}
set_divisor(d);
diff --git a/kc/core/kstdio.c b/kc/core/stdio.c
index 680eb07..66c539f 100644
--- a/kc/core/kstdio.c
+++ b/kc/core/stdio.c
@@ -4,12 +4,12 @@
#include <stdint.h>
#include <stdbool.h>
-#include <lib/kstdio.h>
-#include <lib/kstring.h>
+#include <libc/stdio.h>
+#include <libc/string.h>
-FILE *kstdout;
+FILE *stdout;
-int kfputc(int c, FILE *f)
+int fputc(int c, FILE *f)
{
(void)f;
video_putchar(c);
diff --git a/kc/core/task.c b/kc/core/task.c
index 3e0288d..a298a05 100644
--- a/kc/core/task.c
+++ b/kc/core/task.c
@@ -12,13 +12,9 @@
#include <stdbool.h>
#include <lib/elf.h>
-#include <lib/kstdio.h>
+#include <libc/stdio.h>
-static const size_t INTERRUPT_STACK_SIZE = 4096;
-static const size_t THREAD_SIZE = 16834;
-static const enum vm_alloc_flags ALLOC_FLAGS = VM_ALLOC_ANY|VM_ALLOC_ANONYMOUS;
-
-extern uint64_t *get_tss_rsp0(void);
+#include "arch_thread.h"
static void lock_scheduler(void);
static void unlock_scheduler(void);
@@ -27,7 +23,7 @@ static void unlock_preempt(void);
static void update_time(void);
-static struct kc_thread *create_thread(void (*thread_entry)(void));
+static struct kc_thread *create_thread(void *(*thread_f)(void *), void *p);
static void destroy_thread(struct kc_thread *thread);
static void set_thread(struct kc_thread *thread);
static void block_thread(enum kc_thread_status reason);
@@ -37,10 +33,6 @@ static void sleep_thread_until(uint64_t nanoseconds);
static int sleeping_thread_callback(uint64_t nanoseconds);
-static struct kc_thread *ready_thread_pop(void);
-static void ready_thread_push(struct kc_thread *thread);
-static void ready_thread_push_back(struct kc_thread *thread);
-
const struct timer_source * timesource;
/* static threads that are always present
@@ -50,130 +42,138 @@ static struct kc_thread *idle_thread;
// thread lists for the scheduler to manipulate
static struct kc_thread *current_thread;
-static struct kc_thread *first_ready_thread;
-static struct kc_thread *last_ready_thread;
-static struct kc_thread *sleeping_threads;
+
+struct thread_queue
+{
+ struct kc_thread
+ *first,
+ *last;
+};
+
+static void thread_queue_push(struct thread_queue *queue, struct kc_thread *thread);
+static void thread_queue_push_back(struct thread_queue *queue, struct kc_thread *thread);
+
+static void thread_queue_push(struct thread_queue *queue, struct kc_thread *thread)
+{
+ thread->next = queue->first;
+ queue->first = thread;
+
+ if (!queue->last)
+ {
+ thread_queue_push_back(queue, thread);
+ }
+}
+
+static void thread_queue_push_back(struct thread_queue *queue, struct kc_thread *thread)
+{
+ if (!queue->first)
+ {
+ thread_queue_push(queue, thread);
+ }
+ else if (queue->last)
+ {
+ queue->last->next = thread;
+ }
+
+ queue->last = thread;
+}
+
+struct kc_thread *thread_queue_pop(struct thread_queue *queue)
+{
+ if (!queue->first)
+ {
+ return nullptr;
+ }
+
+ struct kc_thread *thread = queue->first;
+ queue->first = thread->next;
+ thread->next = nullptr;
+ if (!queue->first)
+ {
+ queue->last = nullptr;
+ }
+
+ return thread;
+}
+
+bool thread_queue_any(struct thread_queue queue)
+{
+ return queue.first && queue.last;
+}
+
+static struct thread_queue ready_queue;
+static struct thread_queue sleep_queue;
+static struct thread_queue wait_queue;
static volatile atomic_uint_fast64_t preempt_switch_count = 0;
static volatile atomic_bool preempt_switch_flag = false;
-static void idle_thread_entry(void)
+static void *idle_thread_entry(void *)
{
- kprintf("idle thread started\n");
- unlock_scheduler();
-
- __asm__ ("sti");
+ printf("idle thread started\n");
+ __asm__ ("sti");
+
+
while (true)
{
__asm__ ("hlt;");
}
-}
-
-#define PS2INPUT 0x60
-#define PS2STATUS 0x64
-#define PS2STATUS_IBF 0x1
-static void keyboard_input_loop(void)
-{
- bool has_bytes = true;
- while (has_bytes)
- {
- has_bytes = inb(PS2STATUS) & PS2STATUS_IBF;
- if (has_bytes)
- {
- kprintf("read byte from keyboard input: %hhd\n", inb(PS2INPUT));
- }
- else
- {
- kprintf("no bytes in keyboard input\n");
- }
- }
+ return nullptr;
}
-static void sleepy_thread_entry(void)
+static void *sleepy_thread_entry(void *p)
{
+ uint64_t sleep_nanoseconds = (uint64_t)p;
int thread_slept_count = 0;
while (true)
{
- sleep_thread(1000000000);
+ sleep_thread(sleep_nanoseconds);
thread_slept_count++;
- //keyboard_input_loop();
+ printf("thread slept %d times\n", thread_slept_count);
}
(void)thread_slept_count;
+ return nullptr;
}
-static void create_interrupt_stack(size_t size)
-{
- char *rsp0 = vm_alloc(size, ALLOC_FLAGS);
- memset(rsp0, 0, size);
- *get_tss_rsp0() = (uintptr_t)rsp0 + size;
-}
-noreturn void task_init(void)
-{
- lock_scheduler();
- timesource = &pit8253_timer_source;
- timesource->append_callback(sleeping_thread_callback);
- timesource->start();
- kprintf(
- "starting task management, timesource delta %luns\n",
- timesource->nanoseconds_delta());
- // XXX: unfuck this mess at some point
- // XXX: make this also not demand-allocated or it's gonna fail
- create_interrupt_stack(INTERRUPT_STACK_SIZE);
-
- // initalize static threads
- idle_thread = create_thread(idle_thread_entry);
- struct kc_thread *sleepy_thread = create_thread(sleepy_thread_entry);
-
- current_thread = idle_thread;
- ready_thread_push_back(sleepy_thread);
+static uint64_t scheduler_flags;
- idle_thread->status = RUNNING;
- cpu_set_thread(&idle_thread->state, NULL, get_tss_rsp0());
+static inline bool check_preempt_count()
+{
+ if (atomic_load(&preempt_switch_count) > 0)
+ {
+ return true;
+ }
- // shouldn't ever get here
- PANIC(DEAD_END);
+ return false;
}
void task_schedule(void)
{
- if (atomic_load(&preempt_switch_count))
- {
- preempt_switch_flag = true;
- return;
- }
+ if(check_preempt_count())
+ {
+ preempt_switch_flag = true;
+ return;
+ }
- if (first_ready_thread)
- {
- struct kc_thread *this_thread = ready_thread_pop();
+ struct kc_thread *t = thread_queue_pop(&ready_queue);
- if (this_thread == idle_thread)
- {
- if (first_ready_thread)
- {
- this_thread->status = READY;
- this_thread = ready_thread_pop();
- ready_thread_push(idle_thread);
- }
- else if (current_thread->status == RUNNING)
- {
- return;
- }
- else
- {
- // NULL statement????? idon't like
- }
- }
- set_thread(this_thread);
- }
-}
+ if (t == idle_thread)
+ {
+ thread_queue_push_back(&ready_queue, t);
+ t = thread_queue_pop(&ready_queue);
+ }
-static uint64_t scheduler_flags;
+ if (t && current_thread->status != RUNNING)
+ {
+ set_thread(t);
+ }
+}
static void lock_scheduler(void)
{
@@ -193,7 +193,7 @@ static void unlock_scheduler(void)
static void unlock_preempt(void)
{
- if (atomic_load(&preempt_switch_count) >= 1)
+ if (atomic_load(&preempt_switch_count) > 0)
{
preempt_switch_count--;
}
@@ -220,42 +220,21 @@ void update_time(void)
}
}
-static struct kc_thread *create_thread(void (*thread_f)(void))
-{
- char *task_bottom = vm_alloc(16384, ALLOC_FLAGS);
- struct kc_thread *thread =
- (struct kc_thread *)(task_bottom + 16384 - sizeof(*thread));
-
- thread->next = NULL;
-
- thread->time_elapsed = 0;
- thread->sleep_expiration = 0;
+#define KC_THREAD_SIZE 0x3000
- thread->state.stack = (uintptr_t)thread;
- thread->state.stack_top = *get_tss_rsp0();
- thread->state.page_map = mmu_get_map();
-
- // set up the expected stack values for the state
- struct task_register_state
- {
- uint64_t rbp;
- uint64_t r15;
- uint64_t r14;
- uint64_t r13;
- uint64_t r12;
- uint64_t rbx;
- uint64_t rip;
- }
- *register_state =
- (struct task_register_state *)
- (thread->state.stack -= sizeof(*register_state));
+static struct kc_thread *create_thread(void *(*thread_f)(void *), void *p)
+{
+ void *buffer = vm_alloc(KC_THREAD_SIZE, VM_ALLOC_ANONYMOUS|VM_ALLOC_ANY);
+ memset(buffer, 0, KC_THREAD_SIZE);
- memset(register_state, 0, sizeof(*register_state));
+ uintptr_t stack_head = (uintptr_t)buffer + KC_THREAD_SIZE;
+ struct kc_thread *thread = (struct kc_thread *)(stack_head -= sizeof(*thread));
- register_state->rip = (uint64_t)thread_f;
- register_state->rbp = thread->state.stack;
+ thread->kernel_stack_head = (void *)stack_head;
+ thread->kernel_stack_pointer = (void *)stack_head;
+ thread->status = READY;
- thread->status = READY;
+ arch_create_thread(thread, thread_f, p);
return thread;
}
@@ -267,11 +246,17 @@ static void destroy_thread(struct kc_thread *thread)
static void set_thread(struct kc_thread *thread)
{
+ if (thread == current_thread)
+ {
+ return;
+ }
+
if (atomic_load(&preempt_switch_count))
{
preempt_switch_flag = true;
return;
}
+
update_time();
struct kc_thread *previous_thread = current_thread;
current_thread = thread;
@@ -279,15 +264,11 @@ static void set_thread(struct kc_thread *thread)
if (previous_thread->status == RUNNING)
{
previous_thread->status = READY;
- ready_thread_push(previous_thread);
+ thread_queue_push(&ready_queue, previous_thread);
}
- cpu_set_thread(
- &current_thread->state,
- &previous_thread->state,
- get_tss_rsp0());
-
current_thread->status = RUNNING;
+ arch_swap_thread(previous_thread, current_thread);
}
static void block_thread(enum kc_thread_status reason)
@@ -304,14 +285,14 @@ static void unblock_thread(struct kc_thread *thread)
thread->status = READY;
- if (!first_ready_thread || (current_thread == idle_thread))
+ if (!thread_queue_any(ready_queue) || (current_thread == idle_thread))
{
unlock_preempt();
set_thread(thread);
}
else
{
- ready_thread_push_back(thread);
+ thread_queue_push_back(&ready_queue, thread);
}
unlock_scheduler();
@@ -332,89 +313,149 @@ static void sleep_thread_until(uint64_t nanoseconds)
return;
}
-// kprintf("time elapsed is now %ld\r\n", timesource->nanoseconds_elapsed());
-// kprintf("thread will now sleep until %ld\r\n", nanoseconds);
current_thread->sleep_expiration = nanoseconds;
- current_thread->next = sleeping_threads;
- sleeping_threads = current_thread;
+
+ thread_queue_push_back(&sleep_queue, current_thread);
unlock_preempt();
block_thread(SLEEPING);
}
-static struct kc_thread *ready_thread_pop(void)
+static int sleeping_thread_callback(uint64_t timestamp)
{
- struct kc_thread *thread = first_ready_thread;
+ lock_preempt();
- if (thread)
- {
- first_ready_thread = thread->next;
- }
+ struct thread_queue queue = sleep_queue;
- if (!first_ready_thread)
- {
- last_ready_thread = NULL;
- }
+ sleep_queue = (struct thread_queue){ nullptr, nullptr };
- return thread;
+ {
+ struct kc_thread *t;
+ while((t = thread_queue_pop(&queue)) != nullptr)
+ {
+ if (t->sleep_expiration <= timestamp)
+ {
+ t->sleep_expiration = 0;
+ unblock_thread(t);
+ }
+ else
+ {
+ thread_queue_push(&sleep_queue, t);
+ }
+ }
+ }
+
+ unlock_preempt();
+ lock_scheduler();
+ task_schedule();
+ unlock_scheduler();
+
+ return 0;
}
-static void ready_thread_push(struct kc_thread *thread)
-{
- thread->next = first_ready_thread;
- first_ready_thread = thread;
+typedef void (locked_scheduler_action)(void *);
- if (!last_ready_thread)
- {
- last_ready_thread = first_ready_thread;
- }
+static void with_locked_scheduler(
+ locked_scheduler_action *action,
+ void *action_parameter)
+{
+ lock_scheduler();
+ action(action_parameter);
+ unlock_scheduler();
}
-static void ready_thread_push_back(struct kc_thread *thread)
+static void terminate_action(void *result)
{
- if (last_ready_thread)
- {
- last_ready_thread->next = thread;
- }
- else
- {
- first_ready_thread = thread;
- }
- last_ready_thread = thread;
+ union kc_thread_result *result_value = result;
+ current_thread->result = *result_value;
+ current_thread->kernel_stack_pointer = current_thread->kernel_stack_head;
+
+ struct thread_queue queue = wait_queue;
+
+ lock_preempt();
+
+ wait_queue = (struct thread_queue) { nullptr, nullptr };
+
+ {
+ struct kc_thread *t;
+ while((t = thread_queue_pop(&queue)) != nullptr)
+ {
+ if (t->wait_target == current_thread)
+ {
+ t->wait_target = nullptr;
+ t->status = READY;
+ thread_queue_push_back(&ready_queue, t);
+ }
+ else
+ {
+ thread_queue_push(&wait_queue, t);
+ }
+ }
+ }
+
+ unlock_preempt();
+
+ block_thread(TERMINATED);
}
-static int sleeping_thread_callback(uint64_t nanoseconds)
+void kct_terminate(union kc_thread_result result)
{
- lock_preempt();
+ with_locked_scheduler(terminate_action, &result);
+}
- struct kc_thread *sleeping = sleeping_threads;
- sleeping_threads = NULL;
+union kc_thread_result kct_wait(struct kc_thread *target)
+{
+ current_thread->wait_target = target;
+ thread_queue_push_back(&wait_queue, current_thread);
+ block_thread(WAITING);
+ return target->result;
+}
- while (sleeping != NULL)
- {
- struct kc_thread *this_thread = sleeping;
- sleeping = sleeping->next;
+static void *waited_thread_test(void *)
+{
+ printf("worker thread, sleeping for some time...\n");
+ sleep_thread(30000000000);
+ return (void *)1;
+}
- if (this_thread->sleep_expiration <= nanoseconds)
- {
- //kprintf("thread awakened: %p\n", this_thread);
- this_thread->sleep_expiration = 0;
- unblock_thread(this_thread);
- }
- else
- {
- this_thread->next = sleeping_threads;
- sleeping_threads = this_thread;
- }
- }
+static void *waiting_thread_test(void *)
+{
+ printf("waiting thread\n");
+ struct kc_thread *t = create_thread(waited_thread_test, nullptr);
+ t->status = READY;
+ thread_queue_push_back(&ready_queue, t);
+ union kc_thread_result r = kct_wait(t);
+ printf("waited thread terminated result: %d\n", r);
+ return nullptr;
+}
- unlock_preempt();
+noreturn void task_init(void)
+{
+ struct kc_thread boot_thread;
+ boot_thread.status = RUNNING;
+ current_thread = &boot_thread;
- lock_scheduler();
- task_schedule();
- unlock_scheduler();
+ timesource = &pit8253_timer_source;
+ timesource->append_callback(sleeping_thread_callback);
+ timesource->start();
+ printf(
+ "starting task management, timesource delta %luns\n",
+ timesource->nanoseconds_delta());
- return 0;
+ idle_thread = create_thread(idle_thread_entry, nullptr);
+ struct kc_thread *sleepy_thread = create_thread(sleepy_thread_entry, (void *)3000000000);
+ struct kc_thread *sleepy_thread2 = create_thread(sleepy_thread_entry, (void *)5000000000);
+ struct kc_thread *waiting_thread = create_thread(waiting_thread_test, nullptr);
+ thread_queue_push(&ready_queue, sleepy_thread);
+ thread_queue_push(&ready_queue, sleepy_thread2);
+ thread_queue_push_back(&ready_queue, waiting_thread);
+ __asm__ volatile ("movq %%rsp, %0" : "=g"(boot_thread.kernel_stack_pointer) :);
+ thread_queue_push(&ready_queue, idle_thread);
+ block_thread(BLOCKED);
+ // shouldn't ever get here
+ printf("the idle thread exited somehow. we're back in the boot thread. this is not good.\n");
+ PANIC(DEAD_END);
}
+
diff --git a/kc/core/task.h b/kc/core/task.h
index bea4756..5d9f39f 100644
--- a/kc/core/task.h
+++ b/kc/core/task.h
@@ -4,34 +4,39 @@
enum kc_thread_status
{
+ AVAILABLE,
+ CREATED,
READY,
RUNNING,
SLEEPING,
BLOCKED,
+ WAITING,
TERMINATED
};
-struct kc_thread_state
+union kc_thread_result
{
- uint64_t stack;
- uint64_t stack_top;
- uint64_t page_map;
+ uint64_t scalar;
+ void *pointer;
};
struct kc_thread
{
- struct kc_thread *next;
- uint64_t time_elapsed;
- uint64_t sleep_expiration;
- enum kc_thread_status status;
- struct kc_thread_state state;
+ void *kernel_stack_head;
+ void *kernel_stack_pointer;
+ uint64_t time_elapsed;
+ union kc_thread_result result;
+ enum kc_thread_status status;
+ struct kc_thread *next;
+ union
+ {
+ uint64_t sleep_expiration;
+ struct kc_thread *wait_target;
+ };
};
-extern void cpu_set_thread(
- struct kc_thread_state *current,
- struct kc_thread_state *next,
- uint64_t *cpu_tss_rsp0);
-
void task_init(void);
-void task_schedule(void);
+
+void kct_terminate(union kc_thread_result result);
+union kc_thread_result kct_wait(struct kc_thread *target);
diff --git a/kc/core/video.c b/kc/core/video.c
index 6d89c08..a3bdce2 100644
--- a/kc/core/video.c
+++ b/kc/core/video.c
@@ -46,8 +46,8 @@
#include <stdbool.h>
-#include <lib/kstring.h>
-#include <lib/kstdio.h>
+#include <libc/string.h>
+#include <libc/stdio.h>
#include <lib/numeric.h>
#include <kernel/entry.h>
@@ -227,7 +227,7 @@ int video_init(void)
}
}
- kprintf("video output %ix%i pixels, %i bytes per line, %s 32 bytes per pixel\n",
+ printf("video output %ix%i pixels, %i bytes per line, %s 32 bytes per pixel\n",
boot_data->width, boot_data->height, boot_data->pitch, video_format_name);
diff --git a/kc/core/vm_tree.c b/kc/core/vm_tree.c
index dd3667e..72affe8 100644
--- a/kc/core/vm_tree.c
+++ b/kc/core/vm_tree.c
@@ -31,8 +31,8 @@
#include "vm_tree.h"
#include "panic.h"
-#include <lib/kstdio.h>
-#include <lib/kstring.h>
+#include <libc/stdio.h>
+#include <libc/string.h>
#define assert(expr)
@@ -44,92 +44,92 @@
static int compare(uintptr_t a1, size_t s1, uintptr_t a2, size_t s2)
{
- // case 1: a1:a1+s1 occupies a region entirely below a2
- // and is therefore less than.
- if ((a1 + s1) <= a2)
- {
- return -1;
- }
- // case 2: a1:a1+s1 occupies a region entirely above (a2+s2)
- // and is therefore greater than.
- else if (a1 >= (a2 + s2))
- {
- return 1;
- }
- // case 3: the above conditions are not satisfied and therefore
- // the regions overlap and are considered equivalent.
- return 0;
+ // case 1: a1:a1+s1 occupies a region entirely below a2
+ // and is therefore less than.
+ if ((a1 + s1) <= a2)
+ {
+ return -1;
+ }
+ // case 2: a1:a1+s1 occupies a region entirely above (a2+s2)
+ // and is therefore greater than.
+ else if (a1 >= (a2 + s2))
+ {
+ return 1;
+ }
+ // case 3: the above conditions are not satisfied and therefore
+ // the regions overlap and are considered equivalent.
+ return 0;
}
static int compare_key(struct vm_tree_key const * const k1,
- struct vm_tree_key const * const k2)
+ struct vm_tree_key const * const k2)
{
- return compare(k1->address, k1->size, k2->address, k2->size);
+ return compare(k1->address, k1->size, k2->address, k2->size);
}
void vmt_init_node(
- struct vm_tree *tree,
- struct vm_tree_node *node,
- struct vm_object *object,
- void *base,
- void *head)
+ struct vm_tree *tree,
+ struct vm_tree_node *node,
+ struct vm_object *object,
+ void *base,
+ void *head)
{
- memset(node, 0, sizeof(*node));
- node->key =
- (struct vm_tree_key)
- {
- (uintptr_t)base,
- (uintptr_t)head - (uintptr_t)base
- };
+ memset(node, 0, sizeof(*node));
+ node->key =
+ (struct vm_tree_key)
+ {
+ (uintptr_t)base,
+ (uintptr_t)head - (uintptr_t)base
+ };
- struct vm_tree_node *ek = NULL;
- if (!(ek = vmt_search_key(tree, &node->key)))
- {
- struct vm_tree_node *p = vmn_predecessor_key(
- tree->root,
- &node->key);
- if (!p)
- {
- // the tree root should be in place of a missing predecessor
- p = tree->root;
- }
- vmt_insert(
- tree,
- node,
- p,
- vmn_child_direction(node, p));
- node->object = object;
- }
- else
- {
- kprintf("fatal: attempt to insert overlapping vm node\n"
- "node 1: %p: %p @ %zu bytes\n"
- "node 2: %p: %p @ %zu bytes\n",
- node->key.address, node->key.size,
- ek->key.address, ek->key.size);
-
- PANIC(GENERAL_PANIC);
- }
+ struct vm_tree_node *ek = NULL;
+ if (!(ek = vmt_search_key(tree, &node->key)))
+ {
+ struct vm_tree_node *p = vmn_predecessor_key(
+ tree->root,
+ &node->key);
+ if (!p)
+ {
+ // the tree root should be in place of a missing predecessor
+ p = tree->root;
+ }
+ vmt_insert(
+ tree,
+ node,
+ p,
+ vmn_child_direction(node, p));
+ node->object = object;
+ }
+ else
+ {
+ printf("fatal: attempt to insert overlapping vm node\n"
+ "node 1: %p: %p @ %zu bytes\n"
+ "node 2: %p: %p @ %zu bytes\n",
+ node->key.address, node->key.size,
+ ek->key.address, ek->key.size);
+
+ PANIC(GENERAL_PANIC);
+ }
}
static struct vm_tree_node* RotateDirRoot(
- struct vm_tree* T, // red–black tree
- struct vm_tree_node* P, // root of subtree (may be the root of T)
- enum vm_tree_direction dir) { // dir ∈ { LEFT, RIGHT }
- struct vm_tree_node* G = P->parent;
- struct vm_tree_node* S = P->child[1-dir];
- struct vm_tree_node* C;
- assert(S != NIL); // pointer to true node required
- C = S->child[dir];
- P->child[1-dir] = C; if (C != NIL) C->parent = P;
- S->child[ dir] = P; P->parent = S;
- S->parent = G;
- if (G != NULL)
- G->child[ P == G->right ? RIGHT : LEFT ] = S;
- else
- T->root = S;
- return S; // new root of subtree
+ struct vm_tree* T, // red–black tree
+ struct vm_tree_node* P, // root of subtree (may be the root of T)
+ enum vm_tree_direction dir) { // dir ∈ { LEFT, RIGHT }
+ struct vm_tree_node* G = P->parent;
+ struct vm_tree_node* S = P->child[1-dir];
+ struct vm_tree_node* C;
+ assert(S != NIL); // pointer to true node required
+ C = S->child[dir];
+ P->child[1-dir] = C; if (C != NIL) C->parent = P;
+ S->child[ dir] = P; P->parent = S;
+ S->parent = G;
+ if (G != NULL)
+ G->child[ P == G->right ? RIGHT : LEFT ] = S;
+ else
+ T->root = S;
+ return S; // new root of subtree
}
#define RotateDir(N,dir) RotateDirRoot(T,N,dir)
@@ -137,251 +137,251 @@ static struct vm_tree_node* RotateDirRoot(
#define RotateRight(N) RotateDirRoot(T,N,RIGHT)
void vmt_insert(
- struct vm_tree* T, // -> red–black tree
- struct vm_tree_node* N, // -> node to be inserted
- struct vm_tree_node* P, // -> parent node of N ( may be NULL )
- enum vm_tree_direction dir) // side ( LEFT or RIGHT ) of P where to insert N
+ struct vm_tree* T, // -> red–black tree
+ struct vm_tree_node* N, // -> node to be inserted
+ struct vm_tree_node* P, // -> parent node of N ( may be NULL )
+ enum vm_tree_direction dir) // side ( LEFT or RIGHT ) of P where to insert N
{
- struct vm_tree_node* G; // -> parent node of P
- struct vm_tree_node* U; // -> uncle of N
+ struct vm_tree_node* G; // -> parent node of P
+ struct vm_tree_node* U; // -> uncle of N
- N->color = RED;
- N->left = NIL;
- N->right = NIL;
- N->parent = P;
- if (P == NULL) { // There is no parent
- T->root = N; // N is the new root of the tree T.
- return; // insertion complete
- }
- P->child[dir] = N; // insert N as dir-child of P
- // start of the (do while)-loop:
- do {
- if (P->color == BLACK) {
- // Case_I1 (P black):
- return; // insertion complete
- }
- // From now on P is red.
- if ((G = P->parent) == NULL)
- goto Case_I4; // P red and root
- // else: P red and G!=NULL.
- dir = childDir(P); // the side of parent G on which node P is located
- U = G->child[1-dir]; // uncle
- if (U == NIL || U->color == BLACK) // considered black
- goto Case_I56; // P red && U black
- // Case_I2 (P+U red):
- P->color = BLACK;
- U->color = BLACK;
- G->color = RED;
- N = G; // new current node
- // iterate 1 black level higher
- // (= 2 tree levels)
- } while ((P = N->parent) != NULL);
- // end of the (do while)-loop
- // Leaving the (do while)-loop (after having fallen through from Case_I2).
- // Case_I3: N is the root and red.
- return; // insertion complete
+ N->color = RED;
+ N->left = NIL;
+ N->right = NIL;
+ N->parent = P;
+ if (P == NULL) { // There is no parent
+ T->root = N; // N is the new root of the tree T.
+ return; // insertion complete
+ }
+ P->child[dir] = N; // insert N as dir-child of P
+ // start of the (do while)-loop:
+ do {
+ if (P->color == BLACK) {
+ // Case_I1 (P black):
+ return; // insertion complete
+ }
+ // From now on P is red.
+ if ((G = P->parent) == NULL)
+ goto Case_I4; // P red and root
+ // else: P red and G!=NULL.
+ dir = childDir(P); // the side of parent G on which node P is located
+ U = G->child[1-dir]; // uncle
+ if (U == NIL || U->color == BLACK) // considered black
+ goto Case_I56; // P red && U black
+ // Case_I2 (P+U red):
+ P->color = BLACK;
+ U->color = BLACK;
+ G->color = RED;
+ N = G; // new current node
+ // iterate 1 black level higher
+ // (= 2 tree levels)
+ } while ((P = N->parent) != NULL);
+ // end of the (do while)-loop
+ // Leaving the (do while)-loop (after having fallen through from Case_I2).
+ // Case_I3: N is the root and red.
+ return; // insertion complete
Case_I4: // P is the root and red:
- P->color = BLACK;
- return; // insertion complete
+ P->color = BLACK;
+ return; // insertion complete
Case_I56: // P red && U black:
- if (N == P->child[1-dir])
- { // Case_I5 (P red && U black && N inner grandchild of G):
- RotateDir(P,dir); // P is never the root
- N = P; // new current node
- P = G->child[dir]; // new parent of N
- // fall through to Case_I6
- }
- // Case_I6 (P red && U black && N outer grandchild of G):
- RotateDirRoot(T,G,1-dir); // G may be the root
- P->color = BLACK;
- G->color = RED;
- return; // insertion complete
+ if (N == P->child[1-dir])
+ { // Case_I5 (P red && U black && N inner grandchild of G):
+ RotateDir(P,dir); // P is never the root
+ N = P; // new current node
+ P = G->child[dir]; // new parent of N
+ // fall through to Case_I6
+ }
+ // Case_I6 (P red && U black && N outer grandchild of G):
+ RotateDirRoot(T,G,1-dir); // G may be the root
+ P->color = BLACK;
+ G->color = RED;
+ return; // insertion complete
} // end of RBinsert1
void vmt_delete(
- struct vm_tree* T, // -> red–black tree
- struct vm_tree_node* N) // -> node to be deleted
+ struct vm_tree* T, // -> red–black tree
+ struct vm_tree_node* N) // -> node to be deleted
{
- struct vm_tree_node* P = N->parent; // -> parent node of N
- enum vm_tree_direction dir; // side of P on which N is located (∈ { LEFT, RIGHT })
- struct vm_tree_node* S; // -> sibling of N
- struct vm_tree_node* C; // -> close nephew
- struct vm_tree_node* D; // -> distant nephew
+ struct vm_tree_node* P = N->parent; // -> parent node of N
+ enum vm_tree_direction dir; // side of P on which N is located (∈ { LEFT, RIGHT })
+ struct vm_tree_node* S; // -> sibling of N
+ struct vm_tree_node* C; // -> close nephew
+ struct vm_tree_node* D; // -> distant nephew
- // P != NULL, since N is not the root.
- dir = childDir(N); // side of parent P on which the node N is located
- // Replace N at its parent P by NIL:
- P->child[dir] = NIL;
- goto Start_D; // jump into the loop
+ // P != NULL, since N is not the root.
+ dir = childDir(N); // side of parent P on which the node N is located
+ // Replace N at its parent P by NIL:
+ P->child[dir] = NIL;
+ goto Start_D; // jump into the loop
- // start of the (do while)-loop:
- do {
- dir = childDir(N); // side of parent P on which node N is located
+ // start of the (do while)-loop:
+ do {
+ dir = childDir(N); // side of parent P on which node N is located
Start_D:
- S = P->child[1-dir]; // sibling of N (has black height >= 1)
- D = S->child[1-dir]; // distant nephew
- C = S->child[ dir]; // close nephew
- if (S->color == RED)
- goto Case_D3; // S red ===> P+C+D black
- // S is black:
- if (D != NIL && D->color == RED) // not considered black
- goto Case_D6; // D red && S black
- if (C != NIL && C->color == RED) // not considered black
- goto Case_D5; // C red && S+D black
- // Here both nephews are == NIL (first iteration) or black (later).
- if (P->color == RED)
- goto Case_D4; // P red && C+S+D black
- // Case_D1 (P+C+S+D black):
- S->color = RED;
- N = P; // new current node (maybe the root)
- // iterate 1 black level
- // (= 1 tree level) higher
- } while ((P = N->parent) != NULL);
- // end of the (do while)-loop
- // Case_D2 (P == NULL):
- return; // deletion complete
+ S = P->child[1-dir]; // sibling of N (has black height >= 1)
+ D = S->child[1-dir]; // distant nephew
+ C = S->child[ dir]; // close nephew
+ if (S->color == RED)
+ goto Case_D3; // S red ===> P+C+D black
+ // S is black:
+ if (D != NIL && D->color == RED) // not considered black
+ goto Case_D6; // D red && S black
+ if (C != NIL && C->color == RED) // not considered black
+ goto Case_D5; // C red && S+D black
+ // Here both nephews are == NIL (first iteration) or black (later).
+ if (P->color == RED)
+ goto Case_D4; // P red && C+S+D black
+ // Case_D1 (P+C+S+D black):
+ S->color = RED;
+ N = P; // new current node (maybe the root)
+ // iterate 1 black level
+ // (= 1 tree level) higher
+ } while ((P = N->parent) != NULL);
+ // end of the (do while)-loop
+ // Case_D2 (P == NULL):
+ return; // deletion complete
Case_D3: // S red && P+C+D black:
- RotateDirRoot(T,P,dir); // P may be the root
- P->color = RED;
- S->color = BLACK;
- S = C; // != NIL
- // now: P red && S black
- D = S->child[1-dir]; // distant nephew
- if (D != NIL && D->color == RED)
- goto Case_D6; // D red && S black
- C = S->child[ dir]; // close nephew
- if (C != NIL && C->color == RED)
- goto Case_D5; // C red && S+D black
- // Otherwise C+D considered black.
- // fall through to Case_D4
- // Case_D4: // P red && S+C+D black:
- S->color = RED;
- P->color = BLACK;
- return; // deletion complete
+ RotateDirRoot(T,P,dir); // P may be the root
+ P->color = RED;
+ S->color = BLACK;
+ S = C; // != NIL
+ // now: P red && S black
+ D = S->child[1-dir]; // distant nephew
+ if (D != NIL && D->color == RED)
+ goto Case_D6; // D red && S black
+ C = S->child[ dir]; // close nephew
+ if (C != NIL && C->color == RED)
+ goto Case_D5; // C red && S+D black
+ // Otherwise C+D considered black.
+ // fall through to Case_D4
+ // Case_D4: // P red && S+C+D black:
+ S->color = RED;
+ P->color = BLACK;
+ return; // deletion complete
Case_D4: // P red && S+C+D black:
- S->color = RED;
- P->color = BLACK;
- return; // deletion complete
+ S->color = RED;
+ P->color = BLACK;
+ return; // deletion complete
Case_D5: // C red && S+D black:
- RotateDir(S,1-dir); // S is never the root
- S->color = RED;
- C->color = BLACK;
- D = S;
- S = C;
- // now: D red && S black
- // fall through to Case_D6
+ RotateDir(S,1-dir); // S is never the root
+ S->color = RED;
+ C->color = BLACK;
+ D = S;
+ S = C;
+ // now: D red && S black
+ // fall through to Case_D6
Case_D6: // D red && S black:
- RotateDirRoot(T,P,dir); // P may be the root
- S->color = P->color;
- P->color = BLACK;
- D->color = BLACK;
- return; // deletion complete
+ RotateDirRoot(T,P,dir); // P may be the root
+ S->color = P->color;
+ P->color = BLACK;
+ D->color = BLACK;
+ return; // deletion complete
} // end of RBdelete2
enum vm_tree_direction vmn_child_direction(
- struct vm_tree_node *n,
- struct vm_tree_node *p
-)
+ struct vm_tree_node *n,
+ struct vm_tree_node *p
+ )
{
- if (p && (compare_key(&p->key, &n->key) > 0))
- {
- return LEFT;
- }
- return RIGHT;
+ if (p && (compare_key(&p->key, &n->key) > 0))
+ {
+ return LEFT;
+ }
+ return RIGHT;
}
struct vm_tree_node *vmt_search_key(
- struct vm_tree *tree,
- struct vm_tree_key *key)
+ struct vm_tree *tree,
+ struct vm_tree_key *key)
{
- struct vm_tree_node *N = tree->root;
-
- while (N && (compare_key(&N->key, key) != 0))
- {
- if (compare_key(&N->key, key) > 0)
- {
- N = N->left;
- }
- else
- {
- N = N->right;
- }
- }
+ struct vm_tree_node *N = tree->root;
+
+ while (N && (compare_key(&N->key, key) != 0))
+ {
+ if (compare_key(&N->key, key) > 0)
+ {
+ N = N->left;
+ }
+ else
+ {
+ N = N->right;
+ }
+ }
- return N;
+ return N;
}
// search for the predecessor node for a given key
struct vm_tree_node *vmn_predecessor_key(
- struct vm_tree_node *N,
- struct vm_tree_key *key)
+ struct vm_tree_node *N,
+ struct vm_tree_key *key)
{
- struct vm_tree_node *P = NULL;
+ struct vm_tree_node *P = NULL;
- while (N && (compare_key(&N->key, key) != 0))
- {
- if (compare_key(&N->key, key) > 0)
- {
- N = N->left;
- }
- else
- {
- P = N;
- N = N->right;
- }
- }
+ while (N && (compare_key(&N->key, key) != 0))
+ {
+ if (compare_key(&N->key, key) > 0)
+ {
+ N = N->left;
+ }
+ else
+ {
+ P = N;
+ N = N->right;
+ }
+ }
- return P;
+ return P;
}
// search for the successor node for a given key
struct vm_tree_node *vmn_successor_node(
- struct vm_tree_node *N)
+ struct vm_tree_node *N)
{
- if (N && N->right)
- {
- return vmn_min(N->right);
- }
+ if (N && N->right)
+ {
+ return vmn_min(N->right);
+ }
- struct vm_tree_node *p = N->parent;
- while (p && N == p->right)
- {
- N = p;
- p = p->parent;
- }
+ struct vm_tree_node *p = N->parent;
+ while (p && N == p->right)
+ {
+ N = p;
+ p = p->parent;
+ }
- return p;
+ return p;
}
struct vm_tree_node *vmn_min(struct vm_tree_node *node)
{
- while (node && node->left)
- {
- node = node->left;
- }
+ while (node && node->left)
+ {
+ node = node->left;
+ }
- return node;
+ return node;
}
struct vm_tree_node *vmn_max(struct vm_tree_node *node)
{
- while (node && node->right)
- {
- node = node->right;
- }
+ while (node && node->right)
+ {
+ node = node->right;
+ }
- return node;
+ return node;
}
struct vm_object *vmt_get_object(struct vm_tree *tree, void *address)
{
- // find the object for a page.
- struct vm_tree_key key = {(uintptr_t)address, 1};
- struct vm_tree_node *node = vmt_search_key(tree, &key);
- if (node)
- {
- return node->object;
- }
- return NULL;
+ // find the object for a page.
+ struct vm_tree_key key = {(uintptr_t)address, 1};
+ struct vm_tree_node *node = vmt_search_key(tree, &key);
+ if (node)
+ {
+ return node->object;
+ }
+ return NULL;
}