1 /* tag: x86 context switching
3 * 2003-10 by SONE Takeshi
5 * See the file "COPYING" for further information about
6 * the copyright and warranty status of this work.
10 #include "kernel/kernel.h"
13 #include "libopenbios/sys_info.h"
17 #define MAIN_STACK_SIZE 16384
18 #define IMAGE_STACK_SIZE 4096
22 static void start_main(void); /* forward decl. */
23 void __exit_context(void); /* assembly routine */
26 * Main context structure
27 * It is placed at the bottom of our stack, and loaded by assembly routine
30 static struct context main_ctx __attribute__((section (".initctx"))) = {
31 .gdt_base = (uint32_t) gdt,
32 .gdt_limit = GDT_LIMIT,
39 .esp = (uint32_t) ESP_LOC(&main_ctx),
40 .eip = (uint32_t) start_main,
41 .return_addr = (uint32_t) __exit_context,
44 /* This is used by assembly routine to load/store the context which
45 * it is to switch/switched. */
46 struct context *__context = &main_ctx;
48 /* Stack for loaded ELF image */
49 static uint8_t image_stack[IMAGE_STACK_SIZE];
51 /* Pointer to startup context (physical address) */
52 unsigned long __boot_ctx;
56 * This is the C function that runs first.
58 static void start_main(void)
62 /* Save startup context, so we can refer to it later.
63 * We have to keep it in physical address since we will relocate. */
64 __boot_ctx = virt_to_phys(__context);
67 /* Start the real fun */
70 /* Pass return value to startup context. Bootloader may see it. */
71 boot_ctx->eax = retval;
73 /* Returning from here should jump to __exit_context */
77 /* Setup a new context using the given stack.
80 init_context(uint8_t *stack, uint32_t stack_size, int num_params)
84 ctx = (struct context *)
85 (stack + stack_size - (sizeof(*ctx) + num_params*sizeof(uint32_t)));
86 memset(ctx, 0, sizeof(*ctx));
88 /* Fill in reasonable default for flat memory model */
89 ctx->gdt_base = virt_to_phys(gdt);
90 ctx->gdt_limit = GDT_LIMIT;
97 ctx->esp = virt_to_phys(ESP_LOC(ctx));
98 ctx->return_addr = virt_to_phys(__exit_context);
103 /* Switch to another context. */
104 struct context *switch_to(struct context *ctx)
106 struct context *save, *ret;
108 debug("switching to new context:\n");
111 asm ("pushl %cs; call __switch_context");
117 /* Start ELF Boot image */
118 unsigned int start_elf(unsigned long entry_point, unsigned long param)
122 ctx = init_context(image_stack, sizeof image_stack, 1);
123 ctx->eip = entry_point;
124 ctx->param[0] = param;
125 ctx->eax = 0xe1fb007;
128 ctx = switch_to(ctx);