]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/pc64/main.c
pc64: multiboot support
[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
12 /*
13  * Where configuration info is left for the loaded programme.
14  * This will turn into a structure as more is done by the boot loader
15  * (e.g. why parse the .ini file twice?).
16  * There are 3584 bytes available at CONFADDR.
17  */
18 #define BOOTLINE        ((char*)CONFADDR)
19 #define BOOTLINELEN     64
20 #define BOOTARGS        ((char*)(CONFADDR+BOOTLINELEN))
21 #define BOOTARGSLEN     (4096-0x200-BOOTLINELEN)
22 #define MAXCONF         64
23
24 Conf conf;
25 char *confname[MAXCONF];
26 char *confval[MAXCONF];
27 int nconf;
28 int delaylink;
29 int idle_spin;
30
31 uchar *sp;      /* user stack of init proc */
32
33 extern void (*i8237alloc)(void);
34
35 static void
36 multibootargs(void)
37 {
38         extern ulong multibootptr;
39         ulong *multiboot;
40         char *cp, *ep;
41         ulong *m, l;
42
43         if(multibootptr == 0)
44                 return;
45
46         multiboot = (ulong*)KADDR(multibootptr);
47         /* command line */
48         if((multiboot[0] & (1<<2)) != 0)
49                 strncpy(BOOTLINE, KADDR(multiboot[4]), BOOTLINELEN-1);
50
51         cp = BOOTARGS;
52         ep = cp + BOOTARGSLEN-1;
53
54         /* memory map */
55         if((multiboot[0] & (1<<6)) != 0 && (l = multiboot[11]) >= 24){
56                 cp = seprint(cp, ep, "*e820=");
57                 m = KADDR(multiboot[12]);
58                 while(m[0] >= 20 && m[0] <= l-4){
59                         uvlong base, size;
60                         m++;
61                         base = ((uvlong)m[0] | (uvlong)m[1]<<32);
62                         size = ((uvlong)m[2] | (uvlong)m[3]<<32);
63                         cp = seprint(cp, ep, "%.1lux %.16llux %.16llux ",
64                                 m[4] & 0xF, base, base+size);
65                         l -= m[-1]+4;
66                         m = (ulong*)((uintptr)m + m[-1]);
67                 }
68                 cp[-1] = '\n';
69         }
70
71         /* plan9.ini passed as the first module */
72         if((multiboot[0] & (1<<3)) != 0 && multiboot[5] > 0){
73                 m = KADDR(multiboot[6]);
74                 l = m[1] - m[0];
75                 m = KADDR(m[0]);
76                 if(cp+l > ep)
77                         l = ep - cp;
78                 memmove(cp, m, l);
79                 cp += l;
80         }
81         *cp = 0;
82 }
83
84 static void
85 options(void)
86 {
87         long i, n;
88         char *cp, *line[MAXCONF], *p, *q;
89
90         multibootargs();
91
92         /*
93          *  parse configuration args from dos file plan9.ini
94          */
95         cp = BOOTARGS;  /* where b.com leaves its config */
96         cp[BOOTARGSLEN-1] = 0;
97
98         /*
99          * Strip out '\r', change '\t' -> ' '.
100          */
101         p = cp;
102         for(q = cp; *q; q++){
103                 if(*q == '\r')
104                         continue;
105                 if(*q == '\t')
106                         *q = ' ';
107                 *p++ = *q;
108         }
109         *p = 0;
110
111         n = getfields(cp, line, MAXCONF, 1, "\n");
112         for(i = 0; i < n; i++){
113                 if(*line[i] == '#')
114                         continue;
115                 cp = strchr(line[i], '=');
116                 if(cp == nil)
117                         continue;
118                 *cp++ = '\0';
119                 confname[nconf] = line[i];
120                 confval[nconf] = cp;
121                 nconf++;
122         }
123 }
124
125 char*
126 getconf(char *name)
127 {
128         int i;
129
130         for(i = 0; i < nconf; i++)
131                 if(cistrcmp(confname[i], name) == 0)
132                         return confval[i];
133         return 0;
134 }
135
136 void
137 confinit(void)
138 {
139         char *p;
140         int i, userpcnt;
141         ulong kpages;
142
143         if(p = getconf("*kernelpercent"))
144                 userpcnt = 100 - strtol(p, 0, 0);
145         else
146                 userpcnt = 0;
147
148         conf.npage = 0;
149         for(i=0; i<nelem(conf.mem); i++)
150                 conf.npage += conf.mem[i].npage;
151
152         conf.nproc = 100 + ((conf.npage*BY2PG)/MB)*5;
153         if(cpuserver)
154                 conf.nproc *= 3;
155         if(conf.nproc > 2000)
156                 conf.nproc = 2000;
157         conf.nimage = 200;
158         conf.nswap = conf.nproc*80;
159         conf.nswppo = 4096;
160
161         if(cpuserver) {
162                 if(userpcnt < 10)
163                         userpcnt = 70;
164                 kpages = conf.npage - (conf.npage*userpcnt)/100;
165
166                 /*
167                  * Hack for the big boys. Only good while physmem < 4GB.
168                  * Give the kernel fixed max + enough to allocate the
169                  * page pool.
170                  * This is an overestimate as conf.upages < conf.npages.
171                  * The patch of nimage is a band-aid, scanning the whole
172                  * page list in imagereclaim just takes too long.
173                  */
174                 if(getconf("*imagemaxmb") == 0)
175                 if(kpages > (64*MB + conf.npage*sizeof(Page))/BY2PG){
176                         kpages = (64*MB + conf.npage*sizeof(Page))/BY2PG;
177                         conf.nimage = 2000;
178                         kpages += (conf.nproc*KSTACK)/BY2PG;
179                 }
180         } else {
181                 if(userpcnt < 10) {
182                         if(conf.npage*BY2PG < 16*MB)
183                                 userpcnt = 50;
184                         else
185                                 userpcnt = 60;
186                 }
187                 kpages = conf.npage - (conf.npage*userpcnt)/100;
188
189                 /*
190                  * Make sure terminals with low memory get at least
191                  * 4MB on the first Image chunk allocation.
192                  */
193                 if(conf.npage*BY2PG < 16*MB)
194                         imagmem->minarena = 4*MB;
195         }
196
197         /*
198          * can't go past the end of virtual memory.
199          */
200         if(kpages > ((uintptr)-KZERO)/BY2PG)
201                 kpages = ((uintptr)-KZERO)/BY2PG;
202
203         conf.upages = conf.npage - kpages;
204         conf.ialloc = (kpages/2)*BY2PG;
205
206         /*
207          * Guess how much is taken by the large permanent
208          * datastructures. Mntcache and Mntrpc are not accounted for
209          * (probably ~300KB).
210          */
211         kpages *= BY2PG;
212         kpages -= conf.upages*sizeof(Page)
213                 + conf.nproc*sizeof(Proc)
214                 + conf.nimage*sizeof(Image)
215                 + conf.nswap
216                 + conf.nswppo*sizeof(Page*);
217         mainmem->maxsize = kpages;
218
219         /*
220          * the dynamic allocation will balance the load properly,
221          * hopefully. be careful with 32-bit overflow.
222          */
223         imagmem->maxsize = kpages - (kpages/10);
224         if(p = getconf("*imagemaxmb")){
225                 imagmem->maxsize = strtol(p, nil, 0)*MB;
226                 if(imagmem->maxsize > mainmem->maxsize)
227                         imagmem->maxsize = mainmem->maxsize;
228         }
229 }
230
231
232 void
233 machinit(void)
234 {
235         int machno;
236         Segdesc *gdt;
237         uintptr *pml4;
238
239         machno = m->machno;
240         pml4 = m->pml4;
241         gdt = m->gdt;
242         memset(m, 0, sizeof(Mach));
243         m->machno = machno;
244         m->pml4 = pml4;
245         m->gdt = gdt;
246         m->perf.period = 1;
247
248         /*
249          * For polled uart output at boot, need
250          * a default delay constant. 100000 should
251          * be enough for a while. Cpuidentify will
252          * calculate the real value later.
253          */
254         m->loopconst = 100000;
255 }
256
257 void
258 mach0init(void)
259 {
260         conf.nmach = 1;
261
262         MACHP(0) = (Mach*)CPU0MACH;
263
264         m->machno = 0;
265         m->pml4 = (u64int*)CPU0PML4;
266         m->gdt = (Segdesc*)CPU0GDT;
267
268         machinit();
269
270         active.machs = 1;
271         active.exiting = 0;
272 }
273
274
275 uchar *
276 pusharg(char *p)
277 {
278         int n;
279
280         n = strlen(p)+1;
281         sp -= n;
282         memmove(sp, p, n);
283         return sp;
284 }
285
286 void
287 bootargs(void *base)
288 {
289         int i, ac;
290         uchar *av[32];
291         uchar **lsp;
292         char *cp = BOOTLINE;
293         char buf[64];
294
295         sp = (uchar*)base + BY2PG - sizeof(Tos);
296
297         ac = 0;
298         av[ac++] = pusharg("boot");
299
300         /* when boot is changed to only use rc, this code can go away */
301         cp[BOOTLINELEN-1] = 0;
302         buf[0] = 0;
303         if(strncmp(cp, "fd", 2) == 0){
304                 sprint(buf, "local!#f/fd%lddisk", strtol(cp+2, 0, 0));
305                 av[ac++] = pusharg(buf);
306         } else if(strncmp(cp, "sd", 2) == 0){
307                 sprint(buf, "local!#S/sd%c%c/fs", *(cp+2), *(cp+3));
308                 av[ac++] = pusharg(buf);
309         } else if(strncmp(cp, "ether", 5) == 0)
310                 av[ac++] = pusharg("-n");
311
312         /* 8 byte word align stack */
313         sp = (uchar*)((uintptr)sp & ~7);
314
315         /* build argc, argv on stack */
316         sp -= (ac+1)*sizeof(sp);
317         lsp = (uchar**)sp;
318         for(i = 0; i < ac; i++)
319                 lsp[i] = av[i] + ((uintptr)(USTKTOP - BY2PG) - (uintptr)base);
320         lsp[i] = 0;
321         sp += (uintptr)(USTKTOP - BY2PG) - (uintptr)base;
322         sp -= BY2WD;
323 }
324
325 void
326 init0(void)
327 {
328         int i;
329         char buf[2*KNAMELEN];
330
331         up->nerrlab = 0;
332
333         spllo();
334
335         /*
336          * These are o.k. because rootinit is null.
337          * Then early kproc's will have a root and dot.
338          */
339         up->slash = namec("#/", Atodir, 0, 0);
340         pathclose(up->slash->path);
341         up->slash->path = newpath("/");
342         up->dot = cclone(up->slash);
343
344         chandevinit();
345
346         if(!waserror()){
347                 snprint(buf, sizeof(buf), "%s %s", arch->id, conffile);
348                 ksetenv("terminal", buf, 0);
349                 ksetenv("cputype", "amd64", 0);
350                 if(cpuserver)
351                         ksetenv("service", "cpu", 0);
352                 else
353                         ksetenv("service", "terminal", 0);
354                 for(i = 0; i < nconf; i++){
355                         if(confname[i][0] != '*')
356                                 ksetenv(confname[i], confval[i], 0);
357                         ksetenv(confname[i], confval[i], 1);
358                 }
359                 poperror();
360         }
361         kproc("alarm", alarmkproc, 0);
362
363         touser(sp);
364 }
365
366 void
367 userinit(void)
368 {
369         void *v;
370         Proc *p;
371         Segment *s;
372         Page *pg;
373
374         p = newproc();
375         p->pgrp = newpgrp();
376         p->egrp = smalloc(sizeof(Egrp));
377         p->egrp->ref = 1;
378         p->fgrp = dupfgrp(nil);
379         p->rgrp = newrgrp();
380         p->procmode = 0640;
381
382         kstrdup(&eve, "");
383         kstrdup(&p->text, "*init*");
384         kstrdup(&p->user, eve);
385
386         procsetup(p);
387
388         /*
389          * Kernel Stack
390          *
391          * N.B. make sure there's enough space for syscall to check
392          *      for valid args and 
393          *      8 bytes for gotolabel's return PC
394          */
395         p->sched.pc = (uintptr)init0;
396         p->sched.sp = (uintptr)p->kstack+KSTACK-(sizeof(Sargs)+BY2WD);
397
398         /* temporarily set up for kmap() */
399         up = p;
400
401         /*
402          * User Stack
403          */
404         s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
405         p->seg[SSEG] = s;
406         pg = newpage(0, 0, USTKTOP-BY2PG);
407         v = kmap(pg);
408         memset(v, 0, BY2PG);
409         segpage(s, pg);
410         bootargs(v);
411         kunmap(v);
412
413         /*
414          * Text
415          */
416         s = newseg(SG_TEXT, UTZERO, 1);
417         s->flushme++;
418         p->seg[TSEG] = s;
419         pg = newpage(0, 0, UTZERO);
420         memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
421         segpage(s, pg);
422         v = kmap(pg);
423         memset(v, 0, BY2PG);
424         memmove(v, initcode, sizeof initcode);
425         kunmap(v);
426
427         /* free kmap */
428         mmurelease(p);
429         up = nil;
430
431         ready(p);
432 }
433
434 void
435 main()
436 {
437         mach0init();
438         options();
439         ioinit();
440         // i8250console();
441         quotefmtinstall();
442         screeninit();
443         trapinit0();
444         kbdinit();
445         i8253init();
446         cpuidentify();
447         meminit();
448         confinit();
449         archinit();
450         xinit();
451         if(i8237alloc != nil)
452                 i8237alloc();
453         trapinit();
454         printinit();
455         cpuidprint();
456         mmuinit();
457         if(arch->intrinit)
458                 arch->intrinit();
459         timersinit();
460         mathinit();
461         kbdenable();
462         if(arch->clockenable)
463                 arch->clockenable();
464         procinit0();
465         initseg();
466         if(delaylink){
467                 bootlinks();
468                 pcimatch(0, 0, 0);
469         }else
470                 links();
471         conf.monitor = 1;
472         chandevreset();
473         pageinit();
474         swapinit();
475         userinit();
476         active.thunderbirdsarego = 1;
477         schedinit();
478 }
479
480 static void
481 shutdown(int ispanic)
482 {
483         int ms, once;
484
485         lock(&active);
486         if(ispanic)
487                 active.ispanic = ispanic;
488         else if(m->machno == 0 && (active.machs & (1<<m->machno)) == 0)
489                 active.ispanic = 0;
490         once = active.machs & (1<<m->machno);
491         /*
492          * setting exiting will make hzclock() on each processor call exit(0),
493          * which calls shutdown(0) and arch->reset(), which on mp systems is
494          * mpshutdown, from which there is no return: the processor is idled
495          * or initiates a reboot.  clearing our bit in machs avoids calling
496          * exit(0) from hzclock() on this processor.
497          */
498         active.machs &= ~(1<<m->machno);
499         active.exiting = 1;
500         unlock(&active);
501
502         if(once)
503                 iprint("cpu%d: exiting\n", m->machno);
504
505         /* wait for any other processors to shutdown */
506         spllo();
507         for(ms = 5*1000; ms > 0; ms -= TK2MS(2)){
508                 delay(TK2MS(2));
509                 if(active.machs == 0 && consactive() == 0)
510                         break;
511         }
512
513         if(active.ispanic){
514                 if(!cpuserver)
515                         for(;;)
516                                 halt();
517                 if(getconf("*debug"))
518                         delay(5*60*1000);
519                 else
520                         delay(10000);
521         }else
522                 delay(1000);
523 }
524
525 void
526 exit(int ispanic)
527 {
528         shutdown(ispanic);
529         arch->reset();
530 }
531
532 void
533 reboot(void*, void*, ulong)
534 {
535         exit(0);
536 }
537
538 /*
539  * SIMD Floating Point.
540  * Assembler support to get at the individual instructions
541  * is in l.s.
542  * There are opportunities to be lazier about saving and
543  * restoring the state and allocating the storage needed.
544  */
545 extern void _clts(void);
546 extern void _fldcw(u16int);
547 extern void _fnclex(void);
548 extern void _fninit(void);
549 extern void _fxrstor(Fxsave*);
550 extern void _fxsave(Fxsave*);
551 extern void _fwait(void);
552 extern void _ldmxcsr(u32int);
553 extern void _stts(void);
554
555 /*
556  * not used, AMD64 mandated SSE
557  */
558 void
559 fpx87save(FPsave*)
560 {
561 }
562 void
563 fpx87restore(FPsave*)
564 {
565 }
566
567 void
568 fpssesave(FPsave *fps)
569 {
570         Fxsave *fx = (Fxsave*)ROUND(((uintptr)fps), FPalign);
571
572         _fxsave(fx);
573         _stts();
574         if(fx != (Fxsave*)fps)
575                 memmove((Fxsave*)fps, fx, sizeof(Fxsave));
576 }
577 void
578 fpsserestore(FPsave *fps)
579 {
580         Fxsave *fx = (Fxsave*)ROUND(((uintptr)fps), FPalign);
581
582         if(fx != (Fxsave*)fps)
583                 memmove(fx, (Fxsave*)fps, sizeof(Fxsave));
584         _clts();
585         _fxrstor(fx);
586 }
587
588 static char* mathmsg[] =
589 {
590         nil,    /* handled below */
591         "denormalized operand",
592         "division by zero",
593         "numeric overflow",
594         "numeric underflow",
595         "precision loss",
596 };
597
598 static void
599 mathnote(ulong status, uintptr pc)
600 {
601         char *msg, note[ERRMAX];
602         int i;
603
604         /*
605          * Some attention should probably be paid here to the
606          * exception masks and error summary.
607          */
608         msg = "unknown exception";
609         for(i = 1; i <= 5; i++){
610                 if(!((1<<i) & status))
611                         continue;
612                 msg = mathmsg[i];
613                 break;
614         }
615         if(status & 0x01){
616                 if(status & 0x40){
617                         if(status & 0x200)
618                                 msg = "stack overflow";
619                         else
620                                 msg = "stack underflow";
621                 }else
622                         msg = "invalid operation";
623         }
624         snprint(note, sizeof note, "sys: fp: %s fppc=%#p status=0x%lux",
625                 msg, pc, status);
626         postnote(up, 1, note, NDebug);
627 }
628
629 /*
630  *  math coprocessor error
631  */
632 static void
633 matherror(Ureg*, void*)
634 {
635         /*
636          * Save FPU state to check out the error.
637          */
638         fpsave(&up->fpsave);
639         up->fpstate = FPinactive;
640         mathnote(up->fpsave.fsw, up->fpsave.rip);
641 }
642
643 /*
644  *  math coprocessor emulation fault
645  */
646 static void
647 mathemu(Ureg *ureg, void*)
648 {
649         ulong status, control;
650
651         if(up->fpstate & FPillegal){
652                 /* someone did floating point in a note handler */
653                 postnote(up, 1, "sys: floating point in note handler", NDebug);
654                 return;
655         }
656         switch(up->fpstate){
657         case FPinit:
658                 /*
659                  * A process tries to use the FPU for the
660                  * first time and generates a 'device not available'
661                  * exception.
662                  * Turn the FPU on and initialise it for use.
663                  * Set the precision and mask the exceptions
664                  * we don't care about from the generic Mach value.
665                  */
666                 _clts();
667                 _fninit();
668                 _fwait();
669                 _fldcw(0x0232);
670                 /*
671                  * TODO: sse exceptions
672                  * _ldmxcsr(m->mxcsr);
673                  *
674                  */
675                 up->fpstate = FPactive;
676                 break;
677         case FPinactive:
678                 /*
679                  * Before restoring the state, check for any pending
680                  * exceptions, there's no way to restore the state without
681                  * generating an unmasked exception.
682                  * More attention should probably be paid here to the
683                  * exception masks and error summary.
684                  */
685                 status = up->fpsave.fsw;
686                 control = up->fpsave.fcw;
687                 if((status & ~control) & 0x07F){
688                         mathnote(status, up->fpsave.rip);
689                         break;
690                 }
691                 fprestore(&up->fpsave);
692                 up->fpstate = FPactive;
693                 break;
694         case FPactive:
695                 panic("math emu pid %ld %s pc %#p", 
696                         up->pid, up->text, ureg->pc);
697                 break;
698         }
699 }
700
701 /*
702  *  math coprocessor segment overrun
703  */
704 static void
705 mathover(Ureg*, void*)
706 {
707         pexit("math overrun", 0);
708 }
709
710 void
711 mathinit(void)
712 {
713         trapenable(VectorCERR, matherror, 0, "matherror");
714         if(X86FAMILY(m->cpuidax) == 3)
715                 intrenable(IrqIRQ13, matherror, 0, BUSUNKNOWN, "matherror");
716         trapenable(VectorCNA, mathemu, 0, "mathemu");
717         trapenable(VectorCSO, mathover, 0, "mathover");
718 }
719
720 void
721 procsetup(Proc *p)
722 {
723         p->fpstate = FPinit;
724         _stts();
725         cycles(&p->kentry);
726         p->pcycles = -p->kentry;
727 }
728
729 void
730 procfork(Proc *p)
731 {
732         int s;
733
734         p->kentry = up->kentry;
735         p->pcycles = -p->kentry;
736
737         /* save floating point state */
738         s = splhi();
739         switch(up->fpstate & ~FPillegal){
740         case FPactive:
741                 fpsave(&up->fpsave);
742                 up->fpstate = FPinactive;
743         case FPinactive:
744                 p->fpsave = up->fpsave;
745                 p->fpstate = FPinactive;
746         }
747         splx(s);
748
749 }
750
751 void
752 procrestore(Proc *p)
753 {
754         uvlong t;
755
756         if(p->kp)
757                 return;
758
759         cycles(&t);
760         p->kentry += t;
761         p->pcycles -= t;
762 }
763
764 void
765 procsave(Proc *p)
766 {
767         uvlong t;
768
769         cycles(&t);
770         p->kentry -= t;
771         p->pcycles += t;
772
773         if(p->fpstate == FPactive){
774                 if(p->state == Moribund){
775                         _clts();
776                         _fnclex();
777                         _stts();
778                 }
779                 else{
780                         /*
781                          * Fpsave() stores without handling pending
782                          * unmasked exeptions. Postnote() can't be called
783                          * here as sleep() already has up->rlock, so
784                          * the handling of pending exceptions is delayed
785                          * until the process runs again and generates an
786                          * emulation fault to activate the FPU.
787                          */
788                         fpsave(&p->fpsave);
789                 }
790                 p->fpstate = FPinactive;
791         }
792
793         /*
794          * While this processor is in the scheduler, the process could run
795          * on another processor and exit, returning the page tables to
796          * the free list where they could be reallocated and overwritten.
797          * When this processor eventually has to get an entry from the
798          * trashed page tables it will crash.
799          *
800          * If there's only one processor, this can't happen.
801          * You might think it would be a win not to do this in that case,
802          * especially on VMware, but it turns out not to matter.
803          */
804         mmuflushtlb();
805 }