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