]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/xen/main.c
devip: cleanup rudp.c
[plan9front.git] / sys / src / 9 / xen / 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        "ureg.h"
8 #include        "init.h"
9 #include        "pool.h"
10 #include        "reboot.h"
11 #include        <tos.h>
12
13 Mach *m;
14
15 #define BOOTARGS        (xenstart->cmd_line)
16 #define BOOTARGSLEN     (sizeof xenstart->cmd_line)
17 #define MAXCONF         64
18
19 enum {
20         /* space for syscall args, return PC, top-of-stack struct */
21         Ustkheadroom    = sizeof(Sargs) + sizeof(uintptr) + sizeof(Tos),
22 };
23
24 Conf conf;
25 char *confname[MAXCONF];
26 char *confval[MAXCONF];
27 int nconf;
28 uchar *sp;      /* user stack of init proc */
29 int idle_spin;
30
31 static void
32 options(void)
33 {
34         long i, n;
35         char *cp, *line[MAXCONF], *p, *q;
36
37         /*
38          *  parse configuration args from dos file plan9.ini
39          */
40         cp = BOOTARGS;  /* where b.com leaves its config */
41         cp[BOOTARGSLEN-1] = 0;
42
43         /*
44          * Strip out '\r', change '\t' -> ' '.
45          */
46         p = cp;
47         for(q = cp; *q; q++){
48                 if(*q == '\r')
49                         continue;
50                 if(*q == '\t')
51                         *q = ' ';
52                 *p++ = *q;
53         }
54         *p = 0;
55
56         n = getfields(cp, line, MAXCONF, 1, "\n");
57         for(i = 0; i < n; i++){
58                 if(*line[i] == '#')
59                         continue;
60                 cp = strchr(line[i], '=');
61                 if(cp == nil)
62                         continue;
63                 *cp++ = '\0';
64                 confname[nconf] = line[i];
65                 confval[nconf] = cp;
66                 nconf++;
67         }
68 }
69
70 void
71 main(void)
72 {
73         mach0init();
74         options();
75         ioinit();
76         xenconsinit();
77         quotefmtinstall();
78
79         //consdebug = rdb;
80         print("\nPlan 9 (%s)\n", xenstart->magic);
81
82         cpuidentify();
83         // meminit() is not for us
84         confinit();
85         archinit();
86         xinit();
87         trapinit();
88         printinit();
89         cpuidprint();
90         mmuinit();
91         if(arch->intrinit)      /* launches other processors on an mp */
92                 arch->intrinit();
93         timersinit();
94         mathinit();
95         kbdenable();
96         xengrantinit();
97         if(arch->clockenable)
98                 arch->clockenable();
99         procinit0();
100         initseg();
101
102         links();
103 //      conf.monitor = 1;
104         chandevreset();
105         pageinit();
106         userinit();
107         schedinit();
108 }
109
110 void
111 mach0init(void)
112 {
113         m = (Mach*)MACHADDR;
114         m->machno = 0;
115         conf.nmach = 1;
116         MACHP(0) = (Mach*)CPU0MACH;
117         m->pdb = (ulong*)xenstart->pt_base;
118
119         machinit();
120
121         active.machs[0] = 1;
122         active.exiting = 0;
123 }
124
125 void
126 machinit(void)
127 {
128         int machno;
129         ulong *pdb;
130
131         machno = m->machno;
132         pdb = m->pdb;
133         memset(m, 0, sizeof(Mach));
134         m->machno = machno;
135         m->pdb = pdb;
136         m->perf.period = 1;
137
138         /*
139          * For polled uart output at boot, need
140          * a default delay constant. 100000 should
141          * be enough for a while. Cpuidentify will
142          * calculate the real value later.
143          */
144         m->loopconst = 100000;
145         m->cpumhz = 1000;                               // XXX! 
146
147         HYPERVISOR_shared_info = (shared_info_t*)mmumapframe(XENSHARED, (xenstart->shared_info)>>PGSHIFT);
148         
149         // XXX m->shared = &HYPERVISOR_shared_info->vcpu_data[m->machno];
150 }
151
152 void
153 init0(void)
154 {
155         int i;
156         char buf[2*KNAMELEN];
157
158         up->nerrlab = 0;
159
160         spllo();
161
162         /*
163          * These are o.k. because rootinit is null.
164          * Then early kproc's will have a root and dot.
165          */
166         up->slash = namec("#/", Atodir, 0, 0);
167         pathclose(up->slash->path);
168         up->slash->path = newpath("/");
169         up->dot = cclone(up->slash);
170
171         chandevinit();
172
173         if(!waserror()){
174                 snprint(buf, sizeof(buf), "%s %s", arch->id, conffile);
175                 ksetenv("terminal", buf, 0);
176                 ksetenv("cputype", "386", 0);
177                 if(cpuserver)
178                         ksetenv("service", "cpu", 0);
179                 else
180                         ksetenv("service", "terminal", 0);
181                 ksetenv("readparts", "1", 0);
182                 for(i = 0; i < nconf; i++){
183                         if(confname[i][0] != '*')
184                                 ksetenv(confname[i], confval[i], 0);
185                         ksetenv(confname[i], confval[i], 1);
186                 }
187                 poperror();
188         }
189
190         kproc("alarm", alarmkproc, 0);
191         touser(sp);
192 }
193
194 void
195 userinit(void)
196 {
197         Proc *p;
198         Segment *s;
199         KMap *k;
200         Page *pg;
201
202         p = newproc();
203         p->pgrp = newpgrp();
204         p->egrp = smalloc(sizeof(Egrp));
205         p->egrp->ref = 1;
206         p->fgrp = dupfgrp(nil);
207         p->rgrp = newrgrp();
208         p->procmode = 0640;
209
210         kstrdup(&eve, "");
211         kstrdup(&p->text, "*init*");
212         kstrdup(&p->user, eve);
213
214         p->fpstate = FPinit;
215         fpoff();
216
217         /*
218          * Kernel Stack
219          *
220          * N.B. make sure there's enough space for syscall to check
221          *      for valid args and 
222          *      4 bytes for gotolabel's return PC
223          */
224         p->sched.pc = (ulong)init0;
225         p->sched.sp = (ulong)p->kstack+KSTACK-(sizeof(Sargs)+BY2WD);
226
227         /*
228          * User Stack
229          */
230         s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
231         p->seg[SSEG] = s;
232         pg = newpage(1, 0, USTKTOP-BY2PG);
233         segpage(s, pg);
234         k = kmap(pg);
235         bootargs(VA(k));
236         kunmap(k);
237
238         /*
239          * Text
240          */
241         s = newseg(SG_TEXT, UTZERO, 1);
242         s->flushme++;
243         p->seg[TSEG] = s;
244         pg = newpage(1, 0, UTZERO);
245         pg->txtflush = ~0;
246         segpage(s, pg);
247         k = kmap(s->map[0]->pages[0]);
248         memmove((ulong*)VA(k), initcode, sizeof initcode);
249         kunmap(k);
250         ready(p);
251 }
252
253 uchar *
254 pusharg(char *p)
255 {
256         int n;
257
258         n = strlen(p)+1;
259         sp -= n;
260         memmove(sp, p, n);
261         return sp;
262 }
263
264 void
265 bootargs(ulong base)
266 {
267         int i, ac;
268         uchar *av[32];
269         uchar **lsp;
270
271         sp = (uchar*)base + BY2PG - Ustkheadroom;
272
273         ac = 0;
274         av[ac++] = pusharg("boot");
275         av[ac++] = pusharg("-D");
276
277         /* 4 byte word align stack */
278         sp = (uchar*)((ulong)sp & ~3);
279
280         /* build argc, argv on stack */
281         sp -= (ac+1)*sizeof(sp);
282         lsp = (uchar**)sp;
283         for(i = 0; i < ac; i++)
284                 *lsp++ = av[i] + ((USTKTOP - BY2PG) - base);
285         *lsp = 0;
286         sp += (USTKTOP - BY2PG) - base - sizeof(ulong);
287 }
288
289 char*
290 getconf(char *name)
291 {
292         int i;
293
294         for(i = 0; i < nconf; i++)
295                 if(cistrcmp(confname[i], name) == 0)
296                         return confval[i];
297         return 0;
298 }
299
300 static void
301 writeconf(void)
302 {
303         char *p, *q;
304         int n;
305
306         p = getconfenv();
307
308         if(waserror()) {
309                 free(p);
310                 nexterror();
311         }
312
313         /* convert to name=value\n format */
314         for(q=p; *q; q++) {
315                 q += strlen(q);
316                 *q = '=';
317                 q += strlen(q);
318                 *q = '\n';
319         }
320         n = q - p + 1;
321         if(n >= BOOTARGSLEN)
322                 error("kernel configuration too large");
323         memmove(BOOTARGS, p, n);
324         poperror();
325         free(p);
326 }
327
328 void
329 confinit(void)
330 {
331         char *p;
332         int i, userpcnt;
333         ulong kpages;
334
335         for(i = 0; i < nconf; i++)
336                 print("%s=%s\n", confname[i], confval[i]);
337         /* 
338          * all ram above xentop is free, but must be mappable
339          * to virt addrs less than VIRT_START.
340          */
341         kpages = PADDR(hypervisor_virt_start)>>PGSHIFT;
342         if(xenstart->nr_pages <= kpages)
343                 kpages = xenstart->nr_pages;
344         else
345                 print("Warning: Plan 9 / Xen limitation - "
346                           "using only %lud of %lud available RAM pages\n",
347                           kpages, xenstart->nr_pages);
348         xentop = PGROUND(PADDR(xentop));
349         conf.mem[0].npage = kpages - (xentop>>PGSHIFT);
350         conf.mem[0].base = xentop;
351
352         if(p = getconf("*kernelpercent"))
353                 userpcnt = 100 - strtol(p, 0, 0);
354         else
355                 userpcnt = 0;
356
357         conf.npage = 0;
358         for(i=0; i<nelem(conf.mem); i++)
359                 conf.npage += conf.mem[i].npage;
360
361         conf.nproc = 100 + ((conf.npage*BY2PG)/MB)*5;
362         if(cpuserver)
363                 conf.nproc *= 3;
364         if(conf.nproc > 2000)
365                 conf.nproc = 2000;
366         conf.nimage = 200;
367         conf.nswap = conf.nproc*80;
368         conf.nswppo = 4096;
369
370         if(cpuserver) {
371                 if(userpcnt < 10)
372                         userpcnt = 70;
373                 kpages = conf.npage - (conf.npage*userpcnt)/100;
374
375                 /*
376                  * Hack for the big boys. Only good while physmem < 4GB.
377                  * Give the kernel fixed max + enough to allocate the
378                  * page pool.
379                  * This is an overestimate as conf.upages < conf.npages.
380                  * The patch of nimage is a band-aid, scanning the whole
381                  * page list in imagereclaim just takes too long.
382                  */
383                 if(kpages > (64*MB + conf.npage*sizeof(Page))/BY2PG){
384                         kpages = (64*MB + conf.npage*sizeof(Page))/BY2PG;
385                         conf.nimage = 2000;
386                         kpages += (conf.nproc*KSTACK)/BY2PG;
387                 }
388         } else {
389                 if(userpcnt < 10) {
390                         if(conf.npage*BY2PG < 16*MB)
391                                 userpcnt = 40;
392                         else
393                                 userpcnt = 60;
394                 }
395                 kpages = conf.npage - (conf.npage*userpcnt)/100;
396
397                 /*
398                  * Make sure terminals with low memory get at least
399                  * 4MB on the first Image chunk allocation.
400                  */
401                 if(conf.npage*BY2PG < 16*MB)
402                         imagmem->minarena = 4*1024*1024;
403         }
404
405         /*
406          * can't go past the end of virtual memory
407          * (ulong)-KZERO is 2^32 - KZERO
408          */
409         if(kpages > ((ulong)-KZERO)/BY2PG)
410                 kpages = ((ulong)-KZERO)/BY2PG;
411
412         conf.upages = conf.npage - kpages;
413         conf.ialloc = (kpages/2)*BY2PG;
414
415         /*
416          * Guess how much is taken by the large permanent
417          * datastructures. Mntcache and Mntrpc are not accounted for.
418          */
419         kpages *= BY2PG;
420         kpages -= conf.upages*sizeof(Page)
421                 + conf.nproc*sizeof(Proc)
422                 + conf.nimage*sizeof(Image)
423                 + conf.nswap
424                 + conf.nswppo*sizeof(Page*);
425         mainmem->maxsize = kpages;
426         if(!cpuserver){
427                 /*
428                  * give terminals lots of image memory, too; the dynamic
429                  * allocation will balance the load properly, hopefully.
430                  * be careful with 32-bit overflow.
431                  */
432                 imagmem->maxsize = kpages;
433         }
434 }
435
436 static char* mathmsg[] =
437 {
438         nil,    /* handled below */
439         "denormalized operand",
440         "division by zero",
441         "numeric overflow",
442         "numeric underflow",
443         "precision loss",
444 };
445
446 static void
447 mathnote(void)
448 {
449         int i;
450         ulong status;
451         char *msg, note[ERRMAX];
452
453         status = up->fpsave->status;
454
455         /*
456          * Some attention should probably be paid here to the
457          * exception masks and error summary.
458          */
459         msg = "unknown exception";
460         for(i = 1; i <= 5; i++){
461                 if(!((1<<i) & status))
462                         continue;
463                 msg = mathmsg[i];
464                 break;
465         }
466         if(status & 0x01){
467                 if(status & 0x40){
468                         if(status & 0x200)
469                                 msg = "stack overflow";
470                         else
471                                 msg = "stack underflow";
472                 }else
473                         msg = "invalid operation";
474         }
475         snprint(note, sizeof note, "sys: fp: %s fppc=0x%lux status=0x%lux",
476                 msg, up->fpsave->pc, status);
477         postnote(up, 1, note, NDebug);
478 }
479
480 /*
481  *  math coprocessor error
482  */
483 static void
484 matherror(Ureg *ur, void*)
485 {
486         /*
487          *  a write cycle to port 0xF0 clears the interrupt latch attached
488          *  to the error# line from the 387
489          */
490         if(!(m->cpuiddx & 0x01))
491                 outb(0xF0, 0xFF);
492
493         /*
494          *  save floating point state to check out error
495          */
496         fpenv(up->fpsave);
497         mathnote();
498
499         if(ur->pc & KZERO)
500                 panic("fp: status %ux fppc=0x%lux pc=0x%lux",
501                         up->fpsave->status, up->fpsave->pc, ur->pc);
502 }
503
504 /*
505  *  math coprocessor emulation fault
506  */
507 static void
508 mathemu(Ureg *ureg, void*)
509 {
510         if(up->fpstate & FPillegal){
511                 /* someone did floating point in a note handler */
512                 postnote(up, 1, "sys: floating point in note handler", NDebug);
513                 return;
514         }
515         switch(up->fpstate){
516         case FPinit:
517                 fpinit();
518                 while(up->fpsave == nil)
519                         up->fpsave = mallocalign(sizeof(FPsave), FPalign, 0, 0);
520                 up->fpstate = FPactive;
521                 break;
522         case FPinactive:
523                 /*
524                  * Before restoring the state, check for any pending
525                  * exceptions, there's no way to restore the state without
526                  * generating an unmasked exception.
527                  * More attention should probably be paid here to the
528                  * exception masks and error summary.
529                  */
530                 if((up->fpsave->status & ~up->fpsave->control) & 0x07F){
531                         mathnote();
532                         break;
533                 }
534                 fprestore(up->fpsave);
535                 up->fpstate = FPactive;
536                 break;
537         case FPactive:
538                 panic("math emu pid %ld %s pc 0x%lux", 
539                         up->pid, up->text, ureg->pc);
540                 break;
541         }
542 }
543
544 /*
545  *  math coprocessor segment overrun
546  */
547 static void
548 mathover(Ureg*, void*)
549 {
550         pexit("math overrun", 0);
551 }
552
553 void
554 mathinit(void)
555 {
556         trapenable(VectorCERR, matherror, 0, "matherror");
557         //if(X86FAMILY(m->cpuidax) == 3)
558         //      intrenable(IrqIRQ13, matherror, 0, BUSUNKNOWN, "matherror");
559         trapenable(VectorCNA, mathemu, 0, "mathemu");
560         trapenable(VectorCSO, mathover, 0, "mathover");
561 }
562
563 /*
564  *  set up floating point for a new process
565  */
566 void
567 procsetup(Proc*p)
568 {
569         p->fpstate = FPinit;
570         fpoff();
571 }
572
573 void
574 procfork(Proc *p)
575 {
576         int s;
577
578         p->kentry = up->kentry;
579         p->pcycles = -p->kentry;
580
581         /* save floating point state */
582         s = splhi();
583         switch(up->fpstate & ~FPillegal){
584         case FPactive:
585                 fpsave(up->fpsave);
586                 up->fpstate = FPinactive;
587         case FPinactive:
588                 while(p->fpsave == nil)
589                         p->fpsave = mallocalign(sizeof(FPsave), FPalign, 0, 0);
590                 memmove(p->fpsave, up->fpsave, sizeof(FPsave));
591                 p->fpstate = FPinactive;
592         }
593         splx(s);
594 }
595
596 void
597 procrestore(Proc *p)
598 {
599         uvlong t;
600
601         if(p->kp)
602                 return;
603         cycles(&t);
604         p->pcycles -= t;
605 }
606
607 /*
608  *  Save the mach dependent part of the process state.
609  */
610 void
611 procsave(Proc *p)
612 {
613         uvlong t;
614
615         cycles(&t);
616         p->pcycles += t;
617         if(p->fpstate == FPactive){
618                 if(p->state == Moribund)
619                         fpclear();
620                 else{
621                         /*
622                          * Fpsave() stores without handling pending
623                          * unmasked exeptions. Postnote() can't be called
624                          * here as sleep() already has up->rlock, so
625                          * the handling of pending exceptions is delayed
626                          * until the process runs again and generates an
627                          * emulation fault to activate the FPU.
628                          */
629                         fpsave(p->fpsave);
630                 }
631                 p->fpstate = FPinactive;
632         }
633
634         /*
635          * While this processor is in the scheduler, the process could run
636          * on another processor and exit, returning the page tables to
637          * the free list where they could be reallocated and overwritten.
638          * When this processor eventually has to get an entry from the
639          * trashed page tables it will crash.
640          *
641          * If there's only one processor, this can't happen.
642          * You might think it would be a win not to do this in that case,
643          * especially on VMware, but it turns out not to matter.
644          */
645         mmuflushtlb(0);
646 }
647
648 void
649 reboot(void *entry, void *code, ulong size)
650 {
651         void (*f)(ulong, ulong, ulong);
652
653         writeconf();
654         cpushutdown();
655
656         splhi();
657
658         /* turn off buffered serial console */
659         serialoq = nil;
660
661         /* shutdown devices */
662         chandevshutdown();
663
664         /* reboot(0, ...) on Xen causes domU shutdown */
665         if(entry == 0)
666                 HYPERVISOR_shutdown(0);
667
668         mmuflushtlb(0);
669
670         /* setup reboot trampoline function */
671         f = (void*)REBOOTADDR;
672         memmove(f, rebootcode, sizeof(rebootcode));
673
674         /* off we go - never to return */
675         (*f)(PADDR(entry), PADDR(code), size);
676 }
677
678 void
679 exit(int)
680 {
681         cpushutdown();
682         arch->reset();
683 }