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