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