]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc/main.c
kernel: introduce per process FPU struct (PFPU) for more flexible machine specific...
[plan9front.git] / sys / src / 9 / pc / main.c
1 #include        "u.h"
2 #include        "../port/lib.h"
3 #include        "mem.h"
4 #include        "dat.h"
5 #include        "fns.h"
6 #include        "io.h"
7 #include        "tos.h"
8 #include        "ureg.h"
9 #include        "init.h"
10 #include        "pool.h"
11 #include        "reboot.h"
12
13 Mach *m;
14 Conf conf;
15
16 int delaylink;
17 int idle_spin;
18
19 extern void (*i8237alloc)(void);
20 extern void bootscreeninit(void);
21 extern void multibootdebug(void);
22
23 void
24 main(void)
25 {
26         mach0init();
27         bootargsinit();
28         ioinit();
29         i8250console();
30         quotefmtinstall();
31         screeninit();
32
33         print("\nPlan 9\n");
34         
35         trapinit0();
36         i8253init();
37         cpuidentify();
38         meminit();
39         confinit();
40         xinit();
41         archinit();
42         bootscreeninit();
43         if(i8237alloc != nil)
44                 i8237alloc();
45         trapinit();
46         printinit();
47         cpuidprint();
48         mmuinit();
49         if(arch->intrinit)      /* launches other processors on an mp */
50                 arch->intrinit();
51         timersinit();
52         mathinit();
53         if(arch->clockenable)
54                 arch->clockenable();
55         procinit0();
56         initseg();
57         if(delaylink){
58                 bootlinks();
59                 pcimatch(0, 0, 0);
60         }else
61                 links();
62         chandevreset();
63         netconsole();
64         pageinit();
65         userinit();
66         schedinit();
67 }
68
69 void
70 mach0init(void)
71 {
72         conf.nmach = 1;
73         MACHP(0) = (Mach*)CPU0MACH;
74         m->pdb = (ulong*)CPU0PDB;
75         m->gdt = (Segdesc*)CPU0GDT;
76
77         machinit();
78
79         active.machs[0] = 1;
80         active.exiting = 0;
81 }
82
83 void
84 machinit(void)
85 {
86         int machno;
87         ulong *pdb;
88         Segdesc *gdt;
89
90         machno = m->machno;
91         pdb = m->pdb;
92         gdt = m->gdt;
93         memset(m, 0, sizeof(Mach));
94         m->machno = machno;
95         m->pdb = pdb;
96         m->gdt = gdt;
97         m->perf.period = 1;
98
99         /*
100          * For polled uart output at boot, need
101          * a default delay constant. 100000 should
102          * be enough for a while. Cpuidentify will
103          * calculate the real value later.
104          */
105         m->loopconst = 100000;
106 }
107
108 void
109 init0(void)
110 {
111         char buf[2*KNAMELEN], **sp;
112
113         up->nerrlab = 0;
114
115         spllo();
116
117         /*
118          * These are o.k. because rootinit is null.
119          * Then early kproc's will have a root and dot.
120          */
121         up->slash = namec("#/", Atodir, 0, 0);
122         pathclose(up->slash->path);
123         up->slash->path = newpath("/");
124         up->dot = cclone(up->slash);
125
126         chandevinit();
127
128         if(!waserror()){
129                 snprint(buf, sizeof(buf), "%s %s", arch->id, conffile);
130                 ksetenv("terminal", buf, 0);
131                 ksetenv("cputype", "386", 0);
132                 if(cpuserver)
133                         ksetenv("service", "cpu", 0);
134                 else
135                         ksetenv("service", "terminal", 0);
136                 setconfenv();
137                 poperror();
138         }
139         kproc("alarm", alarmkproc, 0);
140
141         sp = (char**)(USTKTOP - sizeof(Tos) - 8 - sizeof(sp[0])*4);
142         sp[3] = sp[2] = nil;
143         strcpy(sp[1] = (char*)&sp[4], "boot");
144         sp[0] = nil;
145         touser(sp);
146 }
147
148 void
149 userinit(void)
150 {
151         void *v;
152         Proc *p;
153         Segment *s;
154         Page *pg;
155
156         p = newproc();
157         p->pgrp = newpgrp();
158         p->egrp = smalloc(sizeof(Egrp));
159         p->egrp->ref = 1;
160         p->fgrp = dupfgrp(nil);
161         p->rgrp = newrgrp();
162         p->procmode = 0640;
163
164         kstrdup(&eve, "");
165         kstrdup(&p->text, "*init*");
166         kstrdup(&p->user, eve);
167
168         procsetup(p);
169
170         /*
171          * Kernel Stack
172          *
173          * N.B. make sure there's enough space for syscall to check
174          *      for valid args and 
175          *      4 bytes for gotolabel's return PC
176          */
177         p->sched.pc = (ulong)init0;
178         p->sched.sp = (ulong)p->kstack+KSTACK-(sizeof(Sargs)+BY2WD);
179
180         /*
181          * User Stack
182          *
183          * N.B. cannot call newpage() with clear=1, because pc kmap
184          * requires up != nil.  use tmpmap instead.
185          */
186         s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
187         p->seg[SSEG] = s;
188         pg = newpage(0, 0, USTKTOP-BY2PG);
189         segpage(s, pg);
190         v = tmpmap(pg);
191         memset(v, 0, BY2PG);
192         tmpunmap(v);
193
194         /*
195          * Text
196          */
197         s = newseg(SG_TEXT, UTZERO, 1);
198         s->flushme++;
199         p->seg[TSEG] = s;
200         pg = newpage(0, 0, UTZERO);
201         pg->txtflush = ~0;
202         segpage(s, pg);
203         v = tmpmap(pg);
204         memset(v, 0, BY2PG);
205         memmove(v, initcode, sizeof initcode);
206         tmpunmap(v);
207
208         ready(p);
209 }
210
211 void
212 confinit(void)
213 {
214         char *p;
215         int i, userpcnt;
216         ulong kpages;
217
218         if(p = getconf("service")){
219                 if(strcmp(p, "cpu") == 0)
220                         cpuserver = 1;
221                 else if(strcmp(p,"terminal") == 0)
222                         cpuserver = 0;
223         }
224
225         if(p = getconf("*kernelpercent"))
226                 userpcnt = 100 - strtol(p, 0, 0);
227         else
228                 userpcnt = 0;
229
230         conf.npage = 0;
231         for(i=0; i<nelem(conf.mem); i++)
232                 conf.npage += conf.mem[i].npage;
233
234         conf.nproc = 100 + ((conf.npage*BY2PG)/MB)*5;
235         if(cpuserver)
236                 conf.nproc *= 3;
237         if(conf.nproc > 2000)
238                 conf.nproc = 2000;
239         conf.nimage = 200;
240         conf.nswap = conf.nproc*80;
241         conf.nswppo = 4096;
242
243         if(cpuserver) {
244                 if(userpcnt < 10)
245                         userpcnt = 70;
246                 kpages = conf.npage - (conf.npage*userpcnt)/100;
247                 conf.nimage = conf.nproc;
248
249                 /*
250                  * Hack for the big boys. Only good while physmem < 4GB.
251                  * Give the kernel fixed max + enough to allocate the
252                  * page pool.
253                  * This is an overestimate as conf.upages < conf.npages.
254                  * The patch of nimage is a band-aid, scanning the whole
255                  * page list in imagereclaim just takes too long.
256                  */
257                 if(getconf("*imagemaxmb") == 0)
258                 if(kpages > (64*MB + conf.npage*sizeof(Page))/BY2PG){
259                         kpages = (64*MB + conf.npage*sizeof(Page))/BY2PG;
260                         kpages += (conf.nproc*KSTACK)/BY2PG;
261                 }
262         } else {
263                 if(userpcnt < 10) {
264                         if(conf.npage*BY2PG < 16*MB)
265                                 userpcnt = 50;
266                         else
267                                 userpcnt = 60;
268                 }
269                 kpages = conf.npage - (conf.npage*userpcnt)/100;
270
271                 /*
272                  * Make sure terminals with low memory get at least
273                  * 4MB on the first Image chunk allocation.
274                  */
275                 if(conf.npage*BY2PG < 16*MB)
276                         imagmem->minarena = 4*MB;
277         }
278
279         /*
280          * can't go past the end of virtual memory
281          * (ulong)-KZERO is 2^32 - KZERO
282          */
283         if(kpages > ((ulong)-KZERO)/BY2PG)
284                 kpages = ((ulong)-KZERO)/BY2PG;
285
286         conf.upages = conf.npage - kpages;
287         conf.ialloc = (kpages/2)*BY2PG;
288
289         /*
290          * Guess how much is taken by the large permanent
291          * datastructures. Mntcache and Mntrpc are not accounted for.
292          */
293         kpages *= BY2PG;
294         kpages -= conf.upages*sizeof(Page)
295                 + conf.nproc*sizeof(Proc)
296                 + conf.nimage*sizeof(Image)
297                 + conf.nswap
298                 + conf.nswppo*sizeof(Page*);
299         mainmem->maxsize = kpages;
300
301         /*
302          * the dynamic allocation will balance the load properly,
303          * hopefully. be careful with 32-bit overflow.
304          */
305         imagmem->maxsize = kpages - (kpages/10);
306         if(p = getconf("*imagemaxmb")){
307                 imagmem->maxsize = strtol(p, nil, 0)*MB;
308                 if(imagmem->maxsize > mainmem->maxsize)
309                         imagmem->maxsize = mainmem->maxsize;
310         }
311 }
312
313 /*
314  * we keep FPsave structure in SSE format emulating FXSAVE / FXRSTOR
315  * instructions for legacy x87 fpu.
316  */
317 void
318 fpx87save(FPsave *fps)
319 {
320         ushort tag;
321
322         fpx87save0(fps);
323
324         /*
325          * convert x87 tag word to fxsave tag byte:
326          * 00, 01, 10 -> 1, 11 -> 0
327          */
328         tag = ~fps->tag;
329         tag = (tag | (tag >> 1)) & 0x5555;
330         tag = (tag | (tag >> 1)) & 0x3333;
331         tag = (tag | (tag >> 2)) & 0x0F0F;
332         tag = (tag | (tag >> 4)) & 0x00FF;
333
334         /* NOP fps->fcw = fps->control; */
335         fps->fsw = fps->status;
336         fps->ftw = tag;
337         fps->fop = fps->opcode;
338         fps->fpuip = fps->pc;
339         fps->cs = fps->selector;
340         fps->fpudp = fps->operand;
341         fps->ds = fps->oselector;
342
343 #define MOVA(d,s) \
344         *((ushort*)(d+8)) = *((ushort*)(s+8)), \
345         *((ulong*)(d+4)) = *((ulong*)(s+4)), \
346         *((ulong*)(d)) = *((ulong*)(s))
347
348         MOVA(fps->xregs+0x70, fps->regs+70);
349         MOVA(fps->xregs+0x60, fps->regs+60);
350         MOVA(fps->xregs+0x50, fps->regs+50);
351         MOVA(fps->xregs+0x40, fps->regs+40);
352         MOVA(fps->xregs+0x30, fps->regs+30);
353         MOVA(fps->xregs+0x20, fps->regs+20);
354         MOVA(fps->xregs+0x10, fps->regs+10);
355         MOVA(fps->xregs+0x00, fps->regs+00);
356
357 #undef MOVA
358
359 #define CLR6(d) \
360         *((ulong*)(d)) = 0, \
361         *((ushort*)(d+4)) = 0
362
363         CLR6(fps->xregs+0x70+10);
364         CLR6(fps->xregs+0x60+10);
365         CLR6(fps->xregs+0x50+10);
366         CLR6(fps->xregs+0x40+10);
367         CLR6(fps->xregs+0x30+10);
368         CLR6(fps->xregs+0x20+10);
369         CLR6(fps->xregs+0x10+10);
370         CLR6(fps->xregs+0x00+10);
371
372 #undef CLR6
373
374         fps->rsrvd1 = fps->rsrvd2 = fps->mxcsr = fps->mxcsr_mask = 0;
375 }
376
377 void
378 fpx87restore(FPsave *fps)
379 {
380         ushort msk, tos, tag, *reg;
381
382         /* convert fxsave tag byte to x87 tag word */
383         tag = 0;
384         tos = 7 - ((fps->fsw >> 11) & 7);
385         for(msk = 0x80; msk != 0; tos--, msk >>= 1){
386                 tag <<= 2;
387                 if((fps->ftw & msk) != 0){
388                         reg = (ushort*)&fps->xregs[(tos & 7) << 4];
389                         switch(reg[4] & 0x7fff){
390                         case 0x0000:
391                                 if((reg[0] | reg[1] | reg[2] | reg[3]) == 0){
392                                         tag |= 1;       /* 01 zero */
393                                         break;
394                                 }
395                                 /* no break */
396                         case 0x7fff:
397                                 tag |= 2;               /* 10 special */
398                                 break;
399                         default:
400                                 if((reg[3] & 0x8000) == 0)
401                                         break;          /* 00 valid */
402                                 tag |= 2;               /* 10 special */
403                                 break;
404                         }
405                 }else{
406                         tag |= 3;                       /* 11 empty */
407                 }
408         }
409
410 #define MOVA(d,s) \
411         *((ulong*)(d)) = *((ulong*)(s)), \
412         *((ulong*)(d+4)) = *((ulong*)(s+4)), \
413         *((ushort*)(d+8)) = *((ushort*)(s+8))
414
415         MOVA(fps->regs+00, fps->xregs+0x00);
416         MOVA(fps->regs+10, fps->xregs+0x10);
417         MOVA(fps->regs+20, fps->xregs+0x20);
418         MOVA(fps->regs+30, fps->xregs+0x30);
419         MOVA(fps->regs+40, fps->xregs+0x40);
420         MOVA(fps->regs+50, fps->xregs+0x50);
421         MOVA(fps->regs+60, fps->xregs+0x60);
422         MOVA(fps->regs+70, fps->xregs+0x70);
423
424 #undef MOVA
425
426         fps->oselector = fps->ds;
427         fps->operand = fps->fpudp;
428         fps->opcode = fps->fop & 0x7ff;
429         fps->selector = fps->cs;
430         fps->pc = fps->fpuip;
431         fps->tag = tag;
432         fps->status = fps->fsw;
433         /* NOP fps->control = fps->fcw;  */
434
435         fps->r1 = fps->r2 = fps->r3 = fps->r4 = 0;
436
437         fpx87restore0(fps);
438 }
439
440 static char* mathmsg[] =
441 {
442         nil,    /* handled below */
443         "denormalized operand",
444         "division by zero",
445         "numeric overflow",
446         "numeric underflow",
447         "precision loss",
448 };
449
450 static void
451 mathnote(ulong status, ulong pc)
452 {
453         char *msg, note[ERRMAX];
454         int i;
455
456         /*
457          * Some attention should probably be paid here to the
458          * exception masks and error summary.
459          */
460         msg = "unknown exception";
461         for(i = 1; i <= 5; i++){
462                 if(!((1<<i) & status))
463                         continue;
464                 msg = mathmsg[i];
465                 break;
466         }
467         if(status & 0x01){
468                 if(status & 0x40){
469                         if(status & 0x200)
470                                 msg = "stack overflow";
471                         else
472                                 msg = "stack underflow";
473                 }else
474                         msg = "invalid operation";
475         }
476         snprint(note, sizeof note, "sys: fp: %s fppc=0x%lux status=0x%lux",
477                 msg, pc, status);
478         postnote(up, 1, note, NDebug);
479 }
480
481 /*
482  *  math coprocessor error
483  */
484 static void
485 matherror(Ureg*, void*)
486 {
487         /*
488          *  a write cycle to port 0xF0 clears the interrupt latch attached
489          *  to the error# line from the 387
490          */
491         if(!(m->cpuiddx & Fpuonchip))
492                 outb(0xF0, 0xFF);
493
494         /*
495          *  get floating point state to check out error
496          */
497         fpsave(up->fpsave);
498         up->fpstate = FPinactive;
499         mathnote(up->fpsave->fsw, up->fpsave->fpuip);
500 }
501
502 /*
503  *  SIMD error
504  */
505 static void
506 simderror(Ureg *ureg, void*)
507 {
508         fpsave(up->fpsave);
509         up->fpstate = FPinactive;
510         mathnote(up->fpsave->mxcsr & 0x3f, ureg->pc);
511 }
512
513 /*
514  *  math coprocessor emulation fault
515  */
516 static void
517 mathemu(Ureg *ureg, void*)
518 {
519         ulong status, control;
520
521         if(up->fpstate & FPillegal){
522                 /* someone did floating point in a note handler */
523                 postnote(up, 1, "sys: floating point in note handler", NDebug);
524                 return;
525         }
526         switch(up->fpstate){
527         case FPinit:
528                 fpinit();
529                 if(fpsave == fpssesave)
530                         ldmxcsr(0);     /* no simd exceptions on 386 */
531                 while(up->fpsave == nil)
532                         up->fpsave = mallocalign(sizeof(FPsave), FPalign, 0, 0);
533                 up->fpstate = FPactive;
534                 break;
535         case FPinactive:
536                 /*
537                  * Before restoring the state, check for any pending
538                  * exceptions, there's no way to restore the state without
539                  * generating an unmasked exception.
540                  * More attention should probably be paid here to the
541                  * exception masks and error summary.
542                  */
543                 status = up->fpsave->fsw;
544                 control = up->fpsave->fcw;
545                 if((status & ~control) & 0x07F){
546                         mathnote(status, up->fpsave->fpuip);
547                         break;
548                 }
549                 fprestore(up->fpsave);
550                 up->fpstate = FPactive;
551                 break;
552         case FPactive:
553                 panic("math emu pid %ld %s pc 0x%lux", 
554                         up->pid, up->text, ureg->pc);
555                 break;
556         }
557 }
558
559 /*
560  *  math coprocessor segment overrun
561  */
562 static void
563 mathover(Ureg*, void*)
564 {
565         pexit("math overrun", 0);
566 }
567
568 void
569 mathinit(void)
570 {
571         trapenable(VectorCERR, matherror, 0, "matherror");
572         if(X86FAMILY(m->cpuidax) == 3)
573                 intrenable(IrqIRQ13, matherror, 0, BUSUNKNOWN, "matherror");
574         trapenable(VectorCNA, mathemu, 0, "mathemu");
575         trapenable(VectorCSO, mathover, 0, "mathover");
576         trapenable(VectorSIMD, simderror, 0, "simderror");
577 }
578
579 /*
580  *  set up floating point for a new process
581  */
582 void
583 procsetup(Proc *p)
584 {
585         p->fpstate = FPinit;
586         fpoff();
587
588         cycles(&p->kentry);
589         p->pcycles = -p->kentry;
590
591         memset(p->gdt, 0, sizeof(p->gdt));
592         p->ldt = nil;
593         p->nldt = 0;
594         
595         memset(p->dr, 0, sizeof(p->dr));
596 }
597
598 void
599 procfork(Proc *p)
600 {
601         int s;
602
603         p->kentry = up->kentry;
604         p->pcycles = -p->kentry;
605
606         /* inherit user descriptors */
607         memmove(p->gdt, up->gdt, sizeof(p->gdt));
608
609         /* copy local descriptor table */
610         if(up->ldt != nil && up->nldt > 0){
611                 p->ldt = smalloc(sizeof(Segdesc) * up->nldt);
612                 memmove(p->ldt, up->ldt, sizeof(Segdesc) * up->nldt);
613                 p->nldt = up->nldt;
614         }
615
616         /* save floating point state */
617         s = splhi();
618         switch(up->fpstate & ~FPillegal){
619         case FPactive:
620                 fpsave(up->fpsave);
621                 up->fpstate = FPinactive;
622         case FPinactive:
623                 while(p->fpsave == nil)
624                         p->fpsave = mallocalign(sizeof(FPsave), FPalign, 0, 0);
625                 memmove(p->fpsave, up->fpsave, sizeof(FPsave));
626                 p->fpstate = FPinactive;
627         }
628         
629         /* clear debug registers */
630         memset(p->dr, 0, sizeof(p->dr));
631         splx(s);
632 }
633
634 void
635 procrestore(Proc *p)
636 {
637         uvlong t;
638         
639         if(p->dr[7] != 0){
640                 m->dr7 = p->dr[7];
641                 putdr(p->dr);
642         }
643         
644         if(p->vmx != nil)
645                 vmxprocrestore(p);
646
647         if(p->kp)
648                 return;
649
650         cycles(&t);
651         p->kentry += t;
652         p->pcycles -= t;
653 }
654
655 /*
656  *  Save the mach dependent part of the process state.
657  */
658 void
659 procsave(Proc *p)
660 {
661         uvlong t;
662         
663         /* we could just always putdr7(0) but accessing DR7 might be slow in a VM */
664         if(m->dr7 != 0){
665                 m->dr7 = 0;
666                 putdr7(0);
667         }
668
669         cycles(&t);
670         p->kentry -= t;
671         p->pcycles += t;
672
673         if(p->fpstate == FPactive){
674                 if(p->state == Moribund)
675                         fpclear();
676                 else{
677                         /*
678                          * Fpsave() stores without handling pending
679                          * unmasked exeptions. Postnote() can't be called
680                          * here as sleep() already has up->rlock, so
681                          * the handling of pending exceptions is delayed
682                          * until the process runs again and generates an
683                          * emulation fault to activate the FPU.
684                          */
685                         fpsave(p->fpsave);
686                 }
687                 p->fpstate = FPinactive;
688         }
689
690         /*
691          * While this processor is in the scheduler, the process could run
692          * on another processor and exit, returning the page tables to
693          * the free list where they could be reallocated and overwritten.
694          * When this processor eventually has to get an entry from the
695          * trashed page tables it will crash.
696          *
697          * If there's only one processor, this can't happen.
698          * You might think it would be a win not to do this in that case,
699          * especially on VMware, but it turns out not to matter.
700          */
701         mmuflushtlb(PADDR(m->pdb));
702 }
703
704 void
705 reboot(void *entry, void *code, ulong size)
706 {
707         void (*f)(ulong, ulong, ulong);
708         ulong *pdb;
709
710         writeconf();
711         vmxshutdown();
712
713         /*
714          * the boot processor is cpu0.  execute this function on it
715          * so that the new kernel has the same cpu0.  this only matters
716          * because the hardware has a notion of which processor was the
717          * boot processor and we look at it at start up.
718          */
719         if (m->machno != 0) {
720                 procwired(up, 0);
721                 sched();
722         }
723         cpushutdown();
724
725         splhi();
726
727         /* turn off buffered serial console */
728         serialoq = nil;
729
730         /* shutdown devices */
731         chandevshutdown();
732         arch->introff();
733
734         /*
735          * Modify the machine page table to directly map the low 4MB of memory
736          * This allows the reboot code to turn off the page mapping
737          */
738         pdb = m->pdb;
739         pdb[PDX(0)] = pdb[PDX(KZERO)];
740         mmuflushtlb(PADDR(pdb));
741
742         /* setup reboot trampoline function */
743         f = (void*)REBOOTADDR;
744         memmove(f, rebootcode, sizeof(rebootcode));
745
746         /* off we go - never to return */
747         coherence();
748         (*f)((ulong)entry & ~0xF0000000UL, PADDR(code), size);
749 }
750
751
752 void
753 exit(int)
754 {
755         cpushutdown();
756         arch->reset();
757 }