Set kernel_vm_end to virtual_start instead of virtual_end so it can be used
[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.22 2007/01/12 18:03:48 dillon 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         cpu_disable_intr();
174         init_sys_memory(memImageFile);
175         init_kern_memory();
176         init_globaldata();
177         init_vkernel();
178         init_rootdevice(rootImageFile);
179         init_netif(netifFile);
180         init_exceptions();
181         mi_startup();
182         /* NOT REACHED */
183         exit(1);
184 }
185
186 /*
187  * Initialize system memory.  This is the virtual kernel's 'RAM'.
188  */
189 static
190 void
191 init_sys_memory(char *imageFile)
192 {
193         struct stat st;
194         int i;
195         int fd;
196
197         /*
198          * Figure out the system memory image size.  If an image file was
199          * specified and -m was not specified, use the image file's size.
200          */
201
202         if (imageFile && stat(imageFile, &st) == 0 && Maxmem_bytes == 0)
203                 Maxmem_bytes = (vm_paddr_t)st.st_size;
204         if ((imageFile == NULL || stat(imageFile, &st) < 0) && 
205             Maxmem_bytes == 0) {
206                 err(1, "Cannot create new memory file %s unless "
207                        "system memory size is specified with -m",
208                        imageFile);
209                 /* NOT REACHED */
210         }
211
212         /*
213          * Maxmem must be known at this time
214          */
215         if (Maxmem_bytes < 32 * 1024 * 1024 || (Maxmem_bytes & SEG_MASK)) {
216                 err(1, "Bad maxmem specification: 32MB minimum, "
217                        "multiples of %dMB only",
218                        SEG_SIZE / 1024 / 1024);
219                 /* NOT REACHED */
220         }
221
222         /*
223          * Generate an image file name if necessary, then open/create the
224          * file exclusively locked.  Do not allow multiple virtual kernels
225          * to use the same image file.
226          */
227         if (imageFile == NULL) {
228                 for (i = 0; i < 1000000; ++i) {
229                         asprintf(&imageFile, "/var/vkernel/memimg.%06d", i);
230                         fd = open(imageFile, 
231                                   O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
232                         if (fd < 0 && errno == EWOULDBLOCK) {
233                                 free(imageFile);
234                                 continue;
235                         }
236                         break;
237                 }
238         } else {
239                 fd = open(imageFile, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
240         }
241         printf("Using memory file: %s\n", imageFile);
242         if (fd < 0 || fstat(fd, &st) < 0) {
243                 err(1, "Unable to open/create %s: %s",
244                       imageFile, strerror(errno));
245                 /* NOT REACHED */
246         }
247
248         /*
249          * Truncate or extend the file as necessary.
250          */
251         if (st.st_size > Maxmem_bytes) {
252                 ftruncate(fd, Maxmem_bytes);
253         } else if (st.st_size < Maxmem_bytes) {
254                 char *zmem;
255                 off_t off = st.st_size & ~SEG_MASK;
256
257                 kprintf("%s: Reserving blocks for memory image\n", imageFile);
258                 zmem = malloc(SEG_SIZE);
259                 bzero(zmem, SEG_SIZE);
260                 lseek(fd, off, SEEK_SET);
261                 while (off < Maxmem_bytes) {
262                         if (write(fd, zmem, SEG_SIZE) != SEG_SIZE) {
263                                 err(1, "Unable to reserve blocks for memory image");
264                                 /* NOT REACHED */
265                         }
266                         off += SEG_SIZE;
267                 }
268                 if (fsync(fd) < 0)
269                         err(1, "Unable to reserve blocks for memory image");
270                 free(zmem);
271         }
272         MemImageFd = fd;
273         Maxmem = Maxmem_bytes >> PAGE_SHIFT;
274 }
275
276 /*
277  * Initialize kernel memory.  This reserves kernel virtual memory by using
278  * MAP_VPAGETABLE
279  */
280 static
281 void
282 init_kern_memory(void)
283 {
284         void *base;
285         char *zero;
286         vpte_t pte;
287         int i;
288
289         /*
290          * Memory map our kernel virtual memory space.  Note that the
291          * kernel image itself is not made part of this memory for the
292          * moment.
293          *
294          * The memory map must be segment-aligned so we can properly
295          * offset KernelPTD.
296          */
297         base = mmap((void *)0x40000000, KERNEL_KVA_SIZE, PROT_READ|PROT_WRITE,
298                     MAP_FILE|MAP_SHARED|MAP_VPAGETABLE, MemImageFd, 0);
299         madvise(base, KERNEL_KVA_SIZE, MADV_NOSYNC);
300         if (base == MAP_FAILED) {
301                 err(1, "Unable to mmap() kernel virtual memory!");
302                 /* NOT REACHED */
303         }
304         KvaStart = (vm_offset_t)base;
305         KvaSize = KERNEL_KVA_SIZE;
306         KvaEnd = KvaStart + KvaSize;
307
308         /*
309          * Create a top-level page table self-mapping itself. 
310          *
311          * Initialize the page directory at physical page index 0 to point
312          * to an array of page table pages starting at physical page index 1
313          */
314         lseek(MemImageFd, 0L, 0);
315         for (i = 0; i < KERNEL_KVA_SIZE / SEG_SIZE; ++i) {
316                 pte = ((i + 1) * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
317                 write(MemImageFd, &pte, sizeof(pte));
318         }
319
320         /*
321          * Initialize the PTEs in the page table pages required to map the
322          * page table itself.  This includes mapping the page directory page
323          * at the base so we go one more loop then normal.
324          */
325         lseek(MemImageFd, PAGE_SIZE, 0);
326         for (i = 0; i <= KERNEL_KVA_SIZE / SEG_SIZE * sizeof(vpte_t); ++i) {
327                 pte = (i * PAGE_SIZE) | VPTE_V | VPTE_R | VPTE_W;
328                 write(MemImageFd, &pte, sizeof(pte));
329         }
330
331         /*
332          * Initialize remaining PTEs to 0.  We may be reusing a memory image
333          * file.  This is approximately a megabyte.
334          */
335         i = (KERNEL_KVA_SIZE / PAGE_SIZE - i) * sizeof(pte);
336         zero = malloc(PAGE_SIZE);
337         while (i) {
338                 write(MemImageFd, zero, (i > PAGE_SIZE) ? PAGE_SIZE : i);
339                 i = i - ((i > PAGE_SIZE) ? PAGE_SIZE : i);
340         }
341         free(zero);
342
343         /*
344          * Enable the page table and calculate pointers to our self-map
345          * for easy kernel page table manipulation.
346          *
347          * KernelPTA must be offset so we can do direct VA translations
348          */
349         mcontrol(base, KERNEL_KVA_SIZE, MADV_SETMAP,
350                  0 | VPTE_R | VPTE_W | VPTE_V);
351         KernelPTD = (vpte_t *)base;                       /* pg directory */
352         KernelPTA = (vpte_t *)((char *)base + PAGE_SIZE); /* pg table pages */
353         KernelPTA -= KvaStart >> PAGE_SHIFT;
354
355         /*
356          * phys_avail[] represents unallocated physical memory.  MI code
357          * will use phys_avail[] to create the vm_page array.
358          */
359         phys_avail[0] = PAGE_SIZE +
360                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
361         phys_avail[0] = (phys_avail[0] + PAGE_MASK) & ~(vm_paddr_t)PAGE_MASK;
362         phys_avail[1] = Maxmem_bytes;
363
364         /*
365          * (virtual_start, virtual_end) represent unallocated kernel virtual
366          * memory.  MI code will create kernel_map using these parameters.
367          */
368         virtual_start = KvaStart + PAGE_SIZE +
369                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
370         virtual_start = (virtual_start + PAGE_MASK) & ~(vm_offset_t)PAGE_MASK;
371         virtual_end = KvaStart + KERNEL_KVA_SIZE;
372
373         /*
374          * kernel_vm_end could be set to virtual_end but we want some 
375          * indication of how much of the kernel_map we've used, so
376          * set it low and let pmap_growkernel increase it even though we
377          * don't need to create any new page table pages.
378          */
379         kernel_vm_end = virtual_start;
380
381         /*
382          * Allocate space for process 0's UAREA.
383          */
384         proc0paddr = (void *)virtual_start;
385         for (i = 0; i < UPAGES; ++i) {
386                 pmap_kenter_quick(virtual_start, phys_avail[0]);
387                 virtual_start += PAGE_SIZE;
388                 phys_avail[0] += PAGE_SIZE;
389         }
390
391         /*
392          * crashdumpmap
393          */
394         crashdumpmap = virtual_start;
395         virtual_start += MAXDUMPPGS * PAGE_SIZE;
396
397         /*
398          * msgbufp maps the system message buffer
399          */
400         assert((MSGBUF_SIZE & PAGE_MASK) == 0);
401         msgbufp = (void *)virtual_start;
402         for (i = 0; i < (MSGBUF_SIZE >> PAGE_SHIFT); ++i) {
403                 pmap_kenter_quick(virtual_start, phys_avail[0]);
404                 virtual_start += PAGE_SIZE;
405                 phys_avail[0] += PAGE_SIZE;
406         }
407         msgbufinit(msgbufp, MSGBUF_SIZE);
408
409         /*
410          * used by kern_memio for /dev/mem access
411          */
412         ptvmmap = (caddr_t)virtual_start;
413         virtual_start += PAGE_SIZE;
414
415         /*
416          * Bootstrap the kernel_pmap
417          */
418         pmap_bootstrap();
419 }
420
421 /*
422  * Map the per-cpu globaldata for cpu #0.  Allocate the space using
423  * virtual_start and phys_avail[0]
424  */
425 static
426 void
427 init_globaldata(void)
428 {
429         int i;
430         vm_paddr_t pa;
431         vm_offset_t va;
432
433         /*
434          * Reserve enough KVA to cover possible cpus.  This is a considerable
435          * amount of KVA since the privatespace structure includes two 
436          * whole page table mappings.
437          */
438         virtual_start = (virtual_start + SEG_MASK) & ~(vm_offset_t)SEG_MASK;
439         CPU_prvspace = (void *)virtual_start;
440         virtual_start += sizeof(struct privatespace) * SMP_MAXCPU;
441
442         /*
443          * Allocate enough physical memory to cover the mdglobaldata
444          * portion of the space and the idle stack and map the pages
445          * into KVA.  For cpu #0 only.
446          */
447         for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
448                 pa = phys_avail[0];
449                 va = (vm_offset_t)&CPU_prvspace[0].mdglobaldata + i;
450                 pmap_kenter_quick(va, pa);
451                 phys_avail[0] += PAGE_SIZE;
452         }
453         for (i = 0; i < sizeof(CPU_prvspace[0].idlestack); i += PAGE_SIZE) {
454                 pa = phys_avail[0];
455                 va = (vm_offset_t)&CPU_prvspace[0].idlestack + i;
456                 pmap_kenter_quick(va, pa);
457                 phys_avail[0] += PAGE_SIZE;
458         }
459
460         /*
461          * Setup the %gs for cpu #0.  The mycpu macro works after this
462          * point.
463          */
464         tls_set_fs(&CPU_prvspace[0], sizeof(struct privatespace));
465 }
466
467 /*
468  * Initialize very low level systems including thread0, proc0, etc.
469  */
470 static
471 void
472 init_vkernel(void)
473 {
474         struct mdglobaldata *gd;
475
476         gd = &CPU_prvspace[0].mdglobaldata;
477         bzero(gd, sizeof(*gd));
478
479         gd->mi.gd_curthread = &thread0;
480         thread0.td_gd = &gd->mi;
481         ncpus = 1;
482         ncpus2 = 1;
483         init_param1();
484         gd->mi.gd_prvspace = &CPU_prvspace[0];
485         mi_gdinit(&gd->mi, 0);
486         cpu_gdinit(gd, 0);
487         mi_proc0init(&gd->mi, proc0paddr);
488         proc0.p_lwp.lwp_md.md_regs = &proc0_tf;
489
490         /*init_locks();*/
491         cninit();
492         rand_initialize();
493 #if 0   /* #ifdef DDB */
494         kdb_init();
495         if (boothowto & RB_KDB)
496                 Debugger("Boot flags requested debugger");
497 #endif
498 #if 0
499         initializecpu();        /* Initialize CPU registers */
500 #endif
501         init_param2((phys_avail[1] - phys_avail[0]) / PAGE_SIZE);
502
503 #if 0
504         /*
505          * Map the message buffer
506          */
507         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
508                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
509         msgbufinit(msgbufp, MSGBUF_SIZE);
510 #endif
511 #if 0
512         thread0.td_pcb_cr3 ... MMU
513         proc0.p_lwp.lwp_md.md_regs = &proc0_tf;
514 #endif
515 }
516
517 /*
518  * The root filesystem path for the virtual kernel is optional.  If specified
519  * it points to a filesystem image.
520  *
521  * The virtual kernel caches data from our 'disk' just like a normal kernel,
522  * so we do not really want the real kernel to cache the data too.  Use
523  * O_DIRECT to remove the duplication.
524  */
525 static
526 void
527 init_rootdevice(char *imageFile)
528 {
529         struct stat st;
530
531         if (imageFile) {
532                 RootImageFd = open(imageFile, O_RDWR|O_DIRECT, 0644);
533                 if (RootImageFd < 0 || fstat(RootImageFd, &st) < 0) {
534                         err(1, "Unable to open/create %s: %s",
535                             imageFile, strerror(errno));
536                         /* NOT REACHED */
537                 }
538                 rootdevnames[0] = "ufs:vkd0a";
539         }
540 }
541
542 static
543 void
544 init_netif(char *netifFile)
545 {
546         if (netifFile) {
547                 NetifFd = open(netifFile, O_RDWR | O_NONBLOCK);
548                 if (NetifFd < 0) {
549                         warn("Unable to open %s: %s",
550                              netifFile, strerror(errno));
551                 }
552         }
553 }
554
555 static
556 void
557 usage(const char *ctl)
558 {
559         
560 }
561
562 void
563 cpu_reset(void)
564 {
565         kprintf("cpu reset\n");
566         exit(0);
567 }
568
569 void
570 cpu_halt(void)
571 {
572         kprintf("cpu halt\n");
573         for (;;)
574                 __asm__ __volatile("hlt");
575 }