xref: /xv6-public/trap.c (revision 8b75366c)
1 #include "types.h"
2 #include "defs.h"
3 #include "param.h"
4 #include "mmu.h"
5 #include "proc.h"
6 #include "x86.h"
7 #include "traps.h"
8 #include "spinlock.h"
9 
10 // Interrupt descriptor table (shared by all CPUs).
11 struct gatedesc idt[256];
12 extern uint vectors[];  // in vectors.S: array of 256 entry pointers
13 struct spinlock tickslock;
14 int ticks;
15 
16 void
17 tvinit(void)
18 {
19   int i;
20 
21   for(i = 0; i < 256; i++)
22     SETGATE(idt[i], 0, SEG_KCODE<<3, vectors[i], 0);
23   SETGATE(idt[T_SYSCALL], 1, SEG_KCODE<<3, vectors[T_SYSCALL], DPL_USER);
24 
25   initlock(&tickslock, "time");
26 }
27 
28 void
29 idtinit(void)
30 {
31   lidt(idt, sizeof(idt));
32 }
33 
34 void
35 trap(struct trapframe *tf)
36 {
37   if(tf->trapno == T_SYSCALL){
38     if(cp->killed)
39       exit();
40     cp->tf = tf;
41     syscall();
42     if(cp->killed)
43       exit();
44     return;
45   }
46 
47   switch(tf->trapno){
48   case T_IRQ0 + IRQ_TIMER:
49     if(cpu() == 0){
50       acquire(&tickslock);
51       ticks++;
52       wakeup(&ticks);
53       release(&tickslock);
54     }
55     lapiceoi();
56     break;
57   case T_IRQ0 + IRQ_IDE:
58     ideintr();
59     lapiceoi();
60     break;
61   case T_IRQ0 + IRQ_KBD:
62     kbdintr();
63     lapiceoi();
64     break;
65   case T_IRQ0 + IRQ_COM1:
66     uartintr();
67     lapiceoi();
68     break;
69   case T_IRQ0 + 7:
70   case T_IRQ0 + IRQ_SPURIOUS:
71     cprintf("cpu%d: spurious interrupt at %x:%x\n",
72             cpu(), tf->cs, tf->eip);
73     lapiceoi();
74     break;
75 
76   default:
77     if(cp == 0 || (tf->cs&3) == 0){
78       // In kernel, it must be our mistake.
79       cprintf("unexpected trap %d from cpu %d eip %x\n",
80               tf->trapno, cpu(), tf->eip);
81       panic("trap");
82     }
83     // In user space, assume process misbehaved.
84     cprintf("pid %d %s: trap %d err %d on cpu %d eip %x -- kill proc\n",
85             cp->pid, cp->name, tf->trapno, tf->err, cpu(), tf->eip);
86     cp->killed = 1;
87   }
88 
89   // Force process exit if it has been killed and is in user space.
90   // (If it is still executing in the kernel, let it keep running
91   // until it gets to the regular system call return.)
92   if(cp && cp->killed && (tf->cs&3) == DPL_USER)
93     exit();
94 
95   // Force process to give up CPU on clock tick.
96   // If interrupts were on while locks held, would need to check nlock.
97   if(cp && cp->state == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)
98     yield();
99 
100   // Check if the process has been killed since we yielded
101   if(cp && cp->killed && (tf->cs&3) == DPL_USER)
102     exit();
103 }
104