6103eda1457e19c891f93082d733cd69c2077bde
[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         int err;
309
310         /* TODO - handle kernel page faults */
311         if ((tf->tf_cs & 3) == 0) {
312                 print_trapframe(tf);
313                 panic("Page Fault in the Kernel at 0x%08x!", fault_va);
314         }
315         if ((err = handle_page_fault(current, fault_va, prot))) {
316                 /* Destroy the faulting process */
317                 printk("[%08x] user %s fault va %08x ip %08x on core %d with err %d\n",
318                        current->pid, prot & PROT_READ ? "READ" : "WRITE", fault_va,
319                        tf->tf_eip, core_id(), err);
320                 print_trapframe(tf);
321                 kref_get(&current->kref, 1);
322                 proc_destroy(current);
323         }
324 }
325
326 void sysenter_init(void)
327 {
328         write_msr(MSR_IA32_SYSENTER_CS, GD_KT);
329         write_msr(MSR_IA32_SYSENTER_ESP, ts.ts_esp0);
330         write_msr(MSR_IA32_SYSENTER_EIP, (uint32_t) &sysenter_handler);
331 }
332
333 /* This is called from sysenter's asm, with the tf on the kernel stack. */
334 void sysenter_callwrapper(struct trapframe *tf)
335 {
336         struct per_cpu_info* coreinfo = &per_cpu_info[core_id()];
337         if (!in_kernel(tf))
338                 coreinfo->cur_tf = tf;
339         coreinfo->cur_ret.returnloc = &(tf->tf_regs.reg_eax);
340         coreinfo->cur_ret.errno_loc = &(tf->tf_regs.reg_esi);
341
342         // syscall code wants an edible reference for current
343         kref_get(&current->kref, 1);
344         tf->tf_regs.reg_eax = (intreg_t) syscall(current,
345                                                  tf->tf_regs.reg_eax,
346                                                  tf->tf_regs.reg_esi,
347                                                  tf->tf_regs.reg_ecx,
348                                                  tf->tf_regs.reg_ebx,
349                                                  tf->tf_regs.reg_edi,
350                                                  0);
351         kref_put(&current->kref);
352         /*
353          * careful here - we need to make sure that this current is the right
354          * process, which could be weird if the syscall blocked.  it would need to
355          * restore the proper value in current before returning to here.
356          * likewise, tf could be pointing to random gibberish.
357          */
358         proc_restartcore(current, tf);
359 }
360
361 struct kmem_cache *kernel_msg_cache;
362 void kernel_msg_init(void)
363 {
364         kernel_msg_cache = kmem_cache_create("kernel_msgs",
365                            sizeof(struct kernel_message), HW_CACHE_ALIGN, 0, 0, 0);
366 }
367
368 uint32_t send_kernel_message(uint32_t dst, amr_t pc, TV(a0t) arg0, TV(a1t) arg1,
369                              TV(a2t) arg2, int type)
370 {
371         kernel_message_t *k_msg;
372         assert(pc);
373         // note this will be freed on the destination core
374         k_msg = (kernel_message_t *CT(1))TC(kmem_cache_alloc(kernel_msg_cache, 0));
375         k_msg->srcid = core_id();
376         k_msg->pc = pc;
377         k_msg->arg0 = arg0;
378         k_msg->arg1 = arg1;
379         k_msg->arg2 = arg2;
380         switch (type) {
381                 case KMSG_IMMEDIATE:
382                         spin_lock_irqsave(&per_cpu_info[dst].immed_amsg_lock);
383                         STAILQ_INSERT_TAIL(&per_cpu_info[dst].immed_amsgs, k_msg, link);
384                         spin_unlock_irqsave(&per_cpu_info[dst].immed_amsg_lock);
385                         break;
386                 case KMSG_ROUTINE:
387                         spin_lock_irqsave(&per_cpu_info[dst].routine_amsg_lock);
388                         STAILQ_INSERT_TAIL(&per_cpu_info[dst].routine_amsgs, k_msg, link);
389                         spin_unlock_irqsave(&per_cpu_info[dst].routine_amsg_lock);
390                         break;
391                 default:
392                         panic("Unknown type of kernel message!");
393         }
394         // since we touched memory the other core will touch (the lock), we don't
395         // need an wmb_f()
396         send_ipi(get_hw_coreid(dst), I_KERNEL_MSG);
397         return 0;
398 }
399
400 /* Helper function.  Returns 0 if the list was empty. */
401 static kernel_message_t *get_next_amsg(struct kernel_msg_list *list_head,
402                                        spinlock_t *list_lock)
403 {
404         kernel_message_t *k_msg;
405         spin_lock_irqsave(list_lock);
406         k_msg = STAILQ_FIRST(list_head);
407         if (k_msg)
408                 STAILQ_REMOVE_HEAD(list_head, link);
409         spin_unlock_irqsave(list_lock);
410         return k_msg;
411 }
412
413 /* Kernel message handler.  Extensive documentation is in
414  * Documentation/kernel_messages.txt.
415  *
416  * In general: this processes immediate messages, then routine messages.
417  * Routine messages might not return (__startcore, etc), so we need to be
418  * careful about a few things.
419  *
420  * Note that all of this happens from interrupt context, and interrupts are
421  * currently disabled for this gate.  Interrupts need to be disabled so that the
422  * self-ipi doesn't preempt the execution of this kernel message. */
423 void __kernel_message(struct trapframe *tf)
424 {
425         per_cpu_info_t *myinfo = &per_cpu_info[core_id()];
426         kernel_message_t msg_cp, *k_msg;
427
428         lapic_send_eoi();
429         while (1) { // will break out when there are no more messages
430                 /* Try to get an immediate message.  Exec and free it. */
431                 k_msg = get_next_amsg(&myinfo->immed_amsgs, &myinfo->immed_amsg_lock);
432                 if (k_msg) {
433                         assert(k_msg->pc);
434                         k_msg->pc(tf, k_msg->srcid, k_msg->arg0, k_msg->arg1, k_msg->arg2);
435                         kmem_cache_free(kernel_msg_cache, (void*)k_msg);
436                 } else { // no immediate, might be a routine
437                         if (in_kernel(tf))
438                                 return; // don't execute routine msgs if we were in the kernel
439                         k_msg = get_next_amsg(&myinfo->routine_amsgs,
440                                               &myinfo->routine_amsg_lock);
441                         if (!k_msg) // no routines either
442                                 return;
443                         /* copy in, and then free, in case we don't return */
444                         msg_cp = *k_msg;
445                         kmem_cache_free(kernel_msg_cache, (void*)k_msg);
446                         /* make sure an IPI is pending if we have more work */
447                         /* techincally, we don't need to lock when checking */
448                         if (!STAILQ_EMPTY(&myinfo->routine_amsgs) &&
449                                !ipi_is_pending(I_KERNEL_MSG))
450                                 send_self_ipi(I_KERNEL_MSG);
451                         /* Execute the kernel message */
452                         assert(msg_cp.pc);
453                         msg_cp.pc(tf, msg_cp.srcid, msg_cp.arg0, msg_cp.arg1, msg_cp.arg2);
454                 }
455         }
456 }
457
458 /* Runs any outstanding routine kernel messages from within the kernel.  Will
459  * make sure immediates still run first (or when they arrive, if processing a
460  * bunch of these messages).  This will disable interrupts, and restore them to
461  * whatever state you left them. */
462 void process_routine_kmsg(void)
463 {
464         per_cpu_info_t *myinfo = &per_cpu_info[core_id()];
465         kernel_message_t msg_cp, *k_msg;
466         int8_t irq_state = 0;
467
468         disable_irqsave(&irq_state);
469         while (1) {
470                 /* normally, we want ints disabled, so we don't have an empty self-ipi
471                  * for every routine message. (imagine a long list of routines).  But we
472                  * do want immediates to run ahead of routines.  This enabling should
473                  * work (might not in some shitty VMs).  Also note we can receive an
474                  * extra self-ipi for routine messages before we turn off irqs again.
475                  * Not a big deal, since we will process it right away. 
476                  * TODO: consider calling __kernel_message() here. */
477                 if (!STAILQ_EMPTY(&myinfo->immed_amsgs)) {
478                         enable_irq();
479                         cpu_relax();
480                         disable_irq();
481                 }
482                 k_msg = get_next_amsg(&myinfo->routine_amsgs,
483                                       &myinfo->routine_amsg_lock);
484                 if (!k_msg) {
485                         enable_irqsave(&irq_state);
486                         return;
487                 }
488                 /* copy in, and then free, in case we don't return */
489                 msg_cp = *k_msg;
490                 kmem_cache_free(kernel_msg_cache, (void*)k_msg);
491                 /* make sure an IPI is pending if we have more work */
492                 if (!STAILQ_EMPTY(&myinfo->routine_amsgs) &&
493                        !ipi_is_pending(I_KERNEL_MSG))
494                         send_self_ipi(I_KERNEL_MSG);
495                 /* Execute the kernel message */
496                 assert(msg_cp.pc);
497                 msg_cp.pc(current_tf, msg_cp.srcid, msg_cp.arg0, msg_cp.arg1,
498                           msg_cp.arg2);
499         }
500 }