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