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