]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/kw/main.c
Import sources from 2011-03-30 iso image - lib
[plan9front.git] / sys / src / 9 / kw / main.c
1 #include "u.h"
2 #include "../port/lib.h"
3 #include "mem.h"
4 #include "dat.h"
5 #include "fns.h"
6
7 #include "init.h"
8 #include "arm.h"
9 #include <pool.h>
10
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 BOOTARGS        ((char*)CONFADDR)
20 #define BOOTARGSLEN     (16*KiB)                /* limit in devenv.c */
21 #define MAXCONF         64
22 #define MAXCONFLINE     160
23
24 #define isascii(c) ((uchar)(c) > 0 && (uchar)(c) < 0177)
25
26 uintptr kseg0 = KZERO;
27 Mach* machaddr[MAXMACH];
28
29 /*
30  * Option arguments from the command line.
31  * oargv[0] is the boot file.
32  * Optionsinit() is called from multiboot()
33  * or some other machine-dependent place
34  * to set it all up.
35  */
36 static int oargc;
37 static char* oargv[20];
38 static char oargb[128];
39 static int oargblen;
40 static char oenv[4096];
41
42 static uintptr sp;              /* XXX - must go - user stack of init proc */
43
44 int vflag;
45 char debug[256];
46
47 /* store plan9.ini contents here at least until we stash them in #ec */
48 static char confname[MAXCONF][KNAMELEN];
49 static char confval[MAXCONF][MAXCONFLINE];
50 static int nconf;
51
52 #ifdef CRYPTOSANDBOX
53 uchar sandbox[64*1024+BY2PG];
54 #endif
55
56 static int
57 findconf(char *name)
58 {
59         int i;
60
61         for(i = 0; i < nconf; i++)
62                 if(cistrcmp(confname[i], name) == 0)
63                         return i;
64         return -1;
65 }
66
67 char*
68 getconf(char *name)
69 {
70         int i;
71
72         i = findconf(name);
73         if(i >= 0)
74                 return confval[i];
75         return nil;
76 }
77
78 void
79 addconf(char *name, char *val)
80 {
81         int i;
82
83         i = findconf(name);
84         if(i < 0){
85                 if(val == nil || nconf >= MAXCONF)
86                         return;
87                 i = nconf++;
88                 strecpy(confname[i], confname[i]+sizeof(confname[i]), name);
89         }
90 //      confval[i] = val;
91         strecpy(confval[i], confval[i]+sizeof(confval[i]), val);
92 }
93
94 static void
95 writeconf(void)
96 {
97         char *p, *q;
98         int n;
99
100         p = getconfenv();
101
102         if(waserror()) {
103                 free(p);
104                 nexterror();
105         }
106
107         /* convert to name=value\n format */
108         for(q=p; *q; q++) {
109                 q += strlen(q);
110                 *q = '=';
111                 q += strlen(q);
112                 *q = '\n';
113         }
114         n = q - p + 1;
115         if(n >= BOOTARGSLEN)
116                 error("kernel configuration too large");
117         memmove(BOOTARGS, p, n);
118         poperror();
119         free(p);
120 }
121
122 /*
123  * assumes that we have loaded our /cfg/pxe/mac file at 0x1000 with
124  * tftp in u-boot.  no longer uses malloc, so can be called early.
125  */
126 static void
127 plan9iniinit(void)
128 {
129         char *k, *v, *next;
130
131         k = (char *)CONFADDR;
132         if(!isascii(*k))
133                 return;
134
135         for(; k && *k != '\0'; k = next) {
136                 if (!isascii(*k))               /* sanity check */
137                         break;
138                 next = strchr(k, '\n');
139                 if (next)
140                         *next++ = '\0';
141
142                 if (*k == '\0' || *k == '\n' || *k == '#')
143                         continue;
144                 v = strchr(k, '=');
145                 if(v == nil)
146                         continue;               /* mal-formed line */
147                 *v++ = '\0';
148
149                 addconf(k, v);
150         }
151 }
152
153 static void
154 optionsinit(char* s)
155 {
156         char *o;
157
158         o = strecpy(oargb, oargb+sizeof(oargb), s)+1;
159         if(getenv("bootargs", o, o - oargb) != nil)
160                 *(o-1) = ' ';
161
162         oargblen = strlen(oargb);
163         oargc = tokenize(oargb, oargv, nelem(oargv)-1);
164         oargv[oargc] = nil;
165 }
166
167 char*
168 getenv(char* name, char* buf, int n)
169 {
170         char *e, *p, *q;
171
172         p = oenv;
173         while(*p != 0){
174                 if((e = strchr(p, '=')) == nil)
175                         break;
176                 for(q = name; p < e; p++){
177                         if(*p != *q)
178                                 break;
179                         q++;
180                 }
181                 if(p == e && *q == 0){
182                         strecpy(buf, buf+n, e+1);
183                         return buf;
184                 }
185                 p += strlen(p)+1;
186         }
187
188         return nil;
189 }
190
191 #include "io.h"
192
193 typedef struct Spiregs Spiregs;
194 struct Spiregs {
195         ulong   ictl;           /* interface ctl */
196         ulong   icfg;           /* interface config */
197         ulong   out;            /* data out */
198         ulong   in;             /* data in */
199         ulong   ic;             /* interrupt cause */
200         ulong   im;             /* interrupt mask */
201         ulong   _pad[2];
202         ulong   dwrcfg;         /* direct write config */
203         ulong   dwrhdr;         /* direct write header */
204 };
205
206 enum {
207         /* ictl bits */
208         Csnact  = 1<<0,         /* serial memory activated */
209
210         /* icfg bits */
211         Bytelen = 1<<5,         /* 2^(this_bit) bytes per transfer */
212         Dirrdcmd= 1<<10,        /* flag: fast read */
213 };
214
215 static void
216 dumpbytes(uchar *bp, long max)
217 {
218         iprint("%#p: ", bp);
219         for (; max > 0; max--)
220                 iprint("%02.2ux ", *bp++);
221         iprint("...\n");
222 }
223
224 static void
225 spiprobe(void)
226 {
227         Spiregs *rp = (Spiregs *)soc.spi;
228
229         rp->ictl |= Csnact;
230         coherence();
231         rp->icfg |= Dirrdcmd | 3<<8;    /* fast reads, 4-byte addresses */
232         rp->icfg &= ~Bytelen;           /* one-byte reads */
233         coherence();
234
235 //      print("spi flash at %#ux: memory reads enabled\n", PHYSSPIFLASH);
236 }
237
238 void    archconsole(void);
239
240 /*
241  * entered from l.s with mmu enabled.
242  *
243  * we may have to realign the data segment; apparently 5l -H0 -R4096
244  * does not pad the text segment.  on the other hand, we may have been
245  * loaded by another kernel.
246  *
247  * be careful not to touch the data segment until we know it's aligned.
248  */
249 void
250 main(Mach* mach)
251 {
252         extern char bdata[], edata[], end[], etext[];
253         static ulong vfy = 0xcafebabe;
254
255         m = mach;
256         if (vfy != 0xcafebabe)
257                 memmove(bdata, etext, edata - bdata);
258         if (vfy != 0xcafebabe) {
259                 wave('?');
260                 panic("misaligned data segment");
261         }
262         memset(edata, 0, end - edata);          /* zero bss */
263         vfy = 0;
264
265 wave('9');
266         machinit();
267         archreset();
268         mmuinit();
269
270         optionsinit("/boot/boot boot");
271         quotefmtinstall();
272         archconsole();
273 wave(' ');
274
275         /* want plan9.ini to be able to affect memory sizing in confinit */
276         plan9iniinit();         /* before we step on plan9.ini in low memory */
277
278         confinit();
279         /* xinit would print if it could */
280         xinit();
281
282         /*
283          * Printinit will cause the first malloc call.
284          * (printinit->qopen->malloc) unless any of the
285          * above (like clockintr) do an irqenable, which
286          * will call malloc.
287          * If the system dies here it's probably due
288          * to malloc(->xalloc) not being initialised
289          * correctly, or the data segment is misaligned
290          * (it's amazing how far you can get with
291          * things like that completely broken).
292          *
293          * (Should be) boilerplate from here on.
294          */
295         trapinit();
296         clockinit();
297
298         printinit();
299         uartkirkwoodconsole();
300         /* only now can we print */
301         print("from Bell Labs\n\n");
302
303 #ifdef CRYPTOSANDBOX
304         print("sandbox: 64K at physical %#lux, mapped to 0xf10b0000\n",
305                 PADDR((uintptr)sandbox & ~(BY2PG-1)));
306 #endif
307
308         archconfinit();
309         cpuidprint();
310         timersinit();
311
312         procinit0();
313         initseg();
314         links();
315         chandevreset();                 /* most devices are discovered here */
316
317         pageinit();
318         swapinit();
319         userinit();
320         schedinit();
321         panic("schedinit returned");
322 }
323
324 void
325 cpuidprint(void)
326 {
327         char name[64];
328
329         cputype2name(name, sizeof name);
330         print("cpu%d: %lldMHz ARM %s\n", m->machno, m->cpuhz/1000000, name);
331 }
332
333 void
334 machinit(void)
335 {
336         memset(m, 0, sizeof(Mach));
337         m->machno = 0;
338         machaddr[m->machno] = m;
339
340         m->ticks = 1;
341         m->perf.period = 1;
342
343         conf.nmach = 1;
344
345         active.machs = 1;
346         active.exiting = 0;
347
348         up = nil;
349 }
350
351 static void
352 shutdown(int ispanic)
353 {
354         int ms, once;
355
356         lock(&active);
357         if(ispanic)
358                 active.ispanic = ispanic;
359         else if(m->machno == 0 && (active.machs & (1<<m->machno)) == 0)
360                 active.ispanic = 0;
361         once = active.machs & (1<<m->machno);
362         active.machs &= ~(1<<m->machno);
363         active.exiting = 1;
364         unlock(&active);
365
366         if(once)
367                 iprint("cpu%d: exiting\n", m->machno);
368         spllo();
369         for(ms = 5*1000; ms > 0; ms -= TK2MS(2)){
370                 delay(TK2MS(2));
371                 if(active.machs == 0 && consactive() == 0)
372                         break;
373         }
374         delay(1000);
375 }
376
377 /*
378  *  exit kernel either on a panic or user request
379  */
380 void
381 exit(int code)
382 {
383         shutdown(code);
384         splhi();
385         archreboot();
386 }
387
388 /*
389  * the new kernel is already loaded at address `code'
390  * of size `size' and entry point `entry'.
391  */
392 void
393 reboot(void *entry, void *code, ulong size)
394 {
395         void (*f)(ulong, ulong, ulong);
396
397         iprint("starting reboot...");
398         writeconf();
399         
400         shutdown(0);
401
402         /*
403          * should be the only processor running now
404          */
405
406         print("shutting down...\n");
407         delay(200);
408
409         /* turn off buffered serial console */
410         serialoq = nil;
411
412         /* shutdown devices */
413         chandevshutdown();
414
415         /* call off the dog */
416         clockshutdown();
417
418         splhi();
419
420         /* setup reboot trampoline function */
421         f = (void*)REBOOTADDR;
422         memmove(f, rebootcode, sizeof(rebootcode));
423         cacheuwbinv();
424         l2cacheuwb();
425
426         print("rebooting...");
427         iprint("entry %#lux code %#lux size %ld\n",
428                 PADDR(entry), PADDR(code), size);
429         delay(100);             /* wait for uart to quiesce */
430
431         /* off we go - never to return */
432         cacheuwbinv();
433         l2cacheuwb();
434         (*f)(PADDR(entry), PADDR(code), size);
435
436         iprint("loaded kernel returned!\n");
437         delay(1000);
438         archreboot();
439 }
440
441 /*
442  *  starting place for first process
443  */
444 void
445 init0(void)
446 {
447         int i;
448         char buf[2*KNAMELEN];
449
450         assert(up != nil);
451         up->nerrlab = 0;
452         coherence();
453         spllo();
454
455         /*
456          * These are o.k. because rootinit is null.
457          * Then early kproc's will have a root and dot.
458          */
459         up->slash = namec("#/", Atodir, 0, 0);
460         pathclose(up->slash->path);
461         up->slash->path = newpath("/");
462         up->dot = cclone(up->slash);
463
464         chandevinit();
465
466         if(!waserror()){
467                 snprint(buf, sizeof(buf), "%s %s", "ARM", conffile);
468                 ksetenv("terminal", buf, 0);
469                 ksetenv("cputype", "arm", 0);
470                 if(cpuserver)
471                         ksetenv("service", "cpu", 0);
472                 else
473                         ksetenv("service", "terminal", 0);
474
475                 /* convert plan9.ini variables to #e and #ec */
476                 for(i = 0; i < nconf; i++) {
477                         ksetenv(confname[i], confval[i], 0);
478                         ksetenv(confname[i], confval[i], 1);
479                 }
480                 poperror();
481         }
482         kproc("alarm", alarmkproc, 0);
483
484         touser(sp);
485 }
486
487 static void
488 bootargs(uintptr base)
489 {
490         int i;
491         ulong ssize;
492         char **av, *p;
493
494         /*
495          * Push the boot args onto the stack.
496          * The initial value of the user stack must be such
497          * that the total used is larger than the maximum size
498          * of the argument list checked in syscall.
499          */
500         i = oargblen+1;
501         p = UINT2PTR(STACKALIGN(base + BY2PG - sizeof(up->s.args) - i));
502         memmove(p, oargb, i);
503
504         /*
505          * Now push argc and the argv pointers.
506          * This isn't strictly correct as the code jumped to by
507          * touser in init9.s calls startboot (port/initcode.c) which
508          * expects arguments
509          *      startboot(char *argv0, char **argv)
510          * not the usual (int argc, char* argv[]), but argv0 is
511          * unused so it doesn't matter (at the moment...).
512          */
513         av = (char**)(p - (oargc+2)*sizeof(char*));
514         ssize = base + BY2PG - PTR2UINT(av);
515         *av++ = (char*)oargc;
516         for(i = 0; i < oargc; i++)
517                 *av++ = (oargv[i] - oargb) + (p - base) + (USTKTOP - BY2PG);
518         *av = nil;
519
520         /*
521          * Leave space for the return PC of the
522          * caller of initcode.
523          */
524         sp = USTKTOP - ssize - sizeof(void*);
525 }
526
527 /*
528  *  create the first process
529  */
530 void
531 userinit(void)
532 {
533         Proc *p;
534         Segment *s;
535         KMap *k;
536         Page *pg;
537
538         /* no processes yet */
539         up = nil;
540
541         p = newproc();
542         p->pgrp = newpgrp();
543         p->egrp = smalloc(sizeof(Egrp));
544         p->egrp->ref = 1;
545         p->fgrp = dupfgrp(nil);
546         p->rgrp = newrgrp();
547         p->procmode = 0640;
548
549         kstrdup(&eve, "");
550         kstrdup(&p->text, "*init*");
551         kstrdup(&p->user, eve);
552
553         /*
554          * Kernel Stack
555          */
556         p->sched.pc = PTR2UINT(init0);
557         p->sched.sp = PTR2UINT(p->kstack+KSTACK-sizeof(up->s.args)-sizeof(uintptr));
558         p->sched.sp = STACKALIGN(p->sched.sp);
559
560         /*
561          * User Stack
562          *
563          * Technically, newpage can't be called here because it
564          * should only be called when in a user context as it may
565          * try to sleep if there are no pages available, but that
566          * shouldn't be the case here.
567          */
568         s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
569         p->seg[SSEG] = s;
570         pg = newpage(1, 0, USTKTOP-BY2PG);
571         segpage(s, pg);
572         k = kmap(pg);
573         bootargs(VA(k));
574         kunmap(k);
575
576         /*
577          * Text
578          */
579         s = newseg(SG_TEXT, UTZERO, 1);
580         s->flushme++;
581         p->seg[TSEG] = s;
582         pg = newpage(1, 0, UTZERO);
583         memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
584         segpage(s, pg);
585         k = kmap(s->map[0]->pages[0]);
586         memmove(UINT2PTR(VA(k)), initcode, sizeof initcode);
587         kunmap(k);
588
589         ready(p);
590 }
591
592 Conf conf;                      /* XXX - must go - gag */
593
594 Confmem sheevamem[] = {
595         /*
596          * Memory available to Plan 9:
597          * the 8K is reserved for ethernet dma access violations to scribble on.
598          */
599         { .base = 0, .limit = 512*MB - 8*1024, },
600 };
601
602 void
603 confinit(void)
604 {
605         int i;
606         ulong kpages;
607         uintptr pa;
608
609         /*
610          * Copy the physical memory configuration to Conf.mem.
611          */
612         if(nelem(sheevamem) > nelem(conf.mem)){
613                 iprint("memory configuration botch\n");
614                 exit(1);
615         }
616         memmove(conf.mem, sheevamem, sizeof(sheevamem));
617
618         conf.npage = 0;
619         pa = PADDR(PGROUND(PTR2UINT(end)));
620
621         /*
622          *  we assume that the kernel is at the beginning of one of the
623          *  contiguous chunks of memory and fits therein.
624          */
625         for(i=0; i<nelem(conf.mem); i++){
626                 /* take kernel out of allocatable space */
627                 if(pa > conf.mem[i].base && pa < conf.mem[i].limit)
628                         conf.mem[i].base = pa;
629
630                 conf.mem[i].npage = (conf.mem[i].limit - conf.mem[i].base)/BY2PG;
631                 conf.npage += conf.mem[i].npage;
632         }
633
634         conf.upages = (conf.npage*90)/100;
635         conf.ialloc = ((conf.npage-conf.upages)/2)*BY2PG;
636
637         /* only one processor */
638         conf.nmach = 1;
639
640         /* set up other configuration parameters */
641         conf.nproc = 100 + ((conf.npage*BY2PG)/MB)*5;
642         if(cpuserver)
643                 conf.nproc *= 3;
644         if(conf.nproc > 2000)
645                 conf.nproc = 2000;
646         conf.nswap = conf.npage*3;
647         conf.nswppo = 4096;
648         conf.nimage = 200;
649
650         conf.copymode = 0;              /* copy on write */
651
652         /*
653          * Guess how much is taken by the large permanent
654          * datastructures. Mntcache and Mntrpc are not accounted for
655          * (probably ~300KB).
656          */
657         kpages = conf.npage - conf.upages;
658         kpages *= BY2PG;
659         kpages -= conf.upages*sizeof(Page)
660                 + conf.nproc*sizeof(Proc)
661                 + conf.nimage*sizeof(Image)
662                 + conf.nswap
663                 + conf.nswppo*sizeof(Page);
664         mainmem->maxsize = kpages;
665         if(!cpuserver)
666                 /*
667                  * give terminals lots of image memory, too; the dynamic
668                  * allocation will balance the load properly, hopefully.
669                  * be careful with 32-bit overflow.
670                  */
671                 imagmem->maxsize = kpages;
672 }
673
674 int
675 cmpswap(long *addr, long old, long new)
676 {
677         return cas32(addr, old, new);
678 }