xref: /freebsd/sys/net/vnet.c (revision 2e620256bd76c449c835c604e404483437743011)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2004-2009 University of Zagreb
5  * Copyright (c) 2006-2009 FreeBSD Foundation
6  * All rights reserved.
7  *
8  * This software was developed by the University of Zagreb and the
9  * FreeBSD Foundation under sponsorship by the Stichting NLnet and the
10  * FreeBSD Foundation.
11  *
12  * Copyright (c) 2009 Jeffrey Roberson <jeff@freebsd.org>
13  * Copyright (c) 2009 Robert N. M. Watson
14  * All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #include <sys/cdefs.h>
39 #include "opt_ddb.h"
40 #include "opt_kdb.h"
41 
42 #include <sys/param.h>
43 #include <sys/kdb.h>
44 #include <sys/kernel.h>
45 #include <sys/jail.h>
46 #include <sys/sdt.h>
47 #include <sys/systm.h>
48 #include <sys/sysctl.h>
49 #include <sys/eventhandler.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/proc.h>
53 #include <sys/socket.h>
54 #include <sys/sx.h>
55 #include <sys/sysctl.h>
56 
57 #include <machine/stdarg.h>
58 
59 #ifdef DDB
60 #include <ddb/ddb.h>
61 #include <ddb/db_sym.h>
62 #endif
63 
64 #include <net/if.h>
65 #include <net/if_var.h>
66 #include <net/vnet.h>
67 
68 /*-
69  * This file implements core functions for virtual network stacks:
70  *
71  * - Virtual network stack management functions.
72  *
73  * - Virtual network stack memory allocator, which virtualizes global
74  *   variables in the network stack
75  *
76  * - Virtualized SYSINIT's/SYSUNINIT's, which allow network stack subsystems
77  *   to register startup/shutdown events to be run for each virtual network
78  *   stack instance.
79  */
80 
81 FEATURE(vimage, "VIMAGE kernel virtualization");
82 
83 static MALLOC_DEFINE(M_VNET, "vnet", "network stack control block");
84 
85 /*
86  * The virtual network stack list has two read-write locks, one sleepable and
87  * the other not, so that the list can be stablized and walked in a variety
88  * of network stack contexts.  Both must be acquired exclusively to modify
89  * the list, but a read lock of either lock is sufficient to walk the list.
90  */
91 struct rwlock		vnet_rwlock;
92 struct sx		vnet_sxlock;
93 
94 #define	VNET_LIST_WLOCK() do {						\
95 	sx_xlock(&vnet_sxlock);						\
96 	rw_wlock(&vnet_rwlock);						\
97 } while (0)
98 
99 #define	VNET_LIST_WUNLOCK() do {					\
100 	rw_wunlock(&vnet_rwlock);					\
101 	sx_xunlock(&vnet_sxlock);					\
102 } while (0)
103 
104 struct vnet_list_head vnet_head;
105 struct vnet *vnet0;
106 
107 /*
108  * The virtual network stack allocator provides storage for virtualized
109  * global variables.  These variables are defined/declared using the
110  * VNET_DEFINE()/VNET_DECLARE() macros, which place them in the 'set_vnet'
111  * linker set.  The details of the implementation are somewhat subtle, but
112  * allow the majority of most network subsystems to maintain
113  * virtualization-agnostic.
114  *
115  * The virtual network stack allocator handles variables in the base kernel
116  * vs. modules in similar but different ways.  In both cases, virtualized
117  * global variables are marked as such by being declared to be part of the
118  * vnet linker set.  These "master" copies of global variables serve two
119  * functions:
120  *
121  * (1) They contain static initialization or "default" values for global
122  *     variables which will be propagated to each virtual network stack
123  *     instance when created.  As with normal global variables, they default
124  *     to zero-filled.
125  *
126  * (2) They act as unique global names by which the variable can be referred
127  *     to, regardless of network stack instance.  The single global symbol
128  *     will be used to calculate the location of a per-virtual instance
129  *     variable at run-time.
130  *
131  * Each virtual network stack instance has a complete copy of each
132  * virtualized global variable, stored in a malloc'd block of memory
133  * referred to by vnet->vnet_data_mem.  Critical to the design is that each
134  * per-instance memory block is laid out identically to the master block so
135  * that the offset of each global variable is the same across all blocks.  To
136  * optimize run-time access, a precalculated 'base' address,
137  * vnet->vnet_data_base, is stored in each vnet, and is the amount that can
138  * be added to the address of a 'master' instance of a variable to get to the
139  * per-vnet instance.
140  *
141  * Virtualized global variables are handled in a similar manner, but as each
142  * module has its own 'set_vnet' linker set, and we want to keep all
143  * virtualized globals togther, we reserve space in the kernel's linker set
144  * for potential module variables using a per-vnet character array,
145  * 'modspace'.  The virtual network stack allocator maintains a free list to
146  * track what space in the array is free (all, initially) and as modules are
147  * linked, allocates portions of the space to specific globals.  The kernel
148  * module linker queries the virtual network stack allocator and will
149  * bind references of the global to the location during linking.  It also
150  * calls into the virtual network stack allocator, once the memory is
151  * initialized, in order to propagate the new static initializations to all
152  * existing virtual network stack instances so that the soon-to-be executing
153  * module will find every network stack instance with proper default values.
154  */
155 
156 /*
157  * Number of bytes of data in the 'set_vnet' linker set, and hence the total
158  * size of all kernel virtualized global variables, and the malloc(9) type
159  * that will be used to allocate it.
160  */
161 #define	VNET_BYTES	(VNET_STOP - VNET_START)
162 
163 static MALLOC_DEFINE(M_VNET_DATA, "vnet_data", "VNET data");
164 
165 /*
166  * VNET_MODMIN is the minimum number of bytes we will reserve for the sum of
167  * global variables across all loaded modules.  As this actually sizes an
168  * array declared as a virtualized global variable in the kernel itself, and
169  * we want the virtualized global variable space to be page-sized, we may
170  * have more space than that in practice.
171  */
172 #define	VNET_MODMIN	(8 * PAGE_SIZE)
173 #define	VNET_SIZE	roundup2(VNET_BYTES, PAGE_SIZE)
174 
175 /*
176  * Space to store virtualized global variables from loadable kernel modules,
177  * and the free list to manage it.
178  */
179 VNET_DEFINE_STATIC(char, modspace[VNET_MODMIN] __aligned(__alignof(void *)));
180 
181 /*
182  * A copy of the initial values of all virtualized global variables.
183  */
184 static uintptr_t vnet_init_var;
185 
186 /*
187  * Global lists of subsystem constructor and destructors for vnets.  They are
188  * registered via VNET_SYSINIT() and VNET_SYSUNINIT().  Both lists are
189  * protected by the vnet_sysinit_sxlock global lock.
190  */
191 static TAILQ_HEAD(vnet_sysinit_head, vnet_sysinit) vnet_constructors =
192 	TAILQ_HEAD_INITIALIZER(vnet_constructors);
193 static TAILQ_HEAD(vnet_sysuninit_head, vnet_sysinit) vnet_destructors =
194 	TAILQ_HEAD_INITIALIZER(vnet_destructors);
195 
196 struct sx		vnet_sysinit_sxlock;
197 
198 #define	VNET_SYSINIT_WLOCK()	sx_xlock(&vnet_sysinit_sxlock);
199 #define	VNET_SYSINIT_WUNLOCK()	sx_xunlock(&vnet_sysinit_sxlock);
200 #define	VNET_SYSINIT_RLOCK()	sx_slock(&vnet_sysinit_sxlock);
201 #define	VNET_SYSINIT_RUNLOCK()	sx_sunlock(&vnet_sysinit_sxlock);
202 
203 struct vnet_data_free {
204 	uintptr_t	vnd_start;
205 	int		vnd_len;
206 	TAILQ_ENTRY(vnet_data_free) vnd_link;
207 };
208 
209 static MALLOC_DEFINE(M_VNET_DATA_FREE, "vnet_data_free",
210     "VNET resource accounting");
211 static TAILQ_HEAD(, vnet_data_free) vnet_data_free_head =
212 	    TAILQ_HEAD_INITIALIZER(vnet_data_free_head);
213 static struct sx vnet_data_free_lock;
214 
215 SDT_PROVIDER_DEFINE(vnet);
216 SDT_PROBE_DEFINE1(vnet, functions, vnet_alloc, entry, "int");
217 SDT_PROBE_DEFINE2(vnet, functions, vnet_alloc, alloc, "int",
218     "struct vnet *");
219 SDT_PROBE_DEFINE2(vnet, functions, vnet_alloc, return,
220     "int", "struct vnet *");
221 SDT_PROBE_DEFINE2(vnet, functions, vnet_destroy, entry,
222     "int", "struct vnet *");
223 SDT_PROBE_DEFINE1(vnet, functions, vnet_destroy, return,
224     "int");
225 
226 /*
227  * Run per-vnet sysinits or sysuninits during vnet creation/destruction.
228  */
229 static void vnet_sysinit(void);
230 static void vnet_sysuninit(void);
231 
232 #ifdef DDB
233 static void db_show_vnet_print_vs(struct vnet_sysinit *, int);
234 #endif
235 
236 /*
237  * Allocate a virtual network stack.
238  */
239 struct vnet *
240 vnet_alloc(void)
241 {
242 	struct vnet *vnet;
243 
244 	SDT_PROBE1(vnet, functions, vnet_alloc, entry, __LINE__);
245 	vnet = malloc(sizeof(struct vnet), M_VNET, M_WAITOK | M_ZERO);
246 	vnet->vnet_magic_n = VNET_MAGIC_N;
247 	SDT_PROBE2(vnet, functions, vnet_alloc, alloc, __LINE__, vnet);
248 
249 	/*
250 	 * Allocate storage for virtualized global variables and copy in
251 	 * initial values from our 'master' copy.
252 	 */
253 	vnet->vnet_data_mem = malloc(VNET_SIZE, M_VNET_DATA, M_WAITOK);
254 	memcpy(vnet->vnet_data_mem, (void *)VNET_START, VNET_BYTES);
255 
256 	/*
257 	 * All use of vnet-specific data will immediately subtract VNET_START
258 	 * from the base memory pointer, so pre-calculate that now to avoid
259 	 * it on each use.
260 	 */
261 	vnet->vnet_data_base = (uintptr_t)vnet->vnet_data_mem - VNET_START;
262 
263 	/* Initialize / attach vnet module instances. */
264 	CURVNET_SET_QUIET(vnet);
265 	vnet_sysinit();
266 	CURVNET_RESTORE();
267 
268 	VNET_LIST_WLOCK();
269 	LIST_INSERT_HEAD(&vnet_head, vnet, vnet_le);
270 	VNET_LIST_WUNLOCK();
271 
272 	SDT_PROBE2(vnet, functions, vnet_alloc, return, __LINE__, vnet);
273 	return (vnet);
274 }
275 
276 /*
277  * Destroy a virtual network stack.
278  */
279 void
280 vnet_destroy(struct vnet *vnet)
281 {
282 
283 	SDT_PROBE2(vnet, functions, vnet_destroy, entry, __LINE__, vnet);
284 	KASSERT(vnet->vnet_sockcnt == 0,
285 	    ("%s: vnet still has sockets", __func__));
286 
287 	VNET_LIST_WLOCK();
288 	LIST_REMOVE(vnet, vnet_le);
289 	VNET_LIST_WUNLOCK();
290 
291 	/* Signal that VNET is being shutdown. */
292 	vnet->vnet_shutdown = true;
293 
294 	CURVNET_SET_QUIET(vnet);
295 	sx_xlock(&ifnet_detach_sxlock);
296 	vnet_sysuninit();
297 	sx_xunlock(&ifnet_detach_sxlock);
298 	CURVNET_RESTORE();
299 
300 	/*
301 	 * Release storage for the virtual network stack instance.
302 	 */
303 	free(vnet->vnet_data_mem, M_VNET_DATA);
304 	vnet->vnet_data_mem = NULL;
305 	vnet->vnet_data_base = 0;
306 	vnet->vnet_magic_n = 0xdeadbeef;
307 	free(vnet, M_VNET);
308 	SDT_PROBE1(vnet, functions, vnet_destroy, return, __LINE__);
309 }
310 
311 /*
312  * Boot time initialization and allocation of virtual network stacks.
313  */
314 static void
315 vnet_init_prelink(void *arg __unused)
316 {
317 
318 	rw_init(&vnet_rwlock, "vnet_rwlock");
319 	sx_init(&vnet_sxlock, "vnet_sxlock");
320 	sx_init(&vnet_sysinit_sxlock, "vnet_sysinit_sxlock");
321 	LIST_INIT(&vnet_head);
322 }
323 SYSINIT(vnet_init_prelink, SI_SUB_VNET_PRELINK, SI_ORDER_FIRST,
324     vnet_init_prelink, NULL);
325 
326 static void
327 vnet0_init(void *arg __unused)
328 {
329 
330 	if (bootverbose)
331 		printf("VIMAGE (virtualized network stack) enabled\n");
332 
333 	/*
334 	 * We MUST clear curvnet in vi_init_done() before going SMP,
335 	 * otherwise CURVNET_SET() macros would scream about unnecessary
336 	 * curvnet recursions.
337 	 */
338 	curvnet = prison0.pr_vnet = vnet0 = vnet_alloc();
339 }
340 SYSINIT(vnet0_init, SI_SUB_VNET, SI_ORDER_FIRST, vnet0_init, NULL);
341 
342 static void
343 vnet_init_done(void *unused __unused)
344 {
345 
346 	curvnet = NULL;
347 }
348 SYSINIT(vnet_init_done, SI_SUB_VNET_DONE, SI_ORDER_ANY, vnet_init_done,
349     NULL);
350 
351 /*
352  * Once on boot, initialize the modspace freelist to entirely cover modspace.
353  */
354 static void
355 vnet_data_startup(void *dummy __unused)
356 {
357 	struct vnet_data_free *df;
358 
359 	df = malloc(sizeof(*df), M_VNET_DATA_FREE, M_WAITOK | M_ZERO);
360 	df->vnd_start = (uintptr_t)&VNET_NAME(modspace);
361 	df->vnd_len = VNET_MODMIN;
362 	TAILQ_INSERT_HEAD(&vnet_data_free_head, df, vnd_link);
363 	sx_init(&vnet_data_free_lock, "vnet_data alloc lock");
364 	vnet_init_var = (uintptr_t)malloc(VNET_BYTES, M_VNET_DATA, M_WAITOK);
365 }
366 SYSINIT(vnet_data, SI_SUB_KLD, SI_ORDER_FIRST, vnet_data_startup, NULL);
367 
368 /* Dummy VNET_SYSINIT to make sure we always reach the final end state. */
369 static void
370 vnet_sysinit_done(void *unused __unused)
371 {
372 
373 	return;
374 }
375 VNET_SYSINIT(vnet_sysinit_done, SI_SUB_VNET_DONE, SI_ORDER_ANY,
376     vnet_sysinit_done, NULL);
377 
378 /*
379  * When a module is loaded and requires storage for a virtualized global
380  * variable, allocate space from the modspace free list.  This interface
381  * should be used only by the kernel linker.
382  */
383 void *
384 vnet_data_alloc(int size)
385 {
386 	struct vnet_data_free *df;
387 	void *s;
388 
389 	s = NULL;
390 	size = roundup2(size, sizeof(void *));
391 	sx_xlock(&vnet_data_free_lock);
392 	TAILQ_FOREACH(df, &vnet_data_free_head, vnd_link) {
393 		if (df->vnd_len < size)
394 			continue;
395 		if (df->vnd_len == size) {
396 			s = (void *)df->vnd_start;
397 			TAILQ_REMOVE(&vnet_data_free_head, df, vnd_link);
398 			free(df, M_VNET_DATA_FREE);
399 			break;
400 		}
401 		s = (void *)df->vnd_start;
402 		df->vnd_len -= size;
403 		df->vnd_start = df->vnd_start + size;
404 		break;
405 	}
406 	sx_xunlock(&vnet_data_free_lock);
407 
408 	return (s);
409 }
410 
411 /*
412  * Free space for a virtualized global variable on module unload.
413  */
414 void
415 vnet_data_free(void *start_arg, int size)
416 {
417 	struct vnet_data_free *df;
418 	struct vnet_data_free *dn;
419 	uintptr_t start;
420 	uintptr_t end;
421 
422 	size = roundup2(size, sizeof(void *));
423 	start = (uintptr_t)start_arg;
424 	end = start + size;
425 	/*
426 	 * Free a region of space and merge it with as many neighbors as
427 	 * possible.  Keeping the list sorted simplifies this operation.
428 	 */
429 	sx_xlock(&vnet_data_free_lock);
430 	TAILQ_FOREACH(df, &vnet_data_free_head, vnd_link) {
431 		if (df->vnd_start > end)
432 			break;
433 		/*
434 		 * If we expand at the end of an entry we may have to merge
435 		 * it with the one following it as well.
436 		 */
437 		if (df->vnd_start + df->vnd_len == start) {
438 			df->vnd_len += size;
439 			dn = TAILQ_NEXT(df, vnd_link);
440 			if (df->vnd_start + df->vnd_len == dn->vnd_start) {
441 				df->vnd_len += dn->vnd_len;
442 				TAILQ_REMOVE(&vnet_data_free_head, dn,
443 				    vnd_link);
444 				free(dn, M_VNET_DATA_FREE);
445 			}
446 			sx_xunlock(&vnet_data_free_lock);
447 			return;
448 		}
449 		if (df->vnd_start == end) {
450 			df->vnd_start = start;
451 			df->vnd_len += size;
452 			sx_xunlock(&vnet_data_free_lock);
453 			return;
454 		}
455 	}
456 	dn = malloc(sizeof(*df), M_VNET_DATA_FREE, M_WAITOK | M_ZERO);
457 	dn->vnd_start = start;
458 	dn->vnd_len = size;
459 	if (df)
460 		TAILQ_INSERT_BEFORE(df, dn, vnd_link);
461 	else
462 		TAILQ_INSERT_TAIL(&vnet_data_free_head, dn, vnd_link);
463 	sx_xunlock(&vnet_data_free_lock);
464 }
465 
466 /*
467  * When a new virtualized global variable has been allocated, propagate its
468  * initial value to each already-allocated virtual network stack instance.
469  */
470 void
471 vnet_data_copy(void *start, int size)
472 {
473 	struct vnet *vnet;
474 
475 	VNET_LIST_RLOCK();
476 	LIST_FOREACH(vnet, &vnet_head, vnet_le)
477 		memcpy((void *)((uintptr_t)vnet->vnet_data_base +
478 		    (uintptr_t)start), start, size);
479 	VNET_LIST_RUNLOCK();
480 }
481 
482 /*
483  * Save a copy of the initial values of virtualized global variables.
484  */
485 void
486 vnet_save_init(void *start, size_t size)
487 {
488 	MPASS(vnet_init_var != 0);
489 	MPASS(VNET_START <= (uintptr_t)start &&
490 	    (uintptr_t)start + size <= VNET_STOP);
491 	memcpy((void *)(vnet_init_var + ((uintptr_t)start - VNET_START)),
492 	    start, size);
493 }
494 
495 /*
496  * Restore the 'master' copies of virtualized global variables to theirs
497  * initial values.
498  */
499 void
500 vnet_restore_init(void *start, size_t size)
501 {
502 	MPASS(vnet_init_var != 0);
503 	MPASS(VNET_START <= (uintptr_t)start &&
504 	    (uintptr_t)start + size <= VNET_STOP);
505 	memcpy(start,
506 	    (void *)(vnet_init_var + ((uintptr_t)start - VNET_START)), size);
507 }
508 
509 /*
510  * Support for special SYSINIT handlers registered via VNET_SYSINIT()
511  * and VNET_SYSUNINIT().
512  */
513 void
514 vnet_register_sysinit(void *arg)
515 {
516 	struct vnet_sysinit *vs, *vs2;
517 	struct vnet *vnet;
518 
519 	vs = arg;
520 	KASSERT(vs->subsystem > SI_SUB_VNET, ("vnet sysinit too early"));
521 
522 	/* Add the constructor to the global list of vnet constructors. */
523 	VNET_SYSINIT_WLOCK();
524 	TAILQ_FOREACH(vs2, &vnet_constructors, link) {
525 		if (vs2->subsystem > vs->subsystem)
526 			break;
527 		if (vs2->subsystem == vs->subsystem && vs2->order > vs->order)
528 			break;
529 	}
530 	if (vs2 != NULL)
531 		TAILQ_INSERT_BEFORE(vs2, vs, link);
532 	else
533 		TAILQ_INSERT_TAIL(&vnet_constructors, vs, link);
534 
535 	/*
536 	 * Invoke the constructor on all the existing vnets when it is
537 	 * registered.
538 	 */
539 	VNET_FOREACH(vnet) {
540 		CURVNET_SET_QUIET(vnet);
541 		vs->func(vs->arg);
542 		CURVNET_RESTORE();
543 	}
544 	VNET_SYSINIT_WUNLOCK();
545 }
546 
547 void
548 vnet_deregister_sysinit(void *arg)
549 {
550 	struct vnet_sysinit *vs;
551 
552 	vs = arg;
553 
554 	/* Remove the constructor from the global list of vnet constructors. */
555 	VNET_SYSINIT_WLOCK();
556 	TAILQ_REMOVE(&vnet_constructors, vs, link);
557 	VNET_SYSINIT_WUNLOCK();
558 }
559 
560 void
561 vnet_register_sysuninit(void *arg)
562 {
563 	struct vnet_sysinit *vs, *vs2;
564 
565 	vs = arg;
566 
567 	/* Add the destructor to the global list of vnet destructors. */
568 	VNET_SYSINIT_WLOCK();
569 	TAILQ_FOREACH(vs2, &vnet_destructors, link) {
570 		if (vs2->subsystem > vs->subsystem)
571 			break;
572 		if (vs2->subsystem == vs->subsystem && vs2->order > vs->order)
573 			break;
574 	}
575 	if (vs2 != NULL)
576 		TAILQ_INSERT_BEFORE(vs2, vs, link);
577 	else
578 		TAILQ_INSERT_TAIL(&vnet_destructors, vs, link);
579 	VNET_SYSINIT_WUNLOCK();
580 }
581 
582 void
583 vnet_deregister_sysuninit(void *arg)
584 {
585 	struct vnet_sysinit *vs;
586 	struct vnet *vnet;
587 
588 	vs = arg;
589 
590 	/*
591 	 * Invoke the destructor on all the existing vnets when it is
592 	 * deregistered.
593 	 */
594 	VNET_SYSINIT_WLOCK();
595 	VNET_FOREACH(vnet) {
596 		CURVNET_SET_QUIET(vnet);
597 		vs->func(vs->arg);
598 		CURVNET_RESTORE();
599 	}
600 
601 	/* Remove the destructor from the global list of vnet destructors. */
602 	TAILQ_REMOVE(&vnet_destructors, vs, link);
603 	VNET_SYSINIT_WUNLOCK();
604 }
605 
606 /*
607  * Invoke all registered vnet constructors on the current vnet.  Used during
608  * vnet construction.  The caller is responsible for ensuring the new vnet is
609  * the current vnet and that the vnet_sysinit_sxlock lock is locked.
610  */
611 static void
612 vnet_sysinit(void)
613 {
614 	struct vnet_sysinit *vs;
615 
616 	VNET_SYSINIT_RLOCK();
617 	TAILQ_FOREACH(vs, &vnet_constructors, link) {
618 		curvnet->vnet_state = vs->subsystem;
619 		vs->func(vs->arg);
620 	}
621 	VNET_SYSINIT_RUNLOCK();
622 }
623 
624 /*
625  * Invoke all registered vnet destructors on the current vnet.  Used during
626  * vnet destruction.  The caller is responsible for ensuring the dying vnet
627  * the current vnet and that the vnet_sysinit_sxlock lock is locked.
628  */
629 static void
630 vnet_sysuninit(void)
631 {
632 	struct vnet_sysinit *vs;
633 
634 	VNET_SYSINIT_RLOCK();
635 	TAILQ_FOREACH_REVERSE(vs, &vnet_destructors, vnet_sysuninit_head,
636 	    link) {
637 		curvnet->vnet_state = vs->subsystem;
638 		vs->func(vs->arg);
639 	}
640 	VNET_SYSINIT_RUNLOCK();
641 }
642 
643 /*
644  * EVENTHANDLER(9) extensions.
645  */
646 /*
647  * Invoke the eventhandler function originally registered with the possibly
648  * registered argument for all virtual network stack instances.
649  *
650  * This iterator can only be used for eventhandlers that do not take any
651  * additional arguments, as we do ignore the variadic arguments from the
652  * EVENTHANDLER_INVOKE() call.
653  */
654 void
655 vnet_global_eventhandler_iterator_func(void *arg, ...)
656 {
657 	VNET_ITERATOR_DECL(vnet_iter);
658 	struct eventhandler_entry_vimage *v_ee;
659 
660 	/*
661 	 * There is a bug here in that we should actually cast things to
662 	 * (struct eventhandler_entry_ ## name *)  but that's not easily
663 	 * possible in here so just re-using the variadic version we
664 	 * defined for the generic vimage case.
665 	 */
666 	v_ee = arg;
667 	VNET_LIST_RLOCK();
668 	VNET_FOREACH(vnet_iter) {
669 		CURVNET_SET(vnet_iter);
670 		((vimage_iterator_func_t)v_ee->func)(v_ee->ee_arg);
671 		CURVNET_RESTORE();
672 	}
673 	VNET_LIST_RUNLOCK();
674 }
675 
676 #ifdef VNET_DEBUG
677 struct vnet_recursion {
678 	SLIST_ENTRY(vnet_recursion)	 vnr_le;
679 	const char			*prev_fn;
680 	const char			*where_fn;
681 	int				 where_line;
682 	struct vnet			*old_vnet;
683 	struct vnet			*new_vnet;
684 };
685 
686 static SLIST_HEAD(, vnet_recursion) vnet_recursions =
687     SLIST_HEAD_INITIALIZER(vnet_recursions);
688 
689 static void
690 vnet_print_recursion(struct vnet_recursion *vnr, int brief)
691 {
692 
693 	if (!brief)
694 		printf("CURVNET_SET() recursion in ");
695 	printf("%s() line %d, prev in %s()", vnr->where_fn, vnr->where_line,
696 	    vnr->prev_fn);
697 	if (brief)
698 		printf(", ");
699 	else
700 		printf("\n    ");
701 	printf("%p -> %p\n", vnr->old_vnet, vnr->new_vnet);
702 }
703 
704 void
705 vnet_log_recursion(struct vnet *old_vnet, const char *old_fn, int line)
706 {
707 	struct vnet_recursion *vnr;
708 
709 	/* Skip already logged recursion events. */
710 	SLIST_FOREACH(vnr, &vnet_recursions, vnr_le)
711 		if (vnr->prev_fn == old_fn &&
712 		    vnr->where_fn == curthread->td_vnet_lpush &&
713 		    vnr->where_line == line &&
714 		    (vnr->old_vnet == vnr->new_vnet) == (curvnet == old_vnet))
715 			return;
716 
717 	vnr = malloc(sizeof(*vnr), M_VNET, M_NOWAIT | M_ZERO);
718 	if (vnr == NULL)
719 		panic("%s: malloc failed", __func__);
720 	vnr->prev_fn = old_fn;
721 	vnr->where_fn = curthread->td_vnet_lpush;
722 	vnr->where_line = line;
723 	vnr->old_vnet = old_vnet;
724 	vnr->new_vnet = curvnet;
725 
726 	SLIST_INSERT_HEAD(&vnet_recursions, vnr, vnr_le);
727 
728 	vnet_print_recursion(vnr, 0);
729 #ifdef KDB
730 	kdb_backtrace();
731 #endif
732 }
733 #endif /* VNET_DEBUG */
734 
735 /*
736  * DDB(4).
737  */
738 #ifdef DDB
739 static void
740 db_vnet_print(struct vnet *vnet)
741 {
742 
743 	db_printf("vnet            = %p\n", vnet);
744 	db_printf(" vnet_magic_n   = %#08x (%s, orig %#08x)\n",
745 	    vnet->vnet_magic_n,
746 	    (vnet->vnet_magic_n == VNET_MAGIC_N) ?
747 		"ok" : "mismatch", VNET_MAGIC_N);
748 	db_printf(" vnet_ifcnt     = %u\n", vnet->vnet_ifcnt);
749 	db_printf(" vnet_sockcnt   = %u\n", vnet->vnet_sockcnt);
750 	db_printf(" vnet_data_mem  = %p\n", vnet->vnet_data_mem);
751 	db_printf(" vnet_data_base = %#jx\n",
752 	    (uintmax_t)vnet->vnet_data_base);
753 	db_printf(" vnet_state     = %#08x\n", vnet->vnet_state);
754 	db_printf(" vnet_shutdown  = %#03x\n", vnet->vnet_shutdown);
755 	db_printf("\n");
756 }
757 
758 DB_SHOW_ALL_COMMAND(vnets, db_show_all_vnets)
759 {
760 	VNET_ITERATOR_DECL(vnet_iter);
761 
762 	VNET_FOREACH(vnet_iter) {
763 		db_vnet_print(vnet_iter);
764 		if (db_pager_quit)
765 			break;
766 	}
767 }
768 
769 DB_SHOW_COMMAND(vnet, db_show_vnet)
770 {
771 
772 	if (!have_addr) {
773 		db_printf("usage: show vnet <struct vnet *>\n");
774 		return;
775 	}
776 
777 	db_vnet_print((struct vnet *)addr);
778 }
779 
780 static void
781 db_show_vnet_print_vs(struct vnet_sysinit *vs, int ddb)
782 {
783 	const char *vsname, *funcname;
784 	c_db_sym_t sym;
785 	db_expr_t  offset;
786 
787 #define xprint(...)							\
788 	if (ddb)							\
789 		db_printf(__VA_ARGS__);					\
790 	else								\
791 		printf(__VA_ARGS__)
792 
793 	if (vs == NULL) {
794 		xprint("%s: no vnet_sysinit * given\n", __func__);
795 		return;
796 	}
797 
798 	sym = db_search_symbol((vm_offset_t)vs, DB_STGY_ANY, &offset);
799 	db_symbol_values(sym, &vsname, NULL);
800 	sym = db_search_symbol((vm_offset_t)vs->func, DB_STGY_PROC, &offset);
801 	db_symbol_values(sym, &funcname, NULL);
802 	xprint("%s(%p)\n", (vsname != NULL) ? vsname : "", vs);
803 	xprint("  %#08x %#08x\n", vs->subsystem, vs->order);
804 	xprint("  %p(%s)(%p)\n",
805 	    vs->func, (funcname != NULL) ? funcname : "", vs->arg);
806 #undef xprint
807 }
808 
809 DB_SHOW_COMMAND_FLAGS(vnet_sysinit, db_show_vnet_sysinit, DB_CMD_MEMSAFE)
810 {
811 	struct vnet_sysinit *vs;
812 
813 	db_printf("VNET_SYSINIT vs Name(Ptr)\n");
814 	db_printf("  Subsystem  Order\n");
815 	db_printf("  Function(Name)(Arg)\n");
816 	TAILQ_FOREACH(vs, &vnet_constructors, link) {
817 		db_show_vnet_print_vs(vs, 1);
818 		if (db_pager_quit)
819 			break;
820 	}
821 }
822 
823 DB_SHOW_COMMAND_FLAGS(vnet_sysuninit, db_show_vnet_sysuninit, DB_CMD_MEMSAFE)
824 {
825 	struct vnet_sysinit *vs;
826 
827 	db_printf("VNET_SYSUNINIT vs Name(Ptr)\n");
828 	db_printf("  Subsystem  Order\n");
829 	db_printf("  Function(Name)(Arg)\n");
830 	TAILQ_FOREACH_REVERSE(vs, &vnet_destructors, vnet_sysuninit_head,
831 	    link) {
832 		db_show_vnet_print_vs(vs, 1);
833 		if (db_pager_quit)
834 			break;
835 	}
836 }
837 
838 #ifdef VNET_DEBUG
839 DB_SHOW_COMMAND_FLAGS(vnetrcrs, db_show_vnetrcrs, DB_CMD_MEMSAFE)
840 {
841 	struct vnet_recursion *vnr;
842 
843 	SLIST_FOREACH(vnr, &vnet_recursions, vnr_le)
844 		vnet_print_recursion(vnr, 1);
845 }
846 #endif
847 #endif /* DDB */
848