Johannes Zellner пре 8 месеци
родитељ
комит
5af1d74524
8 измењених фајлова са 441 додато и 59 уклоњено
  1. 10 4
      Makefile
  2. 3 9
      kernel.c
  3. 211 0
      process.c
  4. 37 0
      process.h
  5. 40 0
      run_api.h
  6. 61 0
      switch.S
  7. 77 38
      terminal.c
  8. 2 8
      timer.S

+ 10 - 4
Makefile

@@ -20,7 +20,7 @@ all: image.bin final.bin root.img
 boot.o: boot.S
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.o: kernel.c io.h terminal.h timer.h
+kernel.o: kernel.c io.h process.h terminal.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 io.o: io.c io.h fbtext.h
@@ -32,7 +32,7 @@ font_8x8.o: font_8x8.c font_8x8.h
 fbtext.o: fbtext.c fbtext.h font_8x8.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-terminal.o: terminal.c terminal.h io.h fbtext.h rtc.h timer.h disk.h
+terminal.o: terminal.c terminal.h io.h fbtext.h process.h rtc.h timer.h disk.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 hello.o: hello.c io.h
@@ -80,7 +80,13 @@ boot.elf: boot.o
 timer.o: timer.S
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: kernel.o timer.o io.o rtc.o terminal.o hello.o reboot.o disk.o fat.o ls.o cat.o run.o vga.o ati.o font_8x8.o fbtext.o clock.o colors.o display.o
+switch.o: switch.S
+	$(AS) $(ASFLAGS) -o $@ $<
+
+process.o: process.c process.h io.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+kernel.elf: kernel.o timer.o switch.o process.o io.o rtc.o terminal.o hello.o reboot.o disk.o fat.o ls.o cat.o run.o vga.o ati.o font_8x8.o fbtext.o clock.o colors.o display.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 boot.bin: boot.elf
@@ -139,4 +145,4 @@ run: image.bin root.img
 	qemu-system-x86_64 -M pc -drive file=image.bin,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 
 clean:
-	rm -f boot.o kernel.o timer.o io.o rtc.o terminal.o hello.o reboot.o fat.o ls.o cat.o run.o disk.o vga.o ati.o font_8x8.o fbtext.o clock.o colors.o display.o boot.elf kernel.elf boot.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin
+	rm -f boot.o kernel.o timer.o switch.o process.o io.o rtc.o terminal.o hello.o reboot.o fat.o ls.o cat.o run.o disk.o vga.o ati.o font_8x8.o fbtext.o clock.o colors.o display.o boot.elf kernel.elf boot.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin

+ 3 - 9
kernel.c

@@ -1,6 +1,7 @@
-/* Kernel: entry point at 0x7E00, timer (PIT 1 kHz), then run terminal. */
+/* Kernel: entry point at 0x7E00, timer (PIT 1 kHz), process init, terminal. */
 
 #include "io.h"
+#include "process.h"
 #include "terminal.h"
 #include "timer.h"
 
@@ -33,14 +34,6 @@ extern void fdc_irq_stub(void);
 extern void default_irq_stub(void);
 extern unsigned int exc_stub_table[];
 
-void pit_irq(void);
-
-void pit_irq(void)
-{
-	ticks++;
-	outb(0x20, 0x20);
-}
-
 unsigned int get_ticks_ms(void)
 {
 	return ticks;
@@ -133,5 +126,6 @@ void kernel_main(void)
 
 	io_init();
 	timer_init();
+	process_init();
 	terminal_run();
 }

+ 211 - 0
process.c

