x86 page faults know about the reason for the PF
[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
234 trap(trapframe_t *tf)
235 {
236         printd("Incoming TRAP frame on core %d at %p\n", core_id(), tf);
237
238         /* Note we are not preemptively saving the TF in the env_tf.  We do maintain
239          * a reference to it in current_tf (a per-cpu pointer).
240          * In general, only save the tf and any silly state once you know it
241          * is necessary (blocking).  And only save it in env_tf when you know you
242          * are single core (PROC_RUNNING_S) */
243         if (!in_kernel(tf))
244                 set_current_tf(tf);
245
246         if ((tf->tf_cs & ~3) != GD_UT && (tf->tf_cs & ~3) != GD_KT) {
247                 print_trapframe(tf);
248                 panic("Trapframe with invalid CS!");
249         }
250
251         // Dispatch based on what type of trap occurred
252         trap_dispatch(tf);
253
254         // Return to the current process, which should be runnable.
255         proc_restartcore(current, tf); // Note the comment in syscall.c
256 }
257
258 void
259 irq_handler(trapframe_t *tf)
260 {
261         if (!in_kernel(tf))
262                 set_current_tf(tf);
263         //if (core_id())
264                 printd("Incoming IRQ, ISR: %d on core %d\n", tf->tf_trapno, core_id());
265
266         extern handler_wrapper_t (RO handler_wrappers)[NUM_HANDLER_WRAPPERS];
267
268         // determine the interrupt handler table to use.  for now, pick the global
269         handler_t TP(TV(t)) LCKD(&iht_lock) * handler_tbl = interrupt_handlers;
270
271         if (handler_tbl[tf->tf_trapno].isr != 0)
272                 handler_tbl[tf->tf_trapno].isr(tf, handler_tbl[tf->tf_trapno].data);
273         // if we're a general purpose IPI function call, down the cpu_list
274         if ((I_SMP_CALL0 <= tf->tf_trapno) && (tf->tf_trapno <= I_SMP_CALL_LAST))
275                 down_checklist(handler_wrappers[tf->tf_trapno & 0x0f].cpu_list);
276
277         // Send EOI.  might want to do this in assembly, and possibly earlier
278         // This is set up to work with an old PIC for now
279         // Convention is that all IRQs between 32 and 47 are for the PIC.
280         // All others are LAPIC (timer, IPIs, perf, non-ExtINT LINTS, etc)
281         // For now, only 235-255 are available
282         assert(tf->tf_trapno >= 32); // slows us down, but we should never have this
283
284 #ifndef __CONFIG_DISABLE_MPTABLES__
285         lapic_send_eoi();
286 #else
287         //Old PIC relatd code. Should be gone for good, but leaving it just incase.
288         if (tf->tf_trapno < 48)
289                 pic_send_eoi(tf->tf_trapno - PIC1_OFFSET);
290         else
291                 lapic_send_eoi();
292 #endif
293
294 }
295
296 void
297 register_interrupt_handler(handler_t TP(TV(t)) table[],
298                            uint8_t int_num, poly_isr_t handler, TV(t) data)
299 {
300         table[int_num].isr = handler;
301         table[int_num].data = data;
302 }
303
304 void page_fault_handler(struct trapframe *tf)
305 {
306         uint32_t fault_va = rcr2();
307         int prot = tf->tf_err & PF_ERROR_WRITE ? PROT_WRITE : PROT_READ;
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 (handle_page_fault(current, fault_va, prot)) {
315                 /* Destroy the faulting process */
316                 printk("[%08x] user fault va %08x ip %08x from core %d\n",
317                        current->pid, fault_va, tf->tf_eip, core_id());
318                 print_trapframe(tf);
319                 kref_get(&current->kref, 1);
320                 proc_destroy(current);
321         }
322 }
323
324 void sysenter_init(void)
325 {
326         write_msr(MSR_IA32_SYSENTER_CS, GD_KT);
327         write_msr(MSR_IA32_SYSENTER_ESP, ts.ts_esp0);
328         write_msr(MSR_IA32_SYSENTER_EIP, (uint32_t) &sysenter_handler);
329 }
330
331 /* This is called from sysenter's asm, with the tf on the kernel stack. */
332 void sysenter_callwrapper(struct trapframe *tf)
333 {
334         struct per_cpu_info* coreinfo = &per_cpu_info[core_id()];
335         if (!in_kernel(tf))
336                 coreinfo->cur_tf = tf;
337         coreinfo->cur_ret.returnloc = &(tf->tf_regs.reg_eax);
338         coreinfo->cur_ret.errno_loc = &(tf->tf_regs.reg_esi);
339
340         // syscall code wants an edible reference for current
341         kref_get(&current->kref, 1);
342         tf->tf_regs.reg_eax = (intreg_t) syscall(current,
343                                                  tf->tf_regs.reg_eax,
344                                                  tf->tf_regs.reg_esi,
345                                                  tf->tf_regs.reg_ecx,
346                                                  tf->tf_regs.reg_ebx,
347                                                  tf->tf_regs.reg_edi,
348                                                  0);
349         kref_put(&current->kref);
350         /*
351          * careful here - we need to make sure that this current is the right
352          * process, which could be weird if the syscall blocked.  it would need to
353          * restore the proper value in current before returning to here.
354          * likewise, tf could be pointing to random gibberish.
355          */
356         proc_restartcore(current, tf);
357 }
358
359 struct kmem_cache *kernel_msg_cache;
360 void kernel_msg_init(void)
361 {
362         kernel_msg_cache = kmem_cache_create("kernel_msgs",
363                            sizeof(struct kernel_message), HW_CACHE_ALIGN, 0, 0, 0);
364 }
365
366 uint32_t send_kernel_message(uint32_t dst, amr_t pc, TV(a0t) arg0, TV(a1t) arg1,
367                              TV(a2t) arg2, int type)
368 {
369         kernel_message_t *k_msg;
370         assert(pc);
371         // note this will be freed on the destination core
372         k_msg = (kernel_message_t *CT(1))TC(kmem_cache_alloc(kernel_msg_cache, 0));
373         k_msg->srcid = core_id();
374         k_msg->pc = pc;
375         k_msg->arg0 = arg0;
376         k_msg->arg1 = arg1;
377         k_msg->arg2 = arg2;
378         switch (type) {
379                 case KMSG_IMMEDIATE:
380                         spin_lock_irqsave(&per_cpu_info[dst].immed_amsg_lock);
381                         STAILQ_INSERT_TAIL(&per_cpu_info[dst].immed_amsgs, k_msg, link);
382                         spin_unlock_irqsave(&per_cpu_info[dst].immed_amsg_lock);
383                         break;
384                 case KMSG_ROUTINE:
385                         spin_lock_irqsave(&per_cpu_info[dst].routine_amsg_lock);
386                         STAILQ_INSERT_TAIL(&per_cpu_info[dst].routine_amsgs, k_msg, link);
387                         spin_unlock_irqsave(&per_cpu_info[dst].routine_amsg_lock);
388                         break;
389                 default:
390                         panic("Unknown type of kernel message!");
391         }
392         // since we touched memory the other core will touch (the lock), we don't
393         // need an wmb_f()
394         send_ipi(get_hw_coreid(dst), I_KERNEL_MSG);
395         return 0;
396 }
397
398 /* Helper function.  Returns 0 if the list was empty. */
399 static kernel_message_t *get_next_amsg(struct kernel_msg_list *list_head,
400                                        spinlock_t *list_lock)
401 {
402         kernel_message_t *k_msg;
403         spin_lock_irqsave(list_lock);
404         k_msg = STAILQ_FIRST(list_head);
405         if (k_msg)
406                 STAILQ_REMOVE_HEAD(list_head, link);
407         spin_unlock_irqsave(list_lock);
408         return k_msg;
409 }
410
411 /* Kernel message handler.  Extensive documentation is in
412  * Documentation/kernel_messages.txt.
413  *
414  * In general: this processes immediate messages, then routine messages.
415  * Routine messages might not return (__startcore, etc), so we need to be
416  * careful about a few things.
417  *
418  * Note that all of this happens from interrupt context, and interrupts are
419  * currently disabled for this gate.  Interrupts need to be disabled so that the
420  * self-ipi doesn't preempt the execution of this kernel message. */
421 void __kernel_message(struct trapframe *tf)
422 {
423         per_cpu_info_t *myinfo = &per_cpu_info[core_id()];
424         kernel_message_t msg_cp, *k_msg;
425
426         lapic_send_eoi();
427         while (1) { // will break out when there are no more messages
428                 /* Try to get an immediate message.  Exec and free it. */
429                 k_msg = get_next_amsg(&myinfo->immed_amsgs, &myinfo->immed_amsg_lock);
430                 if (k_msg) {
431                         assert(k_msg->pc);
432                         k_msg->pc(tf, k_msg->srcid, k_msg->arg0, k_msg->arg1, k_msg->arg2);
433                         kmem_cache_free(kernel_msg_cache, (void*)k_msg);
434                 } else { // no immediate, might be a routine
435                         if (in_kernel(tf))
436                                 return; // don't execute routine msgs if we were in the kernel
437                         k_msg = get_next_amsg(&myinfo->routine_amsgs,
438                                               &myinfo->routine_amsg_lock);
439                         if (!k_msg) // no routines either
440                                 return;
441                         /* copy in, and then free, in case we don't return */
442                         msg_cp = *k_msg;
443                         kmem_cache_free(kernel_msg_cache, (void*)k_msg);
444                         /* make sure an IPI is pending if we have more work */
445                         /* techincally, we don't need to lock when checking */
446                         if (!STAILQ_EMPTY(&myinfo->routine_amsgs) &&
447                                !ipi_is_pending(I_KERNEL_MSG))
448                                 send_self_ipi(I_KERNEL_MSG);
449                         /* Execute the kernel message */
450                         assert(msg_cp.pc);
451                         msg_cp.pc(tf, msg_cp.srcid, msg_cp.arg0, msg_cp.arg1, msg_cp.arg2);
452                 }
453         }
454 }
455
456 /* Runs any outstanding routine kernel messages from within the kernel.  Will
457  * make sure immediates still run first (or when they arrive, if processing a
458  * bunch of these messages).  This will disable interrupts, and restore them to
459  * whatever state you left them. */
460 void process_routine_kmsg(void)
461 {
462         per_cpu_info_t *myinfo = &per_cpu_info[core_id()];
463         kernel_message_t msg_cp, *k_msg;
464         int8_t irq_state = 0;
465
466         disable_irqsave(&irq_state);
467         while (1) {
468                 /* normally, we want ints disabled, so we don't have an empty self-ipi
469                  * for every routine message. (imagine a long list of routines).  But we
470                  * do want immediates to run ahead of routines.  This enabling should
471                  * work (might not in some shitty VMs).  Also note we can receive an
472                  * extra self-ipi for routine messages before we turn off irqs again.
473                  * Not a big deal, since we will process it right away. 
474                  * TODO: consider calling __kernel_message() here. */
475                 if (!STAILQ_EMPTY(&myinfo->immed_amsgs)) {
476                         enable_irq();
477                         cpu_relax();
478                         disable_irq();
479                 }
480                 k_msg = get_next_amsg(&myinfo->routine_amsgs,
481                                       &myinfo->routine_amsg_lock);
482                 if (!k_msg) {
483                         enable_irqsave(&irq_state);
484                         return;
485                 }
486                 /* copy in, and then free, in case we don't return */
487                 msg_cp = *k_msg;
488                 kmem_cache_free(kernel_msg_cache, (void*)k_msg);
489                 /* make sure an IPI is pending if we have more work */
490                 if (!STAILQ_EMPTY(&myinfo->routine_amsgs) &&
491                        !ipi_is_pending(I_KERNEL_MSG))
492                         send_self_ipi(I_KERNEL_MSG);
493                 /* Execute the kernel message */
494                 assert(msg_cp.pc);
495                 msg_cp.pc(current_tf, msg_cp.srcid, msg_cp.arg0, msg_cp.arg1,
496                           msg_cp.arg2);
497         }
498 }