hammer2 - Merge Mihai Carabas's VKERNEL/VMM GSOC project into the main tree
[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
35 #include <sys/types.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/stat.h>
39 #include <sys/mman.h>
40 #include <sys/cons.h>
41 #include <sys/random.h>
42 #include <sys/vkernel.h>
43 #include <sys/tls.h>
44 #include <sys/reboot.h>
45 #include <sys/proc.h>
46 #include <sys/msgbuf.h>
47 #include <sys/vmspace.h>
48 #include <sys/socket.h>
49 #include <sys/sockio.h>
50 #include <sys/sysctl.h>
51 #include <sys/un.h>
52 #include <vm/vm_page.h>
53 #include <sys/mplock2.h>
54
55 #include <machine/cpu.h>
56 #include <machine/globaldata.h>
57 #include <machine/tls.h>
58 #include <machine/md_var.h>
59 #include <machine/vmparam.h>
60 #include <cpu/specialreg.h>
61
62 #include <net/if.h>
63 #include <net/if_arp.h>
64 #include <net/ethernet.h>
65 #include <net/bridge/if_bridgevar.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #include <net/if_var.h>
69
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <stdarg.h>
73 #include <stdbool.h>
74 #include <unistd.h>
75 #include <fcntl.h>
76 #include <string.h>
77 #include <err.h>
78 #include <errno.h>
79 #include <assert.h>
80 #include <sysexits.h>
81
82 vm_paddr_t phys_avail[16];
83 vm_paddr_t Maxmem;
84 vm_paddr_t Maxmem_bytes;
85 long physmem;
86 int MemImageFd = -1;
87 struct vkdisk_info DiskInfo[VKDISK_MAX];
88 int DiskNum;
89 struct vknetif_info NetifInfo[VKNETIF_MAX];
90 int NetifNum;
91 char *pid_file;
92 vm_offset_t KvaStart;
93 vm_offset_t KvaEnd;
94 vm_offset_t KvaSize;
95 vm_offset_t virtual_start;
96 vm_offset_t virtual_end;
97 vm_offset_t virtual2_start;
98 vm_offset_t virtual2_end;
99 vm_offset_t kernel_vm_end;
100 vm_offset_t crashdumpmap;
101 vm_offset_t clean_sva;
102 vm_offset_t clean_eva;
103 struct msgbuf *msgbufp;
104 caddr_t ptvmmap;
105 vpte_t  *KernelPTD;
106 vpte_t  *KernelPTA;     /* Warning: Offset for direct VA translation */
107 u_int cpu_feature;      /* XXX */
108 int tsc_present;
109 int tsc_invariant;
110 int tsc_mpsync;
111 int64_t tsc_frequency;
112 int optcpus;            /* number of cpus - see mp_start() */
113 int lwp_cpu_lock;       /* if/how to lock virtual CPUs to real CPUs */
114 int real_ncpus;         /* number of real CPUs */
115 int next_cpu;           /* next real CPU to lock a virtual CPU to */
116 int vkernel_b_arg;      /* -b argument - no of logical CPU bits - only SMP */
117 int vkernel_B_arg;      /* -B argument - no of core bits - only SMP */
118
119 int via_feature_xcrypt = 0;     /* XXX */
120 int via_feature_rng = 0;        /* XXX */
121
122 struct privatespace *CPU_prvspace;
123
124 static struct trapframe proc0_tf;
125 static void *proc0paddr;
126
127 static void init_sys_memory(char *imageFile);
128 static void init_kern_memory(void);
129 static void init_globaldata(void);
130 static void init_vkernel(void);
131 static void init_disk(char *diskExp[], int diskFileNum, enum vkdisk_type type); 
132 static void init_netif(char *netifExp[], int netifFileNum);
133 static void writepid(void);
134 static void cleanpid(void);
135 static int unix_connect(const char *path);
136 static void usage_err(const char *ctl, ...);
137 static void usage_help(_Bool);
138 static void init_locks(void);
139
140 static int save_ac;
141 static char **save_av;
142
143 /*
144  * Kernel startup for virtual kernels - standard main() 
145  */
146 int
147 main(int ac, char **av)
148 {
149         char *memImageFile = NULL;
150         char *netifFile[VKNETIF_MAX];
151         char *diskFile[VKDISK_MAX];
152         char *cdFile[VKDISK_MAX];
153         char *suffix;
154         char *endp;
155         char *tmp;
156         char *tok;
157         int netifFileNum = 0;
158         int diskFileNum = 0;
159         int cdFileNum = 0;
160         int bootOnDisk = -1;    /* set below to vcd (0) or vkd (1) */
161         int c;
162         int i;
163         int j;
164         int n;
165         int isq;
166         int pos;
167         int eflag;
168         int real_vkernel_enable;
169         int supports_sse;
170         size_t vsize;
171         size_t kenv_size;
172         size_t kenv_size2;
173         
174         save_ac = ac;
175         save_av = av;
176         eflag = 0;
177         pos = 0;
178         kenv_size = 0;
179
180         /*
181          * Process options
182          */
183         kernel_mem_readonly = 1;
184         optcpus = 2;
185         vkernel_b_arg = 0;
186         vkernel_B_arg = 0;
187         lwp_cpu_lock = LCL_NONE;
188
189         real_vkernel_enable = 0;
190         vsize = sizeof(real_vkernel_enable);
191         sysctlbyname("vm.vkernel_enable", &real_vkernel_enable, &vsize, NULL,0);
192         
193         if (real_vkernel_enable == 0) {
194                 errx(1, "vm.vkernel_enable is 0, must be set "
195                         "to 1 to execute a vkernel!");
196         }
197
198         real_ncpus = 1;
199         vsize = sizeof(real_ncpus);
200         sysctlbyname("hw.ncpu", &real_ncpus, &vsize, NULL, 0);
201
202         if (ac < 2)
203                 usage_help(false);
204
205         while ((c = getopt(ac, av, "c:hsvl:m:n:r:e:i:p:I:Ub:B:")) != -1) {
206                 switch(c) {
207                 case 'e':
208                         /*
209                          * name=value:name=value:name=value...
210                          * name="value"...
211                          *
212                          * Allow values to be quoted but note that shells
213                          * may remove the quotes, so using this feature
214                          * to embed colons may require a backslash.
215                          */
216                         n = strlen(optarg);
217                         isq = 0;
218
219                         if (eflag == 0) {
220                                 kenv_size = n + 2;
221                                 kern_envp = malloc(kenv_size);
222                                 if (kern_envp == NULL)
223                                         errx(1, "Couldn't allocate %zd bytes for kern_envp", kenv_size);
224                         } else {
225                                 kenv_size2 = kenv_size + n + 1;
226                                 pos = kenv_size - 1;
227                                 if ((tmp = realloc(kern_envp, kenv_size2)) == NULL)
228                                         errx(1, "Couldn't reallocate %zd bytes for kern_envp", kenv_size2);
229                                 kern_envp = tmp;
230                                 kenv_size = kenv_size2;
231                         }
232
233                         for (i = 0, j = pos; i < n; ++i) {
234                                 if (optarg[i] == '"')
235                                         isq ^= 1;
236                                 else if (optarg[i] == '\'')
237                                         isq ^= 2;
238                                 else if (isq == 0 && optarg[i] == ':')
239                                         kern_envp[j++] = 0;
240                                 else
241                                         kern_envp[j++] = optarg[i];
242                         }
243                         kern_envp[j++] = 0;
244                         kern_envp[j++] = 0;
245                         eflag++;
246                         break;
247                 case 's':
248                         boothowto |= RB_SINGLE;
249                         break;
250                 case 'v':
251                         bootverbose = 1;
252                         break;
253                 case 'i':
254                         memImageFile = optarg;
255                         break;
256                 case 'I':
257                         if (netifFileNum < VKNETIF_MAX)
258                                 netifFile[netifFileNum++] = strdup(optarg);
259                         break;
260                 case 'r':
261                         if (bootOnDisk < 0)
262                                 bootOnDisk = 1;
263                         if (diskFileNum + cdFileNum < VKDISK_MAX)
264                                 diskFile[diskFileNum++] = strdup(optarg);
265                         break;
266                 case 'c':
267                         if (bootOnDisk < 0)
268                                 bootOnDisk = 0;
269                         if (diskFileNum + cdFileNum < VKDISK_MAX)
270                                 cdFile[cdFileNum++] = strdup(optarg);
271                         break;
272                 case 'm':
273                         Maxmem_bytes = strtoull(optarg, &suffix, 0);
274                         if (suffix) {
275                                 switch(*suffix) {
276                                 case 'g':
277                                 case 'G':
278                                         Maxmem_bytes <<= 30;
279                                         break;
280                                 case 'm':
281                                 case 'M':
282                                         Maxmem_bytes <<= 20;
283                                         break;
284                                 case 'k':
285                                 case 'K':
286                                         Maxmem_bytes <<= 10;
287                                         break;
288                                 default:
289                                         Maxmem_bytes = 0;
290                                         usage_err("Bad maxmem option");
291                                         /* NOT REACHED */
292                                         break;
293                                 }
294                         }
295                         break;
296                 case 'l':
297                         next_cpu = -1;
298                         if (strncmp("map", optarg, 3) == 0) {
299                                 lwp_cpu_lock = LCL_PER_CPU;
300                                 if (optarg[3] == ',') {
301                                         next_cpu = strtol(optarg+4, &endp, 0);
302                                         if (*endp != '\0')
303                                                 usage_err("Bad target CPU number at '%s'", endp);
304                                 } else {
305                                         next_cpu = 0;
306                                 }
307                                 if (next_cpu < 0 || next_cpu > real_ncpus - 1)
308                                         usage_err("Bad target CPU, valid range is 0-%d", real_ncpus - 1);
309                         } else if (strncmp("any", optarg, 3) == 0) {
310                                 lwp_cpu_lock = LCL_NONE;
311                         } else {
312                                 lwp_cpu_lock = LCL_SINGLE_CPU;
313                                 next_cpu = strtol(optarg, &endp, 0);
314                                 if (*endp != '\0')
315                                         usage_err("Bad target CPU number at '%s'", endp);
316                                 if (next_cpu < 0 || next_cpu > real_ncpus - 1)
317                                         usage_err("Bad target CPU, valid range is 0-%d", real_ncpus - 1);
318                         }
319                         break;
320                 case 'n':
321                         /*
322                          * This value is set up by mp_start(), don't just
323                          * set ncpus here.
324                          */
325                         tok = strtok(optarg, ":");
326                         optcpus = strtol(tok, NULL, 0);
327                         if (optcpus < 1 || optcpus > MAXCPU)
328                                 usage_err("Bad ncpus, valid range is 1-%d", MAXCPU);
329                         
330                         /* :core_bits argument */
331                         tok = strtok(NULL, ":");
332                         if (tok != NULL) {
333                                 vkernel_b_arg = strtol(tok, NULL, 0);
334
335                                 /* :logical_CPU_bits argument */
336                                 tok = strtok(NULL, ":");
337                                 if (tok != NULL) {
338                                         vkernel_B_arg = strtol(tok, NULL, 0);
339                                 }
340
341                         }
342                         break;
343                 case 'p':
344                         pid_file = optarg;
345                         break;
346                 case 'U':
347                         kernel_mem_readonly = 0;
348                         break;
349                 case 'h':
350                         usage_help(true);
351                         break;
352                 default:
353                         usage_help(false);
354                 }
355         }
356
357         writepid();
358         cpu_disable_intr();
359         init_sys_memory(memImageFile);
360         init_kern_memory();
361         init_globaldata();
362         init_vkernel();
363         setrealcpu();
364         init_kqueue();
365
366         vmm_guest = 1;
367
368         /*
369          * Check TSC
370          */
371         vsize = sizeof(tsc_present);
372         sysctlbyname("hw.tsc_present", &tsc_present, &vsize, NULL, 0);
373         vsize = sizeof(tsc_invariant);
374         sysctlbyname("hw.tsc_invariant", &tsc_invariant, &vsize, NULL, 0);
375         vsize = sizeof(tsc_mpsync);
376         sysctlbyname("hw.tsc_mpsync", &tsc_mpsync, &vsize, NULL, 0);
377         vsize = sizeof(tsc_frequency);
378         sysctlbyname("hw.tsc_frequency", &tsc_frequency, &vsize, NULL, 0);
379         if (tsc_present)
380                 cpu_feature |= CPUID_TSC;
381
382         /*
383          * Check SSE
384          */
385         vsize = sizeof(supports_sse);
386         supports_sse = 0;
387         sysctlbyname("hw.instruction_sse", &supports_sse, &vsize, NULL, 0);
388         init_fpu(supports_sse);
389         if (supports_sse)
390                 cpu_feature |= CPUID_SSE | CPUID_FXSR;
391
392         /*
393          * We boot from the first installed disk.
394          */
395         if (bootOnDisk == 1) {
396                 init_disk(diskFile, diskFileNum, VKD_DISK);
397                 init_disk(cdFile, cdFileNum, VKD_CD);
398         } else {
399                 init_disk(cdFile, cdFileNum, VKD_CD);
400                 init_disk(diskFile, diskFileNum, VKD_DISK);
401         }
402         init_netif(netifFile, netifFileNum);
403         init_exceptions();
404         mi_startup();
405         /* NOT REACHED */
406         exit(EX_SOFTWARE);
407 }
408
409 /*
410  * Initialize system memory.  This is the virtual kernel's 'RAM'.
411  */
412 static
413 void
414 init_sys_memory(char *imageFile)
415 {
416         struct stat st;
417         int i;
418         int fd;
419
420         /*
421          * Figure out the system memory image size.  If an image file was
422          * specified and -m was not specified, use the image file's size.
423          */
424         if (imageFile && stat(imageFile, &st) == 0 && Maxmem_bytes == 0)
425                 Maxmem_bytes = (vm_paddr_t)st.st_size;
426         if ((imageFile == NULL || stat(imageFile, &st) < 0) && 
427             Maxmem_bytes == 0) {
428                 errx(1, "Cannot create new memory file %s unless "
429                        "system memory size is specified with -m",
430                        imageFile);
431                 /* NOT REACHED */
432         }
433
434         /*
435          * Maxmem must be known at this time
436          */
437         if (Maxmem_bytes < 32 * 1024 * 1024 || (Maxmem_bytes & SEG_MASK)) {
438                 errx(1, "Bad maxmem specification: 32MB minimum, "
439                        "multiples of %dMB only",
440                        SEG_SIZE / 1024 / 1024);
441                 /* NOT REACHED */
442         }
443
444         /*
445          * Generate an image file name if necessary, then open/create the
446          * file exclusively locked.  Do not allow multiple virtual kernels
447          * to use the same image file.
448          *
449          * Don't iterate through a million files if we do not have write
450          * access to the directory, stop if our open() failed on a
451          * non-existant file.  Otherwise opens can fail for any number
452          * of reasons (lock failed, file not owned or writable by us, etc).
453          */
454         if (imageFile == NULL) {
455                 for (i = 0; i < 1000000; ++i) {
456                         asprintf(&imageFile, "/var/vkernel/memimg.%06d", i);
457                         fd = open(imageFile, 
458                                   O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
459                         if (fd < 0 && stat(imageFile, &st) == 0) {
460                                 free(imageFile);
461                                 continue;
462                         }
463                         break;
464                 }
465         } else {
466                 fd = open(imageFile, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0644);
467         }
468         printf("Using memory file: %s\n", imageFile);
469         if (fd < 0 || fstat(fd, &st) < 0) {
470                 err(1, "Unable to open/create %s", imageFile);
471                 /* NOT REACHED */
472         }
473
474         /*
475          * Truncate or extend the file as necessary.  Clean out the contents
476          * of the file, we want it to be full of holes so we don't waste
477          * time reading in data from an old file that we no longer care
478          * about.
479          */
480         ftruncate(fd, 0);
481         ftruncate(fd, Maxmem_bytes);
482
483         MemImageFd = fd;
484         Maxmem = Maxmem_bytes >> PAGE_SHIFT;
485         physmem = Maxmem;
486 }
487
488 /*
489  * Initialize pool tokens and other necessary locks
490  */
491 static void
492 init_locks(void)
493 {
494
495         /*
496          * Get the initial mplock with a count of 1 for the BSP.
497          * This uses a LOGICAL cpu ID, ie BSP == 0.
498          */
499         cpu_get_initial_mplock();
500
501         /* our token pool needs to work early */
502         lwkt_token_pool_init();
503
504 }
505
506 /*
507  * Initialize kernel memory.  This reserves kernel virtual memory by using
508  * MAP_VPAGETABLE
509  */
510
511 static
512 void
513 init_kern_memory(void)
514 {
515         void *base;
516         void *try;
517         char *zero;
518         char dummy;
519         char *topofstack = &dummy;
520         vpte_t pte;
521         int i;
522
523         /*
524          * Memory map our kernel virtual memory space.  Note that the
525          * kernel image itself is not made part of this memory for the
526          * moment.
527          *
528          * The memory map must be segment-aligned so we can properly
529          * offset KernelPTD.
530          *
531          * If the system kernel has a different MAXDSIZ, it might not
532          * be possible to map kernel memory in its prefered location.
533          * Try a number of different locations.
534          */
535         try = (void *)0x40000000;
536         base = NULL;
537         while ((char *)try + KERNEL_KVA_SIZE < topofstack) {
538                 base = mmap(try, KERNEL_KVA_SIZE, PROT_READ|PROT_WRITE,
539                             MAP_FILE|MAP_SHARED|MAP_VPAGETABLE,
540                             MemImageFd, 0);
541                 if (base == try)
542                         break;
543                 if (base != MAP_FAILED)
544                         munmap(base, KERNEL_KVA_SIZE);
545                 try = (char *)try + 0x10000000;
546         }
547         if (base != try) {
548                 err(1, "Unable to mmap() kernel virtual memory!");
549                 /* NOT REACHED */
550         }
551         madvise(base, KERNEL_KVA_SIZE, MADV_NOSYNC);
552         KvaStart = (vm_offset_t)base;
553         KvaSize = KERNEL_KVA_SIZE;
554         KvaEnd = KvaStart + KvaSize;
555
556         /* cannot use kprintf yet */
557         printf("KVM mapped at %p-%p\n", (void *)KvaStart, (void *)KvaEnd);
558
559         /*
560          * Create a top-level page table self-mapping itself. 
561          *
562          * Initialize the page directory at physical page index 0 to point
563          * to an array of page table pages starting at physical page index 1
564          */
565         lseek(MemImageFd, 0L, 0);
566         for (i = 0; i < KERNEL_KVA_SIZE / SEG_SIZE; ++i) {
567                 pte = ((i + 1) * PAGE_SIZE) | VPTE_V | VPTE_RW;
568                 write(MemImageFd, &pte, sizeof(pte));
569         }
570
571         /*
572          * Initialize the PTEs in the page table pages required to map the
573          * page table itself.  This includes mapping the page directory page
574          * at the base so we go one more loop then normal.
575          */
576         lseek(MemImageFd, PAGE_SIZE, 0);
577         for (i = 0; i <= KERNEL_KVA_SIZE / SEG_SIZE * sizeof(vpte_t); ++i) {
578                 pte = (i * PAGE_SIZE) | VPTE_V | VPTE_RW;
579                 write(MemImageFd, &pte, sizeof(pte));
580         }
581
582         /*
583          * Initialize remaining PTEs to 0.  We may be reusing a memory image
584          * file.  This is approximately a megabyte.
585          */
586         i = (KERNEL_KVA_SIZE / PAGE_SIZE - i) * sizeof(pte);
587         zero = malloc(PAGE_SIZE);
588         bzero(zero, PAGE_SIZE);
589         while (i) {
590                 write(MemImageFd, zero, (i > PAGE_SIZE) ? PAGE_SIZE : i);
591                 i = i - ((i > PAGE_SIZE) ? PAGE_SIZE : i);
592         }
593         free(zero);
594
595         /*
596          * Enable the page table and calculate pointers to our self-map
597          * for easy kernel page table manipulation.
598          *
599          * KernelPTA must be offset so we can do direct VA translations
600          */
601         mcontrol(base, KERNEL_KVA_SIZE, MADV_SETMAP,
602                  0 | VPTE_RW | VPTE_V);
603         KernelPTD = (vpte_t *)base;                       /* pg directory */
604         KernelPTA = (vpte_t *)((char *)base + PAGE_SIZE); /* pg table pages */
605         KernelPTA -= KvaStart >> PAGE_SHIFT;
606
607         /*
608          * phys_avail[] represents unallocated physical memory.  MI code
609          * will use phys_avail[] to create the vm_page array.
610          */
611         phys_avail[0] = PAGE_SIZE +
612                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
613         phys_avail[0] = (phys_avail[0] + PAGE_MASK) & ~(vm_paddr_t)PAGE_MASK;
614         phys_avail[1] = Maxmem_bytes;
615
616         /*
617          * (virtual_start, virtual_end) represent unallocated kernel virtual
618          * memory.  MI code will create kernel_map using these parameters.
619          */
620         virtual_start = KvaStart + PAGE_SIZE +
621                         KERNEL_KVA_SIZE / PAGE_SIZE * sizeof(vpte_t);
622         virtual_start = (virtual_start + PAGE_MASK) & ~(vm_offset_t)PAGE_MASK;
623         virtual_end = KvaStart + KERNEL_KVA_SIZE;
624
625         /*
626          * kernel_vm_end could be set to virtual_end but we want some 
627          * indication of how much of the kernel_map we've used, so
628          * set it low and let pmap_growkernel increase it even though we
629          * don't need to create any new page table pages.
630          */
631         kernel_vm_end = virtual_start;
632
633         /*
634          * Allocate space for process 0's UAREA.
635          */
636         proc0paddr = (void *)virtual_start;
637         for (i = 0; i < UPAGES; ++i) {
638                 pmap_kenter_quick(virtual_start, phys_avail[0]);
639                 virtual_start += PAGE_SIZE;
640                 phys_avail[0] += PAGE_SIZE;
641         }
642
643         /*
644          * crashdumpmap
645          */
646         crashdumpmap = virtual_start;
647         virtual_start += MAXDUMPPGS * PAGE_SIZE;
648
649         /*
650          * msgbufp maps the system message buffer
651          */
652         assert((MSGBUF_SIZE & PAGE_MASK) == 0);
653         msgbufp = (void *)virtual_start;
654         for (i = 0; i < (MSGBUF_SIZE >> PAGE_SHIFT); ++i) {
655                 pmap_kenter_quick(virtual_start, phys_avail[0]);
656                 virtual_start += PAGE_SIZE;
657                 phys_avail[0] += PAGE_SIZE;
658         }
659         msgbufinit(msgbufp, MSGBUF_SIZE);
660
661         /*
662          * used by kern_memio for /dev/mem access
663          */
664         ptvmmap = (caddr_t)virtual_start;
665         virtual_start += PAGE_SIZE;
666
667         /*
668          * Bootstrap the kernel_pmap
669          */
670         pmap_bootstrap();
671 }
672
673 /*
674  * Map the per-cpu globaldata for cpu #0.  Allocate the space using
675  * virtual_start and phys_avail[0]
676  */
677 static
678 void
679 init_globaldata(void)
680 {
681         int i;
682         vm_paddr_t pa;
683         vm_offset_t va;
684
685         /*
686          * Reserve enough KVA to cover possible cpus.  This is a considerable
687          * amount of KVA since the privatespace structure includes two 
688          * whole page table mappings.
689          */
690         virtual_start = (virtual_start + SEG_MASK) & ~(vm_offset_t)SEG_MASK;
691         CPU_prvspace = (void *)virtual_start;
692         virtual_start += sizeof(struct privatespace) * SMP_MAXCPU;
693
694         /*
695          * Allocate enough physical memory to cover the mdglobaldata
696          * portion of the space and the idle stack and map the pages
697          * into KVA.  For cpu #0 only.
698          */
699         for (i = 0; i < sizeof(struct mdglobaldata); i += PAGE_SIZE) {
700                 pa = phys_avail[0];
701                 va = (vm_offset_t)&CPU_prvspace[0].mdglobaldata + i;
702                 pmap_kenter_quick(va, pa);
703                 phys_avail[0] += PAGE_SIZE;
704         }
705         for (i = 0; i < sizeof(CPU_prvspace[0].idlestack); i += PAGE_SIZE) {
706                 pa = phys_avail[0];
707                 va = (vm_offset_t)&CPU_prvspace[0].idlestack + i;
708                 pmap_kenter_quick(va, pa);
709                 phys_avail[0] += PAGE_SIZE;
710         }
711
712         /*
713          * Setup the %fs for cpu #0.  The mycpu macro works after this
714          * point.  Note that %gs is used by pthreads.
715          */
716         tls_set_fs(&CPU_prvspace[0], sizeof(struct privatespace));
717 }
718
719 /*
720  * Initialize very low level systems including thread0, proc0, etc.
721  */
722 static
723 void
724 init_vkernel(void)
725 {
726         struct mdglobaldata *gd;
727
728         gd = &CPU_prvspace[0].mdglobaldata;
729         bzero(gd, sizeof(*gd));
730
731         gd->mi.gd_curthread = &thread0;
732         thread0.td_gd = &gd->mi;
733         ncpus = 1;
734         ncpus2 = 1;     /* rounded down power of 2 */
735         ncpus_fit = 1;  /* rounded up power of 2 */
736         /* ncpus2_mask and ncpus_fit_mask are 0 */
737         init_param1();
738         gd->mi.gd_prvspace = &CPU_prvspace[0];
739         mi_gdinit(&gd->mi, 0);
740         cpu_gdinit(gd, 0);
741         mi_proc0init(&gd->mi, proc0paddr);
742         lwp0.lwp_md.md_regs = &proc0_tf;
743
744         init_locks();
745         cninit();
746         rand_initialize();
747 #if 0   /* #ifdef DDB */
748         kdb_init();
749         if (boothowto & RB_KDB)
750                 Debugger("Boot flags requested debugger");
751 #endif
752         identcpu();
753 #if 0
754         initializecpu();        /* Initialize CPU registers */
755 #endif
756         init_param2((phys_avail[1] - phys_avail[0]) / PAGE_SIZE);
757
758 #if 0
759         /*
760          * Map the message buffer
761          */
762         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
763                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
764         msgbufinit(msgbufp, MSGBUF_SIZE);
765 #endif
766 #if 0
767         thread0.td_pcb_cr3 ... MMU
768         lwp0.lwp_md.md_regs = &proc0_tf;
769 #endif
770 }
771
772 /*
773  * Filesystem image paths for the virtual kernel are optional.  
774  * If specified they each should point to a disk image, 
775  * the first of which will become the root disk.
776  *
777  * The virtual kernel caches data from our 'disk' just like a normal kernel,
778  * so we do not really want the real kernel to cache the data too.  Use
779  * O_DIRECT to remove the duplication.
780  */
781 static
782 void
783 init_disk(char *diskExp[], int diskFileNum, enum vkdisk_type type)
784 {
785         char *serno;
786         int i;  
787
788         if (diskFileNum == 0)
789                 return;
790
791         for(i=0; i < diskFileNum; i++){
792                 char *fname;
793                 fname = diskExp[i];
794
795                 if (fname == NULL) {
796                         warnx("Invalid argument to '-r'");
797                         continue;
798                 }
799                 /*
800                  * Check for a serial number for the virtual disk
801                  * passed from the command line.
802                  */
803                 serno = fname;
804                 strsep(&serno, ":");
805
806                 if (DiskNum < VKDISK_MAX) {
807                         struct stat st; 
808                         struct vkdisk_info* info = NULL;
809                         int fd;
810                         size_t l = 0;
811
812                         if (type == VKD_DISK)
813                             fd = open(fname, O_RDWR|O_DIRECT, 0644);
814                         else
815                             fd = open(fname, O_RDONLY|O_DIRECT, 0644);
816                         if (fd < 0 || fstat(fd, &st) < 0) {
817                                 err(1, "Unable to open/create %s", fname);
818                                 /* NOT REACHED */
819                         }
820                         if (S_ISREG(st.st_mode)) {
821                                 if (flock(fd, LOCK_EX|LOCK_NB) < 0) {
822                                         errx(1, "Disk image %s is already "
823                                                 "in use\n", fname);
824                                         /* NOT REACHED */
825                                 }
826                         }
827
828                         info = &DiskInfo[DiskNum];
829                         l = strlen(fname);
830
831                         info->unit = i;
832                         info->fd = fd;
833                         info->type = type;
834                         memcpy(info->fname, fname, l);
835                         info->serno = NULL;
836                         if (serno) {
837                                 if ((info->serno = malloc(SERNOLEN)) != NULL)
838                                     strlcpy(info->serno, serno, SERNOLEN);
839                                 else
840                                     warnx("Couldn't allocate memory for the operation");
841                         }
842
843                         if (DiskNum == 0) {
844                                 if (type == VKD_CD) {
845                                     rootdevnames[0] = "cd9660:vcd0a";
846                                 } else if (type == VKD_DISK) {
847                                     rootdevnames[0] = "ufs:vkd0s0a";
848                                     rootdevnames[1] = "ufs:vkd0s1a";
849                                 }
850                         }
851
852                         DiskNum++;
853                 } else {
854                         warnx("vkd%d (%s) > VKDISK_MAX", DiskNum, fname);
855                         continue;
856                 }
857         }
858 }
859
860 static
861 int
862 netif_set_tapflags(int tap_unit, int f, int s)
863 {
864         struct ifreq ifr;
865         int flags;
866
867         bzero(&ifr, sizeof(ifr));
868
869         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
870         if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
871                 warn("tap%d: ioctl(SIOCGIFFLAGS) failed", tap_unit);
872                 return -1;
873         }
874
875         /*
876          * Adjust if_flags
877          *
878          * If the flags are already set/cleared, then we return
879          * immediately to avoid extra syscalls
880          */
881         flags = (ifr.ifr_flags & 0xffff) | (ifr.ifr_flagshigh << 16);
882         if (f < 0) {
883                 /* Turn off flags */
884                 f = -f;
885                 if ((flags & f) == 0)
886                         return 0;
887                 flags &= ~f;
888         } else {
889                 /* Turn on flags */
890                 if (flags & f)
891                         return 0;
892                 flags |= f;
893         }
894
895         /*
896          * Fix up ifreq.ifr_name, since it may be trashed
897          * in previous ioctl(SIOCGIFFLAGS)
898          */
899         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tap%d", tap_unit);
900
901         ifr.ifr_flags = flags & 0xffff;
902         ifr.ifr_flagshigh = flags >> 16;
903         if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) {
904                 warn("tap%d: ioctl(SIOCSIFFLAGS) failed", tap_unit);
905                 return -1;
906         }
907         return 0;
908 }
909
910 static
911 int
912 netif_set_tapaddr(int tap_unit, in_addr_t addr, in_addr_t mask, int s)
913 {
914         struct ifaliasreq ifra;
915         struct sockaddr_in *in;
916
917         bzero(&ifra, sizeof(ifra));
918         snprintf(ifra.ifra_name, sizeof(ifra.ifra_name), "tap%d", tap_unit);
919
920         /* Setup address */
921         in = (struct sockaddr_in *)&ifra.ifra_addr;
922         in->sin_family = AF_INET;
923         in->sin_len = sizeof(*in);
924         in->sin_addr.s_addr = addr;
925
926         if (mask != 0) {
927                 /* Setup netmask */
928                 in = (struct sockaddr_in *)&ifra.ifra_mask;
929                 in->sin_len = sizeof(*in);
930                 in->sin_addr.s_addr = mask;
931         }
932
933         if (ioctl(s, SIOCAIFADDR, &ifra) < 0) {
934                 warn("tap%d: ioctl(SIOCAIFADDR) failed", tap_unit);
935                 return -1;
936         }
937         return 0;
938 }
939
940 static
941 int
942 netif_add_tap2brg(int tap_unit, const char *ifbridge, int s)
943 {
944         struct ifbreq ifbr;
945         struct ifdrv ifd;
946
947         bzero(&ifbr, sizeof(ifbr));
948         snprintf(ifbr.ifbr_ifsname, sizeof(ifbr.ifbr_ifsname),
949                  "tap%d", tap_unit);
950
951         bzero(&ifd, sizeof(ifd));
952         strlcpy(ifd.ifd_name, ifbridge, sizeof(ifd.ifd_name));
953         ifd.ifd_cmd = BRDGADD;
954         ifd.ifd_len = sizeof(ifbr);
955         ifd.ifd_data = &ifbr;
956
957         if (ioctl(s, SIOCSDRVSPEC, &ifd) < 0) {
958                 /*
959                  * 'errno == EEXIST' means that the tap(4) is already
960                  * a member of the bridge(4)
961                  */
962                 if (errno != EEXIST) {
963                         warn("ioctl(%s, SIOCSDRVSPEC) failed", ifbridge);
964                         return -1;
965                 }
966         }
967         return 0;
968 }
969
970 #define TAPDEV_OFLAGS   (O_RDWR | O_NONBLOCK)
971
972 /*
973  * Locate the first unused tap(4) device file if auto mode is requested,
974  * or open the user supplied device file, and bring up the corresponding
975  * tap(4) interface.
976  *
977  * NOTE: Only tap(4) device file is supported currently
978  */
979 static
980 int
981 netif_open_tap(const char *netif, int *tap_unit, int s)
982 {
983         char tap_dev[MAXPATHLEN];
984         int tap_fd, failed;
985         struct stat st;
986         char *dname;
987
988         *tap_unit = -1;
989
990         if (strcmp(netif, "auto") == 0) {
991                 /*
992                  * Find first unused tap(4) device file
993                  */
994                 tap_fd = open("/dev/tap", TAPDEV_OFLAGS);
995                 if (tap_fd < 0) {
996                         warnc(errno, "Unable to find a free tap(4)");
997                         return -1;
998                 }
999         } else {
1000                 /*
1001                  * User supplied tap(4) device file or unix socket.
1002                  */
1003                 if (netif[0] == '/')    /* Absolute path */
1004                         strlcpy(tap_dev, netif, sizeof(tap_dev));
1005                 else
1006                         snprintf(tap_dev, sizeof(tap_dev), "/dev/%s", netif);
1007
1008                 tap_fd = open(tap_dev, TAPDEV_OFLAGS);
1009
1010                 /*
1011                  * If we cannot open normally try to connect to it.
1012                  */
1013                 if (tap_fd < 0)
1014                         tap_fd = unix_connect(tap_dev);
1015
1016                 if (tap_fd < 0) {
1017                         warn("Unable to open %s", tap_dev);
1018                         return -1;
1019                 }
1020         }
1021
1022         /*
1023          * Check whether the device file is a tap(4)
1024          */
1025         if (fstat(tap_fd, &st) < 0) {
1026                 failed = 1;
1027         } else if (S_ISCHR(st.st_mode)) {
1028                 dname = fdevname(tap_fd);
1029                 if (dname)
1030                         dname = strstr(dname, "tap");
1031                 if (dname) {
1032                         /*
1033                          * Bring up the corresponding tap(4) interface
1034                          */
1035                         *tap_unit = strtol(dname + 3, NULL, 10);
1036                         printf("TAP UNIT %d\n", *tap_unit);
1037                         if (netif_set_tapflags(*tap_unit, IFF_UP, s) == 0)
1038                                 failed = 0;
1039                         else
1040                                 failed = 1;
1041                 } else {
1042                         failed = 1;
1043                 }
1044         } else if (S_ISSOCK(st.st_mode)) {
1045                 /*
1046                  * Special socket connection (typically to vknet).  We
1047                  * do not have to do anything.
1048                  */
1049                 failed = 0;
1050         } else {
1051                 failed = 1;
1052         }
1053
1054         if (failed) {
1055                 warnx("%s is not a tap(4) device or socket", tap_dev);
1056                 close(tap_fd);
1057                 tap_fd = -1;
1058                 *tap_unit = -1;
1059         }
1060         return tap_fd;
1061 }
1062
1063 static int
1064 unix_connect(const char *path)
1065 {
1066         struct sockaddr_un sunx;
1067         int len;
1068         int net_fd;
1069         int sndbuf = 262144;
1070         struct stat st;
1071
1072         snprintf(sunx.sun_path, sizeof(sunx.sun_path), "%s", path);
1073         len = offsetof(struct sockaddr_un, sun_path[strlen(sunx.sun_path)]);
1074         ++len;  /* include nul */
1075         sunx.sun_family = AF_UNIX;
1076         sunx.sun_len = len;
1077
1078         net_fd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
1079         if (net_fd < 0)
1080                 return(-1);
1081         if (connect(net_fd, (void *)&sunx, len) < 0) {
1082                 close(net_fd);
1083                 return(-1);
1084         }
1085         setsockopt(net_fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
1086         if (fstat(net_fd, &st) == 0)
1087                 printf("Network socket buffer: %d bytes\n", st.st_blksize);
1088         fcntl(net_fd, F_SETFL, O_NONBLOCK);
1089         return(net_fd);
1090 }
1091
1092 #undef TAPDEV_MAJOR
1093 #undef TAPDEV_MINOR
1094 #undef TAPDEV_OFLAGS
1095
1096 /*
1097  * Following syntax is supported,
1098  * 1) x.x.x.x             tap(4)'s address is x.x.x.x
1099  *
1100  * 2) x.x.x.x/z           tap(4)'s address is x.x.x.x
1101  *                        tap(4)'s netmask len is z
1102  *
1103  * 3) x.x.x.x:y.y.y.y     tap(4)'s address is x.x.x.x
1104  *                        pseudo netif's address is y.y.y.y
1105  *
1106  * 4) x.x.x.x:y.y.y.y/z   tap(4)'s address is x.x.x.x
1107  *                        pseudo netif's address is y.y.y.y
1108  *                        tap(4) and pseudo netif's netmask len are z
1109  *
1110  * 5) bridgeX             tap(4) will be added to bridgeX
1111  *
1112  * 6) bridgeX:y.y.y.y     tap(4) will be added to bridgeX
1113  *                        pseudo netif's address is y.y.y.y
1114  *
1115  * 7) bridgeX:y.y.y.y/z   tap(4) will be added to bridgeX
1116  *                        pseudo netif's address is y.y.y.y
1117  *                        pseudo netif's netmask len is z
1118  */
1119 static
1120 int
1121 netif_init_tap(int tap_unit, in_addr_t *addr, in_addr_t *mask, int s)
1122 {
1123         in_addr_t tap_addr, netmask, netif_addr;
1124         int next_netif_addr;
1125         char *tok, *masklen_str, *ifbridge;
1126
1127         *addr = 0;
1128         *mask = 0;
1129
1130         tok = strtok(NULL, ":/");
1131         if (tok == NULL) {
1132                 /*
1133                  * Nothing special, simply use tap(4) as backend
1134                  */
1135                 return 0;
1136         }
1137
1138         if (inet_pton(AF_INET, tok, &tap_addr) > 0) {
1139                 /*
1140                  * tap(4)'s address is supplied
1141                  */
1142                 ifbridge = NULL;
1143
1144                 /*
1145                  * If there is next token, then it may be pseudo
1146                  * netif's address or netmask len for tap(4)
1147                  */
1148                 next_netif_addr = 0;
1149         } else {
1150                 /*
1151                  * Not tap(4)'s address, assume it as a bridge(4)
1152                  * iface name
1153                  */
1154                 tap_addr = 0;
1155                 ifbridge = tok;
1156
1157                 /*
1158                  * If there is next token, then it must be pseudo
1159                  * netif's address
1160                  */
1161                 next_netif_addr = 1;
1162         }
1163
1164         netmask = netif_addr = 0;
1165
1166         tok = strtok(NULL, ":/");
1167         if (tok == NULL)
1168                 goto back;
1169
1170         if (inet_pton(AF_INET, tok, &netif_addr) <= 0) {
1171                 if (next_netif_addr) {
1172                         warnx("Invalid pseudo netif address: %s", tok);
1173                         return -1;
1174                 }
1175                 netif_addr = 0;
1176
1177                 /*
1178                  * Current token is not address, then it must be netmask len
1179                  */
1180                 masklen_str = tok;
1181         } else {
1182                 /*
1183                  * Current token is pseudo netif address, if there is next token
1184                  * it must be netmask len
1185                  */
1186                 masklen_str = strtok(NULL, "/");
1187         }
1188
1189         /* Calculate netmask */
1190         if (masklen_str != NULL) {
1191                 u_long masklen;
1192
1193                 masklen = strtoul(masklen_str, NULL, 10);
1194                 if (masklen < 32 && masklen > 0) {
1195                         netmask = htonl(~((1LL << (32 - masklen)) - 1)
1196                                         & 0xffffffff);
1197                 } else {
1198                         warnx("Invalid netmask len: %lu", masklen);
1199                         return -1;
1200                 }
1201         }
1202
1203         /* Make sure there is no more token left */
1204         if (strtok(NULL, ":/") != NULL) {
1205                 warnx("Invalid argument to '-I'");
1206                 return -1;
1207         }
1208
1209 back:
1210         if (tap_unit < 0) {
1211                 /* Do nothing */
1212         } else if (ifbridge == NULL) {
1213                 /* Set tap(4) address/netmask */
1214                 if (netif_set_tapaddr(tap_unit, tap_addr, netmask, s) < 0)
1215                         return -1;
1216         } else {
1217                 /* Tie tap(4) to bridge(4) */
1218                 if (netif_add_tap2brg(tap_unit, ifbridge, s) < 0)
1219                         return -1;
1220         }
1221
1222         *addr = netif_addr;
1223         *mask = netmask;
1224         return 0;
1225 }
1226
1227 /*
1228  * NetifInfo[] will be filled for pseudo netif initialization.
1229  * NetifNum will be bumped to reflect the number of valid entries
1230  * in NetifInfo[].
1231  */
1232 static
1233 void
1234 init_netif(char *netifExp[], int netifExpNum)
1235 {
1236         int i, s;
1237         char *tmp;
1238
1239         if (netifExpNum == 0)
1240                 return;
1241
1242         s = socket(AF_INET, SOCK_DGRAM, 0);     /* for ioctl(SIOC) */
1243         if (s < 0)
1244                 return;
1245
1246         for (i = 0; i < netifExpNum; ++i) {
1247                 struct vknetif_info *info;
1248                 in_addr_t netif_addr, netif_mask;
1249                 int tap_fd, tap_unit;
1250                 char *netif;
1251
1252                 /* Extract MAC address if there is one */
1253                 tmp = netifExp[i];
1254                 strsep(&tmp, "=");
1255
1256                 netif = strtok(netifExp[i], ":");
1257                 if (netif == NULL) {
1258                         warnx("Invalid argument to '-I'");
1259                         continue;
1260                 }
1261
1262                 /*
1263                  * Open tap(4) device file and bring up the
1264                  * corresponding interface
1265                  */
1266                 tap_fd = netif_open_tap(netif, &tap_unit, s);
1267                 if (tap_fd < 0)
1268                         continue;
1269
1270                 /*
1271                  * Initialize tap(4) and get address/netmask
1272                  * for pseudo netif
1273                  *
1274                  * NB: Rest part of netifExp[i] is passed
1275                  *     to netif_init_tap() implicitly.
1276                  */
1277                 if (netif_init_tap(tap_unit, &netif_addr, &netif_mask, s) < 0) {
1278                         /*
1279                          * NB: Closing tap(4) device file will bring
1280                          *     down the corresponding interface
1281                          */
1282                         close(tap_fd);
1283                         continue;
1284                 }
1285
1286                 info = &NetifInfo[NetifNum];
1287                 bzero(info, sizeof(*info));
1288                 info->tap_fd = tap_fd;
1289                 info->tap_unit = tap_unit;
1290                 info->netif_addr = netif_addr;
1291                 info->netif_mask = netif_mask;
1292                 /*
1293                  * If tmp isn't NULL it means a MAC could have been
1294                  * specified so attempt to convert it.
1295                  * Setting enaddr to NULL will tell vke_attach() we
1296                  * need a pseudo-random MAC address.
1297                  */
1298                 if (tmp != NULL) {
1299                         if ((info->enaddr = malloc(ETHER_ADDR_LEN)) == NULL)
1300                                 warnx("Couldn't allocate memory for the operation");
1301                         else {
1302                                 if ((kether_aton(tmp, info->enaddr)) == NULL) {
1303                                         free(info->enaddr);
1304                                         info->enaddr = NULL;
1305                                 }
1306                         }
1307                 }
1308
1309                 NetifNum++;
1310                 if (NetifNum >= VKNETIF_MAX)    /* XXX will this happen? */
1311                         break;
1312         }
1313         close(s);
1314 }
1315
1316 /*
1317  * Create the pid file and leave it open and locked while the vkernel is
1318  * running.  This allows a script to use /usr/bin/lockf to probe whether
1319  * a vkernel is still running (so as not to accidently kill an unrelated
1320  * process from a stale pid file).
1321  */
1322 static
1323 void
1324 writepid(void)
1325 {
1326         char buf[32];
1327         int fd;
1328
1329         if (pid_file != NULL) {
1330                 snprintf(buf, sizeof(buf), "%ld\n", (long)getpid());
1331                 fd = open(pid_file, O_RDWR|O_CREAT|O_EXLOCK|O_NONBLOCK, 0666);
1332                 if (fd < 0) {
1333                         if (errno == EWOULDBLOCK) {
1334                                 perror("Failed to lock pidfile, "
1335                                        "vkernel already running");
1336                         } else {
1337                                 perror("Failed to create pidfile");
1338                         }
1339                         exit(EX_SOFTWARE);
1340                 }
1341                 ftruncate(fd, 0);
1342                 write(fd, buf, strlen(buf));
1343                 /* leave the file open to maintain the lock */
1344         }
1345 }
1346
1347 static
1348 void
1349 cleanpid( void ) 
1350 {
1351         if (pid_file != NULL) {
1352                 if (unlink(pid_file) < 0)
1353                         perror("Warning: couldn't remove pidfile");
1354         }
1355 }
1356
1357 static
1358 void
1359 usage_err(const char *ctl, ...)
1360 {
1361         va_list va;
1362
1363         va_start(va, ctl);
1364         vfprintf(stderr, ctl, va);
1365         va_end(va);
1366         fprintf(stderr, "\n");
1367         exit(EX_USAGE);
1368 }
1369
1370 static
1371 void
1372 usage_help(_Bool help)
1373 {
1374         fprintf(stderr, "Usage: %s [-hsUv] [-c file] [-e name=value:name=value:...]\n"
1375             "\t[-i file] [-I interface[:address1[:address2][/netmask]]] [-l cpulock]\n"
1376             "\t[-m size] [-n numcpus[:lbits[:cbits]]]\n"
1377             "\t[-p file] [-r file]\n", save_av[0]);
1378
1379         if (help)
1380                 fprintf(stderr, "\nArguments:\n"
1381                     "\t-c\tSpecify a readonly CD-ROM image file to be used by the kernel.\n"
1382                     "\t-e\tSpecify an environment to be used by the kernel.\n"
1383                     "\t-h\tThis list of options.\n"
1384                     "\t-i\tSpecify a memory image file to be used by the virtual kernel.\n"
1385                     "\t-I\tCreate a virtual network device.\n"
1386                     "\t-l\tSpecify which, if any, real CPUs to lock virtual CPUs to.\n"
1387                     "\t-m\tSpecify the amount of memory to be used by the kernel in bytes.\n"
1388                     "\t-n\tSpecify the number of CPUs and the topology you wish to emulate:\n"
1389                     "\t  \t- numcpus - number of cpus\n"
1390                     "\t  \t- :lbits - specify the number of bits within APICID(=CPUID) needed for representing\n"
1391                     "\t  \tthe logical ID. Controls the number of threads/core (0bits - 1 thread, 1bit - 2 threads).\n"
1392                     "\t  \t- :cbits - specify the number of bits within APICID(=CPUID) needed for representing\n"
1393                     "\t  \tthe core ID. Controls the number of core/package (0bits - 1 core, 1bit - 2 cores).\n"
1394                     "\t-p\tSpecify a file in which to store the process ID.\n"
1395                     "\t-r\tSpecify a R/W disk image file to be used by the kernel.\n"
1396                     "\t-s\tBoot into single-user mode.\n"
1397                     "\t-U\tEnable writing to kernel memory and module loading.\n"
1398                     "\t-v\tTurn on verbose booting.\n");
1399
1400         exit(EX_USAGE);
1401 }
1402
1403 void
1404 cpu_reset(void)
1405 {
1406         kprintf("cpu reset, rebooting vkernel\n");
1407         closefrom(3);
1408         cleanpid();
1409         execv(save_av[0], save_av);
1410 }
1411
1412 void
1413 cpu_halt(void)
1414 {
1415         kprintf("cpu halt, exiting vkernel\n");
1416         cleanpid();
1417         exit(EX_OK);
1418 }
1419
1420 void
1421 setrealcpu(void)
1422 {
1423         switch(lwp_cpu_lock) {
1424         case LCL_PER_CPU:
1425                 if (bootverbose)
1426                         kprintf("Locking CPU%d to real cpu %d\n",
1427                                 mycpuid, next_cpu);
1428                 usched_set(getpid(), USCHED_SET_CPU, &next_cpu, sizeof(next_cpu));
1429                 next_cpu++;
1430                 if (next_cpu >= real_ncpus)
1431                         next_cpu = 0;
1432                 break;
1433         case LCL_SINGLE_CPU:
1434                 if (bootverbose)
1435                         kprintf("Locking CPU%d to real cpu %d\n",
1436                                 mycpuid, next_cpu);
1437                 usched_set(getpid(), USCHED_SET_CPU, &next_cpu, sizeof(next_cpu));
1438                 break;
1439         default:
1440                 /* do not map virtual cpus to real cpus */
1441                 break;
1442         }
1443 }
1444