@@ -0,0 +1,211 @@
+/* Process management: create, exit, round-robin schedule, ps, kill. */
+
+#include "process.h"
+#include "io.h"
+
+struct process procs[MAX_PROCS];
+volatile unsigned int current_pid;
+
+static unsigned int next_pid_counter = 1; /* monotonic, wraps */
+
+/* Stack top for process slot (1..MAX_PROCS-1).  Slot 0 uses bootstrap stack. */
+static unsigned int stack_top_for(unsigned int slot)
+{
+	return PROC_STACK_BASE + slot * PROC_STACK_SIZE;
+}
+
+static void name_copy(char *dst, const char *src)
+{
+	unsigned int i;
+	for (i = 0; i < PROC_NAME_LEN - 1 && src[i]; i++)
+		dst[i] = src[i];
+	dst[i] = '\0';
+}
+
+void process_init(void)
+{
+	unsigned int i;
+	for (i = 0; i < MAX_PROCS; i++)
+		procs[i].state = PROC_UNUSED;
+
+	procs[0].state = PROC_RUNNING;
+	procs[0].pid   = 0;
+	name_copy(procs[0].name, "terminal");
+	current_pid = 0;
+}
+
+/*
+ * Build initial stack frame for a new process so that popa + iret
+ * "returns" to the entry point.  For arg-taking entries the argument
+ * string is copied onto the stack and a pointer to it passed as the
+ * first C parameter.
+ *
+ * Stack layout (high to low):
+ *
+ *   [copied arg string, if any, rounded up to 4-byte boundary]
+ *   arg pointer           -- first C parameter (only if has_arg)
+ *   process_exit address  -- return address seen by the entry function
+ *   EFLAGS  (0x202)       -- IF=1
+ *   CS      (0x08)
+ *   EIP     (entry)       -- iret target
+ *   EAX  ECX  EDX  EBX  ESP_orig  EBP  ESI  EDI   (pusha frame)
+ *   <- saved ESP
+ */
+static int setup_process(const char *name, unsigned int entry,
+			 int has_arg, const char *arg)
+{
+	unsigned int slot, top, *sp, arg_ptr = 0;
+
+	for (slot = 1; slot < MAX_PROCS; slot++)
+		if (procs[slot].state == PROC_UNUSED)
+			break;
+	if (slot == MAX_PROCS)
+		return -1;
+
+	top = stack_top_for(slot);
+
+	sp = (unsigned int *)top;
+
+	if (has_arg && arg) {
+		unsigned int len, aligned, i;
+		char *dst;
+		for (len = 0; arg[len]; len++)
+			;
+		len++;
+		aligned = (len + 3) & ~3u;
+		sp = (unsigned int *)((unsigned int)sp - aligned);
+		dst = (char *)sp;
+		for (i = 0; i < len; i++)
+			dst[i] = arg[i];
+		for (; i < aligned; i++)
+			dst[i] = '\0';
+		arg_ptr = (unsigned int)sp;
+	}
+
+	if (has_arg)
+		*--sp = arg_ptr;
+	*--sp = (unsigned int)process_exit;
+	*--sp = 0x202;          /* EFLAGS: IF=1 */
+	*--sp = 0x08;           /* CS */
+	*--sp = entry;          /* EIP */
+	*--sp = 0;              /* EAX */
+	*--sp = 0;              /* ECX */
+	*--sp = 0;              /* EDX */
+	*--sp = 0;              /* EBX */
+	*--sp = 0;              /* ESP (ignored by popa) */
+	*--sp = 0;              /* EBP */
+	*--sp = 0;              /* ESI */
+	*--sp = 0;              /* EDI */
+
+	procs[slot].esp   = (unsigned int)sp;
+	procs[slot].state = PROC_READY;
+	procs[slot].pid   = next_pid_counter++;
+	name_copy(procs[slot].name, name);
+
+	return (int)procs[slot].pid;
+}
+
+int process_create(const char *name, void (*entry)(void))
+{
+	return setup_process(name, (unsigned int)entry, 0, (void *)0);
+}
+
+int process_create_arg(const char *name, void (*entry)(const char *),
+		       const char *arg)
+{
+	return setup_process(name, (unsigned int)entry, 1, arg);
+}
+
+void process_exit(void)
+{
+	procs[current_pid].state = PROC_DEAD;
+	for (;;)
+		__asm__ volatile ("hlt");
+}
+
+/*
+ * Round-robin scheduler.  Called from the PIT IRQ stub with interrupts
+ * disabled.  Picks the next runnable process and updates current_pid.
+ * The caller (switch.S) takes care of actually switching ESP.
+ */
+void schedule(void)
+{
+	unsigned int i, next;
+
+	/* Clean up dead processes. */
+	for (i = 0; i < MAX_PROCS; i++)
+		if (procs[i].state == PROC_DEAD)
+			procs[i].state = PROC_UNUSED;
+
+	/* Mark current as READY (it was RUNNING). */
+	if (procs[current_pid].state == PROC_RUNNING)
+		procs[current_pid].state = PROC_READY;
+
+	/* Find next runnable slot. */
+	next = current_pid;
+	for (i = 0; i < MAX_PROCS; i++) {
+		next = (next + 1) % MAX_PROCS;
+		if (procs[next].state == PROC_READY) {
+			procs[next].state = PROC_RUNNING;
+			current_pid = next;
+			return;
+		}
+	}
+
+	/* Nothing else runnable -- stay on current if still alive. */
+	if (procs[current_pid].state == PROC_READY) {
+		procs[current_pid].state = PROC_RUNNING;
+		return;
+	}
+
+	/* Everything dead: fall back to slot 0 (terminal). */
+	procs[0].state = PROC_RUNNING;
+	current_pid = 0;
+}
+
+/* ---- user-facing helpers ---- */
+
+static const char *state_str(unsigned int s)
+{
+	switch (s) {
+	case PROC_RUNNING: return "run  ";
+	case PROC_READY:   return "ready";
+	default:           return "?    ";
+	}
+}
+
+void process_ps(void)
+{
+	unsigned int i;
+	io_putstr("PID  STATE  NAME\n");
+	for (i = 0; i < MAX_PROCS; i++) {
+		if (procs[i].state == PROC_UNUSED || procs[i].state == PROC_DEAD)
+			continue;
+		io_putchar(' ');
+		if (procs[i].pid < 10)
+			io_putchar(' ');
+		if (procs[i].pid >= 10)
+			io_putchar((char)('0' + procs[i].pid / 10));
+		io_putchar((char)('0' + procs[i].pid % 10));
+		io_putstr("  ");
+		io_putstr(state_str(procs[i].state));
+		io_putstr("  ");
+		io_putstr(procs[i].name);
+		io_putchar('\n');
+	}
+}
+
+int process_kill(unsigned int pid)
+{
+	unsigned int i;
+	if (pid == 0)
+		return -1; /* cannot kill terminal */
+	for (i = 1; i < MAX_PROCS; i++) {
+		if (procs[i].state != PROC_UNUSED && procs[i].state != PROC_DEAD &&
+		    procs[i].pid == pid) {
+			procs[i].state = PROC_DEAD;
+			return 0;
+		}
+	}
+	return -1;
+}

+ 37 - 0
process.h

@@ -0,0 +1,37 @@
+/* Preemptive round-robin multitasking for i586, ring-0 only. */
+#ifndef PROCESS_H
+#define PROCESS_H
+
+#define MAX_PROCS       8
+#define PROC_STACK_SIZE 0x1000  /* 4 KB per process */
+#define PROC_STACK_BASE 0x40000 /* process 1 stack bottom; process 0 uses bootstrap stack */
+
+#define PROC_UNUSED  0
+#define PROC_READY   1
+#define PROC_RUNNING 2
+#define PROC_DEAD    3
+
+#define TIMESLICE_TICKS 20 /* context switch every 20 ms (PIT @ 1 kHz) */
+
+#define PROC_NAME_LEN 12
+
+struct process {
+	unsigned int esp;
+	unsigned int state;
+	unsigned int pid;
+	char         name[PROC_NAME_LEN];
+};
+
+extern struct process procs[MAX_PROCS];
+extern volatile unsigned int current_pid;
+
+void process_init(void);
+int  process_create(const char *name, void (*entry)(void));
+int  process_create_arg(const char *name, void (*entry)(const char *),
+			const char *arg);
+void process_exit(void);
+void schedule(void);
+void process_ps(void);
+int  process_kill(unsigned int pid);
+
+#endif

+ 40 - 0
run_api.h

@@ -0,0 +1,40 @@
+/* API passed to loaded program at PROGRAM_API_ADDR. Used by run command and by programs run via run (e.g. prog, space). */
+
+#ifndef RUN_API_H
+#define RUN_API_H
+
+#define PROGRAM_API_ADDR 0x20F00
+#define IO_KEY_ESC       0x1B
+#define IO_KEY_SPACE     0x20
+#define IO_KEY_LEFT      0x100
+#define IO_KEY_RIGHT     0x101
+
+/* Function pointer types for the program API. */
+typedef void (*prog_draw_string_xy_t)(unsigned int x0, unsigned int y0,
+	const char *str, unsigned int r_fg, unsigned int g_fg, unsigned int b_fg,
+	int transparent_bg);
+typedef unsigned int (*prog_get_cols_t)(void);
+typedef unsigned int (*prog_get_rows_t)(void);
+typedef int (*prog_poll_key_t)(void);
+typedef int (*prog_poll_key_with_hw_t)(void);
+typedef unsigned int (*prog_get_fb_width_t)(void);
+typedef unsigned int (*prog_get_fb_height_t)(void);
+typedef void (*prog_clear_rgb_t)(unsigned int r, unsigned int g, unsigned int b);
+typedef void (*prog_put_pixel_rgb_t)(unsigned int x, unsigned int y,
+	unsigned int r, unsigned int g, unsigned int b);
+typedef unsigned int (*prog_get_ticks_ms_t)(void);
+
+struct prog_api {
+	prog_draw_string_xy_t draw_string_xy;
+	prog_get_cols_t       get_cols;
+	prog_get_rows_t       get_rows;
+	prog_poll_key_t       poll_key;
+	prog_poll_key_with_hw_t poll_key_with_hw;
+	prog_get_fb_width_t   get_fb_width;
+	prog_get_fb_height_t  get_fb_height;
+	prog_clear_rgb_t      clear_rgb;
+	prog_put_pixel_rgb_t  put_pixel_rgb;
+	prog_get_ticks_ms_t   get_ticks_ms;
+};
+
+#endif

+ 61 - 0
switch.S

@@ -0,0 +1,61 @@
+/*
+ * Context-switch PIT IRQ stub.
+ *
+ * On entry the CPU has already pushed EFLAGS, CS, EIP onto the
+ * current process's stack.  We save the rest, bump the tick counter,
+ * and -- when the timeslice expires -- call schedule() and swap ESP
+ * to the next process.
+ */
+.code32
+.text
+
+.extern ticks
+.extern current_pid
+.extern procs
+.extern schedule
+
+/* struct process offsets (must match process.h / process.c) */
+.equ PCB_ESP,   0
+.equ PCB_SIZE,  24      /* sizeof(struct process): 4+4+4+12 = 24 */
+
+.equ TIMESLICE, 20
+
+.globl pit_irq_stub
+pit_irq_stub:
+	pusha
+
+	/* ticks++ and send EOI -- always, even when we don't switch. */
+	incl  ticks
+	movb  $0x20, %al
+	outb  %al, $0x20
+
+	/* Decrement timeslice counter; switch only when it reaches 0. */
+	decl  slice_counter
+	jnz   .no_switch
+
+	/* Reset counter for next timeslice. */
+	movl  $TIMESLICE, slice_counter
+
+	/* Save current ESP into procs[current_pid].esp */
+	movl  current_pid, %eax
+	imull $PCB_SIZE, %eax
+	leal  procs(%eax), %ebx
+	movl  %esp, PCB_ESP(%ebx)
+
+	/* Let the C scheduler pick the next process. */
+	call  schedule
+
+	/* Load new ESP from procs[current_pid].esp */
+	movl  current_pid, %eax
+	imull $PCB_SIZE, %eax
+	leal  procs(%eax), %ebx
+	movl  PCB_ESP(%ebx), %esp
+
+.no_switch:
+	popa
+	iret
+
+.data
+.align 4
+slice_counter:
+	.long TIMESLICE

+ 77 - 38
terminal.c

@@ -1,7 +1,9 @@
-/* Terminal: prompt, datetime (top right), blinking cursor, echo loop, command dispatch. */
+/* Terminal: prompt, datetime (top right), blinking cursor, echo loop, command dispatch.
+   Commands are spawned as separate processes for preemptive multitasking. */
 
 #include "io.h"
 #include "fbtext.h"
+#include "process.h"
 #include "rtc.h"
 #include "terminal.h"
 #include "timer.h"
@@ -283,6 +285,49 @@ static int is_cmd_clear(const char *line, unsigned int line_len)
 	return (i == line_len);
 }
 
+static int is_cmd_ps(const char *line, unsigned int line_len)
+{
+	unsigned int i = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 2 > line_len)
+		return 0;
+	if (line[i] != 'p' || line[i+1] != 's')
+		return 0;
+	i += 2;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+static int is_cmd_kill(const char *line, unsigned int line_len, unsigned int *pid_out)
+{
+	unsigned int i = 0, num = 0;
+	int has_digit = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 4 > line_len)
+		return 0;
+	if (line[i] != 'k' || line[i+1] != 'i' || line[i+2] != 'l' || line[i+3] != 'l')
+		return 0;
+	i += 4;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	while (i < line_len && line[i] >= '0' && line[i] <= '9') {
+		num = num * 10 + (unsigned int)(line[i] - '0');
+		has_digit = 1;
+		i++;
+	}
+	if (!has_digit)
+		return 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i != line_len)
+		return 0;
+	*pid_out = num;
+	return 1;
+}
+
 /* Redraw line from index `from` to end, clear one cell after, set cursor to line_pos. */
 static void redraw_line_from(const char *line, unsigned int line_len,
 	unsigned int line_pos, unsigned int line_start, unsigned int from)
@@ -430,63 +475,57 @@ void terminal_run(void)
 					}
 				} else if (k == '\n') {
 					static char cat_fname[CAT_FNAME_MAX];
-					unsigned int drive_sel;
+					unsigned int drive_sel, kill_pid;
 					int skip_prompt = 0;
 					io_putchar('\n');
 					history_push(line, line_len);
 					history_browse = 0;
 					if (is_cmd_hello(line, line_len)) {
-						program_hello_main();
-						io_drain_keyboard();
-						draw_header_row();
+						if (process_create("hello", program_hello_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_reboot(line, line_len)) {
 						program_reboot_main();
 					} else if (is_cmd_ls(line, line_len)) {
-						program_ls_main();
-						io_drain_keyboard();
-						draw_header_row();
+						if (process_create("ls", program_ls_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_clock(line, line_len)) {
-						program_clock_main();
-						io_drain_keyboard();
-						io_clear_screen();
-						draw_header_row();
+						if (process_create("clock", program_clock_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_colors(line, line_len)) {
-						program_colors_main();
-						io_drain_keyboard();
-						io_clear_screen();
-						draw_header_row();
+						if (process_create("colors", program_colors_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_cat(line, line_len, cat_fname, CAT_FNAME_MAX)) {
-						program_cat_main(cat_fname);
-						io_drain_keyboard();
-						draw_header_row();
+						if (process_create_arg("cat", program_cat_main, cat_fname) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_run(line, line_len, cat_fname, CAT_FNAME_MAX)) {
-						program_run_main(cat_fname);
-						io_drain_keyboard();
-						draw_header_row();
+						if (process_create_arg("run", program_run_main, cat_fname) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_space(line, line_len)) {
-						program_run_main("space.bin");
-						io_drain_keyboard();
-						draw_header_row();
+						if (process_create_arg("space", program_run_main, "space.bin") < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_display(line, line_len)) {
-						program_display_main();
+						if (process_create("display", program_display_main) < 0)
+							io_putstr("error: too many processes\n");
 					} else if (is_cmd_drive(line, line_len, &drive_sel)) {
 						disk_set_drive(drive_sel);
 						io_putstr("drive ");
 						io_putchar((char)('0' + disk_get_drive()));
 						io_putstr(" selected\n");
+					} else if (is_cmd_ps(line, line_len)) {
+						process_ps();
+					} else if (is_cmd_kill(line, line_len, &kill_pid)) {
+						if (process_kill(kill_pid) < 0)
+							io_putstr("kill: no such process\n");
+						else
+							io_putstr("killed\n");
 					} else if (is_cmd_help(line, line_len)) {
-						io_putstr("hello\n");
-						io_putstr("reboot\n");
-						io_putstr("ls\n");
-						io_putstr("clock\n");
-						io_putstr("colors\n");
-						io_putstr("cat <file>\n");
-						io_putstr("run <file>\n");
-						io_putstr("space\n");
-						io_putstr("display\n");
-						io_putstr("drive <0|1>\n");
-						io_putstr("help\n");
-						io_putstr("clear\n");
+						io_putstr("hello     reboot\n");
+						io_putstr("ls        cat <file>\n");
+						io_putstr("run <file>  space\n");
+						io_putstr("clock     colors\n");
+						io_putstr("display   drive <0|1>\n");
+						io_putstr("ps        kill <pid>\n");
+						io_putstr("help      clear\n");
 					} else if (is_cmd_clear(line, line_len)) {
 						io_clear_screen();
 						draw_header_row();

+ 2 - 8
timer.S

@@ -1,14 +1,8 @@
-/* IRQ stubs: save state, call C handler, restore, iret. */
+/* IRQ stubs: save state, call C handler, restore, iret.
+   PIT stub (pit_irq_stub) lives in switch.S for context switching. */
 .code32
 .text
 
-.globl pit_irq_stub
-pit_irq_stub:
-	pusha
-	call  pit_irq
-	popa
-	iret
-
 .globl kbd_irq_stub
 kbd_irq_stub:
 	pusha