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