[committed on behalf of sephe]
[dragonfly.git] / sys / platform / vkernel / platform / init.c
1 /*
2  * Copyright (c) 2006 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/platform/vkernel/platform/init.c,v 1.19 2007/01/10 13:33:23 swildner Exp $
35  */
36
37 #include <sys/types.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/stat.h>
41 #include <sys/mman.h>
42 #include <sys/cons.h>
43 #include <sys/random.h>
44 #include <sys/vkernel.h>
45 #include <sys/tls.h>
46 #include <sys/proc.h>
47 #include <sys/msgbuf.h>
48 #include <sys/vmspace.h>
49 #include <vm/vm_page.h>
50
51 #include <machine/globaldata.h>
52 #include <machine/tls.h>
53 #include <machine/md_var.h>
54 #include <machine/vmparam.h>
55
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <unistd.h>
59 #include <fcntl.h>
60 #include <string.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <assert.h>
64
65 vm_paddr_t phys_avail[16];
66 vm_paddr_t Maxmem;
67 vm_paddr_t Maxmem_bytes;
68 int MemImageFd = -1;
69 int RootImageFd = -1;
70 int NetifFd = -1;
71 vm_offset_t KvaStart;
72 vm_offset_t KvaEnd;
73 vm_offset_t KvaSize;
74 vm_offset_t virtual_start;
75 vm_offset_t virtual_end;
76 vm_offset_t kernel_vm_end;
77 vm_offset_t crashdumpmap;
78 vm_offset_t clean_sva;
79 vm_offset_t clean_eva;
80 struct msgbuf *msgbufp;
81 caddr_t ptvmmap;
82 vpte_t  *KernelPTD;
83 vpte_t  *KernelPTA;     /* Warning: Offset for direct VA translation */
84 u_int cpu_feature;      /* XXX */
85 u_int tsc_present;      /* XXX */
86
87 struct privatespace *CPU_prvspace;
88
89 static struct trapframe proc0_tf;
90 static void *proc0paddr;
91
92 static void init_sys_memory(char *imageFile);
93 static void init_kern_memory(void);
94 static void init_globaldata(void);
95 static void init_vkernel(void);
96 static void init_rootdevice(char *imageFile);
97 static void init_netif(char *netifFile);
98 static void usage(const char *ctl);
99
100 /*
101  * Kernel startup for virtual kernels - standard main() 
102  */
103 int
104 main(int ac, char **av)
105 {
106         char *memImageFile = NULL;
107         char *rootImageFile = NULL;
108         char *netifFile = NULL;
109         char *suffix;
110         int c;
111         int i;
112         int n;
113
114         /*
115          * Process options
116          */
117         while ((c = getopt(ac, av, "vm:r:e:I:")) != -1) {
118                 switch(c) {
119                 case 'e':
120                         /*
121                          * name=value:name=value:name=value...
122                          */
123                         n = strlen(optarg);
124                         kern_envp = malloc(n + 2);
125                         for (i = 0; i < n; ++i) {
126                                 if (optarg[i] == ':')
127                                         kern_envp[i] = 0;
128                                 else
129                                         kern_envp[i] = optarg[i];
130                         }
131                         kern_envp[i++] = 0;
132                         kern_envp[i++] = 0;
133                         break;
134                 case 'v':
135                         bootverbose = 1;
136                         break;
137                 case 'i':
138                         memImageFile = optarg;
139                         break;
140                 case 'I':
141                         netifFile = optarg;
142                         break;
143                 case 'r':
144                         rootImageFile = optarg;
145                         break;
146                 case 'm':
147                         Maxmem_bytes = strtoull(optarg, &suffix, 0);
148                         if (suffix) {
149                                 switch(*suffix) {
150                                 case 'g':
151                                 case 'G':
152                                         Maxmem_bytes <<= 30;
153                                         break;
154                                 case 'm':
155                                 case 'M':
156                                         Maxmem_bytes <<= 20;
157                                         break;
158                                 case 'k':
159                                 case 'K':
160                                         Maxmem_bytes <<= 10;
161                                         break;
162                                 default:
163                                         Maxmem_bytes = 0;
164                                         usage("Bad maxmem option");
165                                         /* NOT REACHED */
166                                         break;
167                                 }
168                         }
169                         break;
170                 }
171         }
172
173         init_sys_memory(memImageFile);
174         init_kern_memory();
175         init_globaldata();
176         init_vkernel();
177         init_rootdevice(rootImageFile);
178         init_netif(netifFile);
179         init_exceptions();
180         mi_startup();
181         /* NOT REACHED */
182         exit(1);
183 }
184
185 /*
186  * Initialize system memory.  This is the virtual kernel's 'RAM'.
187  */
188 static
189 void
190 init_sys_memory(char *imageFile)
191 {
192         struct stat st;
193         int i;
194         int fd;
195
196         /*
197          * Figure out the system memory image size.  If an image file was
198          * specified and -m was not specified, use the image file's size.
199          */
200
201         if (imageFile && stat(imageFile, &st) == 0 && Maxmem_bytes == 0)
202                 Maxmem_bytes = (vm_paddr_t)st.st_size;
203         if ((imageFile == NULL || stat(imageFile, &st) < 0) && 
204             Maxmem_bytes == 0) {
205                 err(1, "Cannot create new memory file %s unless "
206                        "system memory size is specified with -m",
207                        imageFile);
208                 /* NOT REACHED */
209         }
210
211         /*
212          * Maxmem must be known at this time
213          */
214         if (Maxmem_bytes < 32 * 1024 * 1024 || (Maxmem_bytes & SEG_MASK)) {
215                 err(1, "Bad maxmem specification: 32MB minimum, "
216                        "multiples of %dMB only",
217                        SEG_SIZE / 1024 / 1024);
218                 /* NOT REACHED */
219         }
220
221         /*
222          * Generate an image file name if necessary, then open/create the
223          * file exclusively locked.  Do not allow multiple virtual kernels
224          * to use the same image file.
225          */
226         if (imageFile == NULL) {
227                 for (i = 0; i < 1000000; ++i) {
228                         asprintf(&imageFile, "/var/vkernel/memimg.%06d", i);
229                         fd = open(imageFile, 
230                                   O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
231                         if (fd < 0 && errno == EWOULDBLOCK) {
232                                 free(imageFile);
233                                 continue;
234                         }
235                         break;
236                 }
237         } else {
238                 fd = open(imageFile, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
239         }
240         printf("Using memory file: %s\n", imageFile);
241         if (fd < 0 || fstat(fd, &st) < 0) {
242                 err(1, "Unable to open/create %s: %s",
243                       imageFile, strerror(errno));
244                 /* NOT REACHED */
245         }
246
247         /*
248          * Truncate or extend the file as necessary.
249          */
250         if (st.st_size > Maxmem_bytes) {
251                 ftruncate(fd, Maxmem_bytes);
252         } else if (st.st_size < Maxmem_bytes) {
253                 char *zmem;
254                 off_t off = st.st_size & ~SEG_MASK;
255
256                 kprintf("%s: Reserving blocks for memory image\n", imageFile);
257                 zmem = malloc(SEG_SIZE);
258                 bzero(zmem, SEG_SIZE);
259                 lseek(fd, off, SEEK_SET);
260                 while (off < Maxmem_bytes) {
261                         if (write(fd, zmem, SEG_SIZE) != SEG_SIZE) {
262                                 err(1, "Unable to reserve blocks for memory image");
263                                 /* NOT REACHED */
264                         }
265                         off += SEG_SIZE;
266                 }
267                 if (fsync(fd) < 0)
268                         err(1, "Unable to reserve blocks for memory image");
269                 free(zmem);
270         }
271         MemImageFd = fd;
272         Maxmem = Maxmem_bytes >> PAGE_SHIFT;
273 }
274
275 /*
276  * Initialize kernel memory.  This reserves kernel virtual memory by using
277  * MAP_VPAGETABLE
278  */
279 static
280 void
281 init_kern_memory(void)
282 {
283         void *base;
284         char *zero;
285         vpte_t pte;
286         int i;
287
288         /*
289          * Memory map our kernel virtual memory space.  Note that the
290          * kernel image itself is not made part of this memory for the
291          * moment.
292          *
293          * The memory map must be segment-aligned so we can properly
294          * offset KernelPTD.
295          */
296         base = mmap((void *)0x40000000, KERNEL_KVA_SIZE, PROT_READ|PROT_WRITE,
297                     MAP_FILE|MAP_SHARED|MAP_VPAGETABLE, MemImageFd, 0);
298         madvise(base, KERNEL_KVA_SIZE, MADV_NOSYNC);
299         if (base == MAP_FAILED) {
300                 err(1, "Unable to mmap() kernel virtual memory!");
301                 /* NOT REACHED */
302         }
303         KvaStart = (vm_offset_t)base;
304         KvaSize = KERNEL_KVA_SIZE;
305         KvaEnd = KvaStart + KvaSize;
306
307         /*
308          * Create a top-level page table self-mapping itself. 
309          *
310          * Initialize the page directory at physical page index 0 to point
311          * to an array of page table pages starting at physical page index 1
312          */
313         lseek(MemImageFd, 0L, 0);
314         for (i = 0; i < KERNEL_KVA_SIZE / SEG_SIZE; ++i) {
315                 pte = ((i + 1) * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
316                 write(MemImageFd, &pte, sizeof(pte));
317         }
318
319         /*
320          * Initialize the PTEs in the page table pages required to map the
321          * page table itself.  This includes mapping the page directory page
322          * at the base so we go one more loop then normal.
323          */
324         lseek(MemImageFd, PAGE_SIZE, 0);
325         for (i = 0; i <= KERNEL_KVA_SIZE / SEG_SIZE * sizeof(vpte_t); ++i) {
326                 pte = (i * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
327                 write(MemImageFd, &pte, sizeof(pte));
328         }
329
330         /*
331          * Initialize remaining PTEs to 0.  We may be reusing a memory image
332          * file.  This is approximately a megabyte.
333          */
334         i = (KERNEL_KVA_SIZE / PAGE_SIZE - i) * sizeof(pte);
335         zero = malloc(PAGE_SIZE);
336         while (i) {
337                 write(MemImageFd, zero, (i > PAGE_SIZE) ? PAGE_SIZE : i);
338                 i = i - ((i > PAGE_SIZE) ? PAGE_SIZE : i);
339         }
340         free(zero);
341
342         /*
343          * Enable the page table and calculate pointers to our self-map
344          * for easy kernel page table manipulation.
345          *
346          * KernelPTA must be offset so we can do direct VA translations
347          */
348         mcontrol(base, KERNEL_KVA_SIZE, MADV_SETMAP,
349                  0 | VPTE_R | VPTE_W | VPTE_V);
350         KernelPTD = (vpte_t *)base;                       /* pg directory */
351         KernelPTA = (vpte_t *)((char *)base + PAGE_SIZE); /* pg table pages */
352         KernelPTA -= KvaStart >> PAGE_SHIFT;
353
354         /*
355          * phys_avail[] represents unallocated physical memory.  MI code
356          * will use phys_avail[] to create the vm_page array.
357          */
358         phys_avail[0] = PAGE_SIZE +
359                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
360         phys_avail[0] = (phys_avail[0] + PAGE_MASK) & ~(vm_paddr_t)PAGE_MASK;
361         phys_avail[1] = Maxmem_bytes;
362
363         /*
364          * (virtual_start, virtual_end) represent unallocated kernel virtual
365          * memory.  MI code will create kernel_map using these parameters.
366          */
367         virtual_start = KvaStart + PAGE_SIZE +
368                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
369         virtual_start = (virtual_start + PAGE_MASK) & ~(vm_offset_t)PAGE_MASK;
370         virtual_end = KvaStart + KERNEL_KVA_SIZE;
371
372         /*
373          * Because we just pre-allocate the entire page table the demark used
374          * to determine when KVM must be grown is just set to the end of
375          * KVM.  pmap_growkernel() simply panics.
376          */
377         kernel_vm_end = virtual_end;
378
379         /*
380          * Allocate space for process 0's UAREA.
381          */
382         proc0paddr = (void *)virtual_start;
383         for (i = 0; i < UPAGES; ++i) {
384                 pmap_kenter_quick(virtual_start, phys_avail[0]);
385                 virtual_start += PAGE_SIZE;
386                 phys_avail[0] += PAGE_SIZE;
387         }
388
389         /*
390          * crashdumpmap
391          */
392         crashdumpmap = virtual_start;
393         virtual_start += MAXDUMPPGS * PAGE_SIZE;
394
395         /*
396          * msgbufp maps the system message buffer
397          */
398         assert((MSGBUF_SIZE & PAGE_MASK) == 0);
399         msgbufp = (void *)virtual_start;
400         for (i = 0; i < (MSGBUF_SIZE >> PAGE_SHIFT); ++i) {
401                 pmap_kenter_quick(virtual_start, phys_avail[0]);
402                 virtual_start += PAGE_SIZE;
403                 phys_avail[0] += PAGE_SIZE;
404         }
405         msgbufinit(msgbufp, MSGBUF_SIZE);
406
407         /*
408          * used by kern_memio for /dev/mem access
409          */
410         ptvmmap = (caddr_t)virtual_start;
411         virtual_start += PAGE_SIZE;
412
413         /*
414          * Bootstrap the kernel_pmap
415          */
416         pmap_bootstrap();
417 }
418
419 /*
420  * Map the per-cpu globaldata for cpu #0.  Allocate the space using
421  * virtual_start and phys_avail[0]
422  */
423 static
424 void
425 init_globaldata(void)
426 {
427         int i;
428         vm_paddr_t pa;
429         vm_offset_t va;
430
431         /*
432          * Reserve enough KVA to cover possible cpus.  This is a considerable
433          * amount of KVA since the privatespace structure includes two 
434          * whole page table mappings.
435          */
436         virtual_start = (virtual_start + SEG_MASK) & ~(vm_offset_t)SEG_MASK;
437         CPU_prvspace = (void *)virtual_start;
438         virtual_start += sizeof(struct privatespace) * SMP_MAXCPU;
439
440         /*
441          * Allocate enough physical memory to cover the mdglobaldata
442          * portion of the space and the idle stack and map the pages
443          * into KVA.  For cpu #0 only.
444          */
445         for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
446                 pa = phys_avail[0];
447                 va = (vm_offset_t)&CPU_prvspace[0].mdglobaldata + i;
448                 pmap_kenter_quick(va, pa);
449                 phys_avail[0] += PAGE_SIZE;
450         }
451         for (i = 0; i < sizeof(CPU_prvspace[0].idlestack); i += PAGE_SIZE) {
452                 pa = phys_avail[0];
453                 va = (vm_offset_t)&CPU_prvspace[0].idlestack + i;
454                 pmap_kenter_quick(va, pa);
455                 phys_avail[0] += PAGE_SIZE;
456         }
457
458         /*
459          * Setup the %gs for cpu #0.  The mycpu macro works after this
460          * point.
461          */
462         tls_set_fs(&CPU_prvspace[0], sizeof(struct privatespace));
463 }
464
465 /*
466  * Initialize very low level systems including thread0, proc0, etc.
467  */
468 static
469 void
470 init_vkernel(void)
471 {
472         struct mdglobaldata *gd;
473
474         gd = &CPU_prvspace[0].mdglobaldata;
475         bzero(gd, sizeof(*gd));
476
477         gd->mi.gd_curthread = &thread0;
478         thread0.td_gd = &gd->mi;
479         ncpus = 1;
480         ncpus2 = 1;
481         init_param1();
482         gd->mi.gd_prvspace = &CPU_prvspace[0];
483         mi_gdinit(&gd->mi, 0);
484         cpu_gdinit(gd, 0);
485         mi_proc0init(&gd->mi, proc0paddr);
486         proc0.p_lwp.lwp_md.md_regs = &proc0_tf;
487
488         /*init_locks();*/
489         cninit();
490         rand_initialize();
491 #if 0   /* #ifdef DDB */
492         kdb_init();
493         if (boothowto & RB_KDB)
494                 Debugger("Boot flags requested debugger");
495 #endif
496 #if 0
497         initializecpu();        /* Initialize CPU registers */
498 #endif
499         init_param2((phys_avail[1] - phys_avail[0]) / PAGE_SIZE);
500
501 #if 0
502         /*
503          * Map the message buffer
504          */
505         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
506                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
507         msgbufinit(msgbufp, MSGBUF_SIZE);
508 #endif
509 #if 0
510         thread0.td_pcb_cr3 ... MMU
511         proc0.p_lwp.lwp_md.md_regs = &proc0_tf;
512 #endif
513 }
514
515 /*
516  * The root filesystem path for the virtual kernel is optional.  If specified
517  * it points to a filesystem image.
518  */
519 static
520 void
521 init_rootdevice(char *imageFile)
522 {
523         struct stat st;
524
525         if (imageFile) {
526                 RootImageFd = open(imageFile, O_RDWR, 0644);
527                 if (RootImageFd < 0 || fstat(RootImageFd, &st) < 0) {
528                         err(1, "Unable to open/create %s: %s",
529                             imageFile, strerror(errno));
530                         /* NOT REACHED */
531                 }
532                 rootdevnames[0] = "ufs:vkd0a";
533         }
534 }
535
536 static
537 void
538 init_netif(char *netifFile)
539 {
540         if (netifFile) {
541                 NetifFd = open(netifFile, O_RDWR | O_NONBLOCK);
542                 if (NetifFd < 0) {
543                         warn("Unable to open %s: %s",
544                              netifFile, strerror(errno));
545                 }
546         }
547 }
548
549 static
550 void
551 usage(const char *ctl)
552 {
553         
554 }
555
556 void
557 cpu_reset(void)
558 {
559         kprintf("cpu reset\n");
560         exit(0);
561 }
562
563 void
564 cpu_halt(void)
565 {
566         kprintf("cpu halt\n");
567         for (;;)
568                 __asm__ __volatile("hlt");
569 }