]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc64/main.c
merge
[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         swapinit();
336         userinit();
337         schedinit();
338 }
339
340 void
341 exit(int)
342 {
343         cpushutdown();
344         arch->reset();
345 }
346
347 void
348 reboot(void *entry, void *code, ulong size)
349 {
350         void (*f)(uintptr, uintptr, ulong);
351
352         writeconf();
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  * There are opportunities to be lazier about saving and
396  * restoring the state and allocating the storage needed.
397  */
398 extern void _clts(void);
399 extern void _fldcw(u16int);
400 extern void _fnclex(void);
401 extern void _fninit(void);
402 extern void _fxrstor(Fxsave*);
403 extern void _fxsave(Fxsave*);
404 extern void _fwait(void);
405 extern void _ldmxcsr(u32int);
406 extern void _stts(void);
407
408 /*
409  * not used, AMD64 mandated SSE
410  */
411 void
412 fpx87save(FPsave*)
413 {
414 }
415 void
416 fpx87restore(FPsave*)
417 {
418 }
419
420 void
421 fpssesave(FPsave *fps)
422 {
423         Fxsave *fx = (Fxsave*)ROUND(((uintptr)fps), FPalign);
424
425         _fxsave(fx);
426         _stts();
427         if(fx != (Fxsave*)fps)
428                 memmove((Fxsave*)fps, fx, sizeof(Fxsave));
429 }
430 void
431 fpsserestore(FPsave *fps)
432 {
433         Fxsave *fx = (Fxsave*)ROUND(((uintptr)fps), FPalign);
434
435         if(fx != (Fxsave*)fps)
436                 memmove(fx, (Fxsave*)fps, sizeof(Fxsave));
437         _clts();
438         _fxrstor(fx);
439 }
440
441 static char* mathmsg[] =
442 {
443         nil,    /* handled below */
444         "denormalized operand",
445         "division by zero",
446         "numeric overflow",
447         "numeric underflow",
448         "precision loss",
449 };
450
451 static void
452 mathnote(ulong status, uintptr pc)
453 {
454         char *msg, note[ERRMAX];
455         int i;
456
457         /*
458          * Some attention should probably be paid here to the
459          * exception masks and error summary.
460          */
461         msg = "unknown exception";
462         for(i = 1; i <= 5; i++){
463                 if(!((1<<i) & status))
464                         continue;
465                 msg = mathmsg[i];
466                 break;
467         }
468         if(status & 0x01){
469                 if(status & 0x40){
470                         if(status & 0x200)
471                                 msg = "stack overflow";
472                         else
473                                 msg = "stack underflow";
474                 }else
475                         msg = "invalid operation";
476         }
477         snprint(note, sizeof note, "sys: fp: %s fppc=%#p status=0x%lux",
478                 msg, pc, status);
479         postnote(up, 1, note, NDebug);
480 }
481
482 /*
483  *  math coprocessor error
484  */
485 static void
486 matherror(Ureg*, void*)
487 {
488         /*
489          * Save FPU state to check out the error.
490          */
491         fpsave(&up->fpsave);
492         up->fpstate = FPinactive;
493         mathnote(up->fpsave.fsw, up->fpsave.rip);
494 }
495
496 /*
497  *  SIMD error
498  */
499 static void
500 simderror(Ureg *ureg, void*)
501 {
502         fpsave(&up->fpsave);
503         up->fpstate = FPinactive;
504         mathnote(up->fpsave.mxcsr & 0x3f, ureg->pc);
505 }
506
507 void
508 fpinit(void)
509 {
510         /*
511          * A process tries to use the FPU for the
512          * first time and generates a 'device not available'
513          * exception.
514          * Turn the FPU on and initialise it for use.
515          * Set the precision and mask the exceptions
516          * we don't care about from the generic Mach value.
517          */
518         _clts();
519         _fninit();
520         _fwait();
521         _fldcw(0x0232);
522         _ldmxcsr(0x1900);
523 }
524
525 /*
526  *  math coprocessor emulation fault
527  */
528 static void
529 mathemu(Ureg *ureg, void*)
530 {
531         ulong status, control;
532
533         if(up->fpstate & FPillegal){
534                 /* someone did floating point in a note handler */
535                 postnote(up, 1, "sys: floating point in note handler", NDebug);
536                 return;
537         }
538         switch(up->fpstate){
539         case FPinit:
540                 fpinit();
541                 up->fpstate = FPactive;
542                 break;
543         case FPinactive:
544                 /*
545                  * Before restoring the state, check for any pending
546                  * exceptions, there's no way to restore the state without
547                  * generating an unmasked exception.
548                  * More attention should probably be paid here to the
549                  * exception masks and error summary.
550                  */
551                 status = up->fpsave.fsw;
552                 control = up->fpsave.fcw;
553                 if((status & ~control) & 0x07F){
554                         mathnote(status, up->fpsave.rip);
555                         break;
556                 }
557                 fprestore(&up->fpsave);
558                 up->fpstate = FPactive;
559                 break;
560         case FPactive:
561                 panic("math emu pid %ld %s pc %#p", 
562                         up->pid, up->text, ureg->pc);
563                 break;
564         }
565 }
566
567 /*
568  *  math coprocessor segment overrun
569  */
570 static void
571 mathover(Ureg*, void*)
572 {
573         pexit("math overrun", 0);
574 }
575
576 void
577 mathinit(void)
578 {
579         trapenable(VectorCERR, matherror, 0, "matherror");
580         if(X86FAMILY(m->cpuidax) == 3)
581                 intrenable(IrqIRQ13, matherror, 0, BUSUNKNOWN, "matherror");
582         trapenable(VectorCNA, mathemu, 0, "mathemu");
583         trapenable(VectorCSO, mathover, 0, "mathover");
584         trapenable(VectorSIMD, simderror, 0, "simderror");
585 }
586
587 void
588 procsetup(Proc *p)
589 {
590         p->fpstate = FPinit;
591         _stts();
592         cycles(&p->kentry);
593         p->pcycles = -p->kentry;
594 }
595
596 void
597 procfork(Proc *p)
598 {
599         int s;
600
601         p->kentry = up->kentry;
602         p->pcycles = -p->kentry;
603
604         /* save floating point state */
605         s = splhi();
606         switch(up->fpstate & ~FPillegal){
607         case FPactive:
608                 fpsave(&up->fpsave);
609                 up->fpstate = FPinactive;
610         case FPinactive:
611                 p->fpsave = up->fpsave;
612                 p->fpstate = FPinactive;
613         }
614         splx(s);
615
616 }
617
618 void
619 procrestore(Proc *p)
620 {
621         uvlong t;
622         
623         if(p->dr[7] != 0){
624                 m->dr7 = p->dr[7];
625                 putdr(p->dr);
626         }
627         
628         if(p->vmx != nil)
629                 vmxprocrestore(p);
630
631         if(p->kp)
632                 return;
633
634         cycles(&t);
635         p->kentry += t;
636         p->pcycles -= t;
637 }
638
639 void
640 procsave(Proc *p)
641 {
642         uvlong t;
643         
644         if(m->dr7 != 0){
645                 m->dr7 = 0;
646                 putdr7(0);
647         }
648
649         cycles(&t);
650         p->kentry -= t;
651         p->pcycles += t;
652
653         if(p->fpstate == FPactive){
654                 if(p->state == Moribund){
655                         _clts();
656                         _fnclex();
657                         _stts();
658                 }
659                 else{
660                         /*
661                          * Fpsave() stores without handling pending
662                          * unmasked exeptions. Postnote() can't be called
663                          * here as sleep() already has up->rlock, so
664                          * the handling of pending exceptions is delayed
665                          * until the process runs again and generates an
666                          * emulation fault to activate the FPU.
667                          */
668                         fpsave(&p->fpsave);
669                 }
670                 p->fpstate = FPinactive;
671         }
672
673         /*
674          * While this processor is in the scheduler, the process could run
675          * on another processor and exit, returning the page tables to
676          * the free list where they could be reallocated and overwritten.
677          * When this processor eventually has to get an entry from the
678          * trashed page tables it will crash.
679          *
680          * If there's only one processor, this can't happen.
681          * You might think it would be a win not to do this in that case,
682          * especially on VMware, but it turns out not to matter.
683          */
684         mmuflushtlb();
685 }