x86: Fixes bug preventing the kernel from trapping
[akaros.git] / kern / arch / i686 / trap.c
1 #ifdef __SHARC__
2 #pragma nosharc
3 #define SINIT(x) x
4 #endif
5
6 #include <arch/mmu.h>
7 #include <arch/x86.h>
8 #include <arch/arch.h>
9 #include <arch/console.h>
10 #include <arch/apic.h>
11 #include <ros/common.h>
12 #include <smp.h>
13 #include <assert.h>
14 #include <pmap.h>
15 #include <trap.h>
16 #include <monitor.h>
17 #include <process.h>
18 #include <mm.h>
19 #include <stdio.h>
20 #include <slab.h>
21 #include <syscall.h>
22
23 taskstate_t RO ts;
24
25 /* Interrupt descriptor table.  (Must be built at run time because
26  * shifted function addresses can't be represented in relocation records.)
27  */
28 // Aligned on an 8 byte boundary (SDM V3A 5-13)
29 gatedesc_t __attribute__ ((aligned (8))) (RO idt)[256] = { { 0 } };
30 pseudodesc_t RO idt_pd = {
31         sizeof(idt) - 1, (uint32_t) idt
32 };
33
34 /* global handler table, used by core0 (for now).  allows the registration
35  * of functions to be called when servicing an interrupt.  other cores
36  * can set up their own later.
37  */
38 #ifdef __IVY__
39 #pragma cilnoremove("iht_lock")
40 #endif
41 spinlock_t iht_lock;
42 handler_t TP(TV(t)) LCKD(&iht_lock) (RO interrupt_handlers)[NUM_INTERRUPT_HANDLERS];
43
44 static const char *NTS trapname(int trapno)
45 {
46     // zra: excnames is SREADONLY because Ivy doesn't trust const
47         static const char *NT const (RO excnames)[] = {
48                 "Divide error",
49                 "Debug",
50                 "Non-Maskable Interrupt",
51                 "Breakpoint",
52                 "Overflow",
53                 "BOUND Range Exceeded",
54                 "Invalid Opcode",
55                 "Device Not Available",
56                 "Double Fault",
57                 "Coprocessor Segment Overrun",
58                 "Invalid TSS",
59                 "Segment Not Present",
60                 "Stack Fault",
61                 "General Protection",
62                 "Page Fault",
63                 "(unknown trap)",
64                 "x87 FPU Floating-Point Error",
65                 "Alignment Check",
66                 "Machine-Check",
67                 "SIMD Floating-Point Exception"
68         };
69
70         if (trapno < sizeof(excnames)/sizeof(excnames[0]))
71                 return excnames[trapno];
72         if (trapno == T_SYSCALL)
73                 return "System call";
74         return "(unknown trap)";
75 }
76
77
78 void
79 idt_init(void)
80 {
81         extern segdesc_t (RO gdt)[];
82
83         // This table is made in trapentry.S by each macro in that file.
84         // It is layed out such that the ith entry is the ith's traphandler's
85         // (uint32_t) trap addr, then (uint32_t) trap number
86         struct trapinfo { uint32_t trapaddr; uint32_t trapnumber; };
87         extern struct trapinfo (BND(__this,trap_tbl_end) RO trap_tbl)[];
88         extern struct trapinfo (SNT RO trap_tbl_end)[];
89         int i, trap_tbl_size = trap_tbl_end - trap_tbl;
90         extern void ISR_default(void);
91
92         // set all to default, to catch everything
93         for(i = 0; i < 256; i++)
94                 ROSETGATE(idt[i], 0, GD_KT, &ISR_default, 0);
95
96         // set all entries that have real trap handlers
97         // we need to stop short of the last one, since the last is the default
98         // handler with a fake interrupt number (500) that is out of bounds of
99         // the idt[]
100         // if we set these to trap gates, be sure to handle the IRQs separately
101         // and we might need to break our pretty tables
102         for(i = 0; i < trap_tbl_size - 1; i++)
103                 ROSETGATE(idt[trap_tbl[i].trapnumber], 0, GD_KT, trap_tbl[i].trapaddr, 0);
104
105         // turn on syscall handling and other user-accessible ints
106         // DPL 3 means this can be triggered by the int instruction
107         // STS_TG32 sets the IDT type to a Trap Gate (interrupts enabled)
108         idt[T_SYSCALL].gd_dpl = SINIT(3);
109         idt[T_SYSCALL].gd_type = SINIT(STS_TG32);
110         idt[T_BRKPT].gd_dpl = SINIT(3);
111
112         // Setup a TSS so that we get the right stack
113         // when we trap to the kernel.
114         ts.ts_esp0 = SINIT(KSTACKTOP);
115         ts.ts_ss0 = SINIT(GD_KD);
116
117         // Initialize the TSS field of the gdt.
118         SEG16ROINIT(gdt[GD_TSS >> 3],STS_T32A, (uint32_t)(&ts),sizeof(taskstate_t),0);
119         //gdt[GD_TSS >> 3] = (segdesc_t)SEG16(STS_T32A, (uint32_t) (&ts),
120         //                                 sizeof(taskstate_t), 0);
121         gdt[GD_TSS >> 3].sd_s = SINIT(0);
122
123         // Load the TSS
124         ltr(GD_TSS);
125
126         // Load the IDT
127         asm volatile("lidt idt_pd");
128
129         // This will go away when we start using the IOAPIC properly
130         pic_remap();
131         // set LINT0 to receive ExtINTs (KVM's default).  At reset they are 0x1000.
132         write_mmreg32(LAPIC_LVT_LINT0, 0x700);
133         // mask it to shut it up for now
134         mask_lapic_lvt(LAPIC_LVT_LINT0);
135         // and turn it on
136         lapic_enable();
137         /* register the generic timer_interrupt() handler for the per-core timers */
138         register_interrupt_handler(interrupt_handlers, LAPIC_TIMER_DEFAULT_VECTOR,
139                                    timer_interrupt, NULL);
140 }
141
142 void
143 print_regs(push_regs_t *regs)
144 {
145         cprintf("  edi  0x%08x\n", regs->reg_edi);
146         cprintf("  esi  0x%08x\n", regs->reg_esi);
147         cprintf("  ebp  0x%08x\n", regs->reg_ebp);
148         cprintf("  oesp 0x%08x\n", regs->reg_oesp);
149         cprintf("  ebx  0x%08x\n", regs->reg_ebx);
150         cprintf("  edx  0x%08x\n", regs->reg_edx);
151         cprintf("  ecx  0x%08x\n", regs->reg_ecx);
152         cprintf("  eax  0x%08x\n", regs->reg_eax);
153 }
154
155 void
156 print_trapframe(trapframe_t *tf)
157 {
158         static spinlock_t ptf_lock;
159
160         spin_lock_irqsave(&ptf_lock);
161         printk("TRAP frame at %p on core %d\n", tf, core_id());
162         print_regs(&tf->tf_regs);
163         printk("  gs   0x----%04x\n", tf->tf_gs);
164         printk("  fs   0x----%04x\n", tf->tf_fs);
165         printk("  es   0x----%04x\n", tf->tf_es);
166         printk("  ds   0x----%04x\n", tf->tf_ds);
167         printk("  trap 0x%08x %s\n", tf->tf_trapno, trapname(tf->tf_trapno));
168         printk("  err  0x%08x\n", tf->tf_err);
169         printk("  eip  0x%08x\n", tf->tf_eip);
170         printk("  cs   0x----%04x\n", tf->tf_cs);
171         printk("  flag 0x%08x\n", tf->tf_eflags);
172         /* Prevents us from thinking these mean something for nested interrupts. */
173         if (tf->tf_cs != GD_KT) {
174                 printk("  esp  0x%08x\n", tf->tf_esp);
175                 printk("  ss   0x----%04x\n", tf->tf_ss);
176         }
177         spin_unlock_irqsave(&ptf_lock);
178 }
179
180 static void
181 trap_dispatch(trapframe_t *tf)
182 {
183         // Handle processor exceptions.
184         switch(tf->tf_trapno) {
185                 case T_BRKPT:
186                         monitor(tf);
187                         break;
188                 case T_PGFLT:
189                         page_fault_handler(tf);
190                         break;
191                 case T_SYSCALL:
192                         // check for userspace, for now
193                         assert(tf->tf_cs != GD_KT);
194                         struct per_cpu_info* coreinfo = &per_cpu_info[core_id()];
195                         coreinfo->cur_ret.returnloc = &(tf->tf_regs.reg_eax);
196                         coreinfo->cur_ret.errno_loc = &(tf->tf_regs.reg_esi);
197                         // syscall code wants an edible reference for current
198                         kref_get(&coreinfo->cur_proc->kref, 1);
199                         tf->tf_regs.reg_eax =
200                                 syscall(coreinfo->cur_proc, tf->tf_regs.reg_eax, tf->tf_regs.reg_edx,
201                                         tf->tf_regs.reg_ecx, tf->tf_regs.reg_ebx,
202                                         tf->tf_regs.reg_edi, tf->tf_regs.reg_esi);
203                         kref_put(&coreinfo->cur_proc->kref);
204                         break;
205                 default:
206                         // Unexpected trap: The user process or the kernel has a bug.
207                         print_trapframe(tf);
208                         if (tf->tf_cs == GD_KT)
209                                 panic("Damn Damn!  Unhandled trap in the kernel!");
210                         else {
211                                 warn("Unexpected trap from userspace");
212                                 kref_get(&current->kref, 1);
213                                 proc_destroy(current);
214                                 return;
215                         }
216         }
217         return;
218 }
219
220 void
221 env_push_ancillary_state(env_t* e)
222 {
223         // TODO: (HSS) handle silly state (don't really want this per-process)
224         // Here's where you'll save FP/MMX/XMM regs
225 }
226
227 void
228 env_pop_ancillary_state(env_t* e)
229 {
230         // Here's where you'll restore FP/MMX/XMM regs
231 }
232
233 void trap(struct trapframe *tf)
234 {
235         printd("Incoming TRAP %d on core %d, TF at %p\n", tf->tf_trapno, core_id(),
236                tf);
237         /* Note we are not preemptively saving the TF in the env_tf.  We do maintain
238          * a reference to it in current_tf (a per-cpu pointer).
239          * In general, only save the tf and any silly state once you know it
240          * is necessary (blocking).  And only save it in env_tf when you know you
241          * are single core (PROC_RUNNING_S) */
242         if (!in_kernel(tf))
243                 set_current_tf(tf);
244         if ((tf->tf_cs & ~3) != GD_UT && (tf->tf_cs & ~3) != GD_KT) {
245                 print_trapframe(tf);
246                 panic("Trapframe with invalid CS!");
247         }
248         trap_dispatch(tf);
249         /* Return to the current process, which should be runnable.  If we're the
250          * kernel, we should just return naturally.  Note that current and tf need
251          * to still be okay (might not be after blocking) */
252         if (in_kernel(tf))
253                 return;
254         proc_restartcore(current, tf);
255         assert(0);
256 }
257
258 void irq_handler(struct trapframe *tf)
259 {
260         if (!in_kernel(tf))
261                 set_current_tf(tf);
262         //if (core_id())
263                 printd("Incoming IRQ, ISR: %d on core %d\n", tf->tf_trapno, core_id());
264
265         extern handler_wrapper_t (RO handler_wrappers)[NUM_HANDLER_WRAPPERS];
266
267         // determine the interrupt handler table to use.  for now, pick the global
268         handler_t TP(TV(t)) LCKD(&iht_lock) * handler_tbl = interrupt_handlers;
269
270         if (handler_tbl[tf->tf_trapno].isr != 0)
271                 handler_tbl[tf->tf_trapno].isr(tf, handler_tbl[tf->tf_trapno].data);
272         // if we're a general purpose IPI function call, down the cpu_list
273         if ((I_SMP_CALL0 <= tf->tf_trapno) && (tf->tf_trapno <= I_SMP_CALL_LAST))
274                 down_checklist(handler_wrappers[tf->tf_trapno & 0x0f].cpu_list);
275
276         // Send EOI.  might want to do this in assembly, and possibly earlier
277         // This is set up to work with an old PIC for now
278         // Convention is that all IRQs between 32 and 47 are for the PIC.
279         // All others are LAPIC (timer, IPIs, perf, non-ExtINT LINTS, etc)
280         // For now, only 235-255 are available
281         assert(tf->tf_trapno >= 32); // slows us down, but we should never have this
282
283 #ifndef __CONFIG_DISABLE_MPTABLES__
284         lapic_send_eoi();
285 #else
286         //Old PIC relatd code. Should be gone for good, but leaving it just incase.
287         if (tf->tf_trapno < 48)
288                 pic_send_eoi(tf->tf_trapno - PIC1_OFFSET);
289         else
290                 lapic_send_eoi();
291 #endif
292
293 }
294
295 void
296 register_interrupt_handler(handler_t TP(TV(t)) table[],
297                            uint8_t int_num, poly_isr_t handler, TV(t) data)
298 {
299         table[int_num].isr = handler;
300         table[int_num].data = data;
301 }
302
303 void page_fault_handler(struct trapframe *tf)
304 {
305         uint32_t fault_va = rcr2();
306         int prot = tf->tf_err & PF_ERROR_WRITE ? PROT_WRITE : PROT_READ;
307         int err;
308
309         /* TODO - handle kernel page faults */
310         if ((tf->tf_cs & 3) == 0) {
311                 print_trapframe(tf);
312                 panic("Page Fault in the Kernel at 0x%08x!", fault_va);
313         }
314         if ((err = handle_page_fault(current, fault_va, prot))) {
315                 /* Destroy the faulting process */
316                 printk("[%08x] user %s fault va %08x ip %08x on core %d with err %d\n",
317                        current->pid, prot & PROT_READ ? "READ" : "WRITE", fault_va,
318                        tf->tf_eip, core_id(), err);
319                 print_trapframe(tf);
320                 kref_get(&current->kref, 1);
321                 proc_destroy(current);
322         }
323 }
324
325 void sysenter_init(void)
326 {
327         write_msr(MSR_IA32_SYSENTER_CS, GD_KT);
328         write_msr(MSR_IA32_SYSENTER_ESP, ts.ts_esp0);
329         write_msr(MSR_IA32_SYSENTER_EIP, (uint32_t) &sysenter_handler);
330 }
331
332 /* This is called from sysenter's asm, with the tf on the kernel stack. */
333 void sysenter_callwrapper(struct trapframe *tf)
334 {
335         struct per_cpu_info* coreinfo = &per_cpu_info[core_id()];
336         if (!in_kernel(tf))
337                 coreinfo->cur_tf = tf;
338         coreinfo->cur_ret.returnloc = &(tf->tf_regs.reg_eax);
339         coreinfo->cur_ret.errno_loc = &(tf->tf_regs.reg_esi);
340
341         // syscall code wants an edible reference for current
342         kref_get(&current->kref, 1);
343         tf->tf_regs.reg_eax = (intreg_t) syscall(current,
344                                                  tf->tf_regs.reg_eax,
345                                                  tf->tf_regs.reg_esi,
346                                                  tf->tf_regs.reg_ecx,
347                                                  tf->tf_regs.reg_ebx,
348                                                  tf->tf_regs.reg_edi,
349                                                  0);
350         kref_put(&current->kref);
351         /*
352          * careful here - we need to make sure that this current is the right
353          * process, which could be weird if the syscall blocked.  it would need to
354          * restore the proper value in current before returning to here.
355          * likewise, tf could be pointing to random gibberish.
356          */
357         proc_restartcore(current, tf);
358 }
359
360 struct kmem_cache *kernel_msg_cache;
361 void kernel_msg_init(void)
362 {
363         kernel_msg_cache = kmem_cache_create("kernel_msgs",
364                            sizeof(struct kernel_message), HW_CACHE_ALIGN, 0, 0, 0);
365 }
366
367 uint32_t send_kernel_message(uint32_t dst, amr_t pc, TV(a0t) arg0, TV(a1t) arg1,
368                              TV(a2t) arg2, int type)
369 {
370         kernel_message_t *k_msg;
371         assert(pc);
372         // note this will be freed on the destination core
373         k_msg = (kernel_message_t *CT(1))TC(kmem_cache_alloc(kernel_msg_cache, 0));
374         k_msg->srcid = core_id();
375         k_msg->pc = pc;
376         k_msg->arg0 = arg0;
377         k_msg->arg1 = arg1;
378         k_msg->arg2 = arg2;
379         switch (type) {
380                 case KMSG_IMMEDIATE:
381                         spin_lock_irqsave(&per_cpu_info[dst].immed_amsg_lock);
382                         STAILQ_INSERT_TAIL(&per_cpu_info[dst].immed_amsgs, k_msg, link);
383                         spin_unlock_irqsave(&per_cpu_info[dst].immed_amsg_lock);
384                         break;
385                 case KMSG_ROUTINE:
386                         spin_lock_irqsave(&per_cpu_info[dst].routine_amsg_lock);
387                         STAILQ_INSERT_TAIL(&per_cpu_info[dst].routine_amsgs, k_msg, link);
388                         spin_unlock_irqsave(&per_cpu_info[dst].routine_amsg_lock);
389                         break;
390                 default:
391                         panic("Unknown type of kernel message!");
392         }
393         // since we touched memory the other core will touch (the lock), we don't
394         // need an wmb_f()
395         send_ipi(get_hw_coreid(dst), I_KERNEL_MSG);
396         return 0;
397 }
398
399 /* Helper function.  Returns 0 if the list was empty. */
400 static kernel_message_t *get_next_amsg(struct kernel_msg_list *list_head,
401                                        spinlock_t *list_lock)
402 {
403         kernel_message_t *k_msg;
404         spin_lock_irqsave(list_lock);
405         k_msg = STAILQ_FIRST(list_head);
406         if (k_msg)
407                 STAILQ_REMOVE_HEAD(list_head, link);
408         spin_unlock_irqsave(list_lock);
409         return k_msg;
410 }
411
412 /* Kernel message handler.  Extensive documentation is in
413  * Documentation/kernel_messages.txt.
414  *
415  * In general: this processes immediate messages, then routine messages.
416  * Routine messages might not return (__startcore, etc), so we need to be
417  * careful about a few things.
418  *
419  * Note that all of this happens from interrupt context, and interrupts are
420  * currently disabled for this gate.  Interrupts need to be disabled so that the
421  * self-ipi doesn't preempt the execution of this kernel message. */
422 void __kernel_message(struct trapframe *tf)
423 {
424         per_cpu_info_t *myinfo = &per_cpu_info[core_id()];
425         kernel_message_t msg_cp, *k_msg;
426
427         lapic_send_eoi();
428         while (1) { // will break out when there are no more messages
429                 /* Try to get an immediate message.  Exec and free it. */
430                 k_msg = get_next_amsg(&myinfo->immed_amsgs, &myinfo->immed_amsg_lock);
431                 if (k_msg) {
432                         assert(k_msg->pc);
433                         k_msg->pc(tf, k_msg->srcid, k_msg->arg0, k_msg->arg1, k_msg->arg2);
434                         kmem_cache_free(kernel_msg_cache, (void*)k_msg);
435                 } else { // no immediate, might be a routine
436                         if (in_kernel(tf))
437                                 return; // don't execute routine msgs if we were in the kernel
438                         k_msg = get_next_amsg(&myinfo->routine_amsgs,
439                                               &myinfo->routine_amsg_lock);
440                         if (!k_msg) // no routines either
441                                 return;
442                         /* copy in, and then free, in case we don't return */
443                         msg_cp = *k_msg;
444                         kmem_cache_free(kernel_msg_cache, (void*)k_msg);
445                         /* make sure an IPI is pending if we have more work */
446                         /* techincally, we don't need to lock when checking */
447                         if (!STAILQ_EMPTY(&myinfo->routine_amsgs) &&
448                                !ipi_is_pending(I_KERNEL_MSG))
449                                 send_self_ipi(I_KERNEL_MSG);
450                         /* Execute the kernel message */
451                         assert(msg_cp.pc);
452                         msg_cp.pc(tf, msg_cp.srcid, msg_cp.arg0, msg_cp.arg1, msg_cp.arg2);
453                 }
454         }
455 }
456
457 /* Runs any outstanding routine kernel messages from within the kernel.  Will
458  * make sure immediates still run first (or when they arrive, if processing a
459  * bunch of these messages).  This will disable interrupts, and restore them to
460  * whatever state you left them. */
461 void process_routine_kmsg(void)
462 {
463         per_cpu_info_t *myinfo = &per_cpu_info[core_id()];
464         kernel_message_t msg_cp, *k_msg;
465         int8_t irq_state = 0;
466
467         disable_irqsave(&irq_state);
468         while (1) {
469                 /* normally, we want ints disabled, so we don't have an empty self-ipi
470                  * for every routine message. (imagine a long list of routines).  But we
471                  * do want immediates to run ahead of routines.  This enabling should
472                  * work (might not in some shitty VMs).  Also note we can receive an
473                  * extra self-ipi for routine messages before we turn off irqs again.
474                  * Not a big deal, since we will process it right away. 
475                  * TODO: consider calling __kernel_message() here. */
476                 if (!STAILQ_EMPTY(&myinfo->immed_amsgs)) {
477                         enable_irq();
478                         cpu_relax();
479                         disable_irq();
480                 }
481                 k_msg = get_next_amsg(&myinfo->routine_amsgs,
482                                       &myinfo->routine_amsg_lock);
483                 if (!k_msg) {
484                         enable_irqsave(&irq_state);
485                         return;
486                 }
487                 /* copy in, and then free, in case we don't return */
488                 msg_cp = *k_msg;
489                 kmem_cache_free(kernel_msg_cache, (void*)k_msg);
490                 /* make sure an IPI is pending if we have more work */
491                 if (!STAILQ_EMPTY(&myinfo->routine_amsgs) &&
492                        !ipi_is_pending(I_KERNEL_MSG))
493                         send_self_ipi(I_KERNEL_MSG);
494                 /* Execute the kernel message */
495                 assert(msg_cp.pc);
496                 msg_cp.pc(current_tf, msg_cp.srcid, msg_cp.arg0, msg_cp.arg1,
497                           msg_cp.arg2);
498         }
499 }