xref: /freebsd/sys/net/if_tuntap.c (revision ae41709ab46305df80f7f35bb478a3c8ebf22ebb)
1 /*	$NetBSD: if_tun.c,v 1.14 1994/06/29 06:36:25 cgd Exp $	*/
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4  *
5  * Copyright (C) 1999-2000 by Maksim Yevmenkin <m_evmenkin@yahoo.com>
6  * All rights reserved.
7  * Copyright (c) 2019 Kyle Evans <kevans@FreeBSD.org>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * BASED ON:
32  * -------------------------------------------------------------------------
33  *
34  * Copyright (c) 1988, Julian Onions <jpo@cs.nott.ac.uk>
35  * Nottingham University 1987.
36  *
37  * This source may be freely distributed, however I would be interested
38  * in any changes that are made.
39  *
40  * This driver takes packets off the IP i/f and hands them up to a
41  * user process to have its wicked way with. This driver has it's
42  * roots in a similar driver written by Phil Cockcroft (formerly) at
43  * UCL. This driver is based much more on read/write/poll mode of
44  * operation though.
45  *
46  * $FreeBSD$
47  */
48 
49 #include "opt_inet.h"
50 #include "opt_inet6.h"
51 
52 #include <sys/param.h>
53 #include <sys/lock.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/systm.h>
57 #include <sys/jail.h>
58 #include <sys/mbuf.h>
59 #include <sys/module.h>
60 #include <sys/socket.h>
61 #include <sys/eventhandler.h>
62 #include <sys/fcntl.h>
63 #include <sys/filio.h>
64 #include <sys/sockio.h>
65 #include <sys/sx.h>
66 #include <sys/syslog.h>
67 #include <sys/ttycom.h>
68 #include <sys/poll.h>
69 #include <sys/selinfo.h>
70 #include <sys/signalvar.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
74 #include <sys/conf.h>
75 #include <sys/uio.h>
76 #include <sys/malloc.h>
77 #include <sys/random.h>
78 #include <sys/ctype.h>
79 
80 #include <net/ethernet.h>
81 #include <net/if.h>
82 #include <net/if_var.h>
83 #include <net/if_clone.h>
84 #include <net/if_dl.h>
85 #include <net/if_media.h>
86 #include <net/if_types.h>
87 #include <net/if_vlan_var.h>
88 #include <net/netisr.h>
89 #include <net/route.h>
90 #include <net/vnet.h>
91 #include <netinet/in.h>
92 #ifdef INET
93 #include <netinet/ip.h>
94 #endif
95 #ifdef INET6
96 #include <netinet/ip6.h>
97 #include <netinet6/ip6_var.h>
98 #endif
99 #include <netinet/udp.h>
100 #include <netinet/tcp.h>
101 #include <net/bpf.h>
102 #include <net/if_tap.h>
103 #include <net/if_tun.h>
104 
105 #include <dev/virtio/network/virtio_net.h>
106 
107 #include <sys/queue.h>
108 #include <sys/condvar.h>
109 #include <security/mac/mac_framework.h>
110 
111 struct tuntap_driver;
112 
113 /*
114  * tun_list is protected by global tunmtx.  Other mutable fields are
115  * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
116  * static for the duration of a tunnel interface.
117  */
118 struct tuntap_softc {
119 	TAILQ_ENTRY(tuntap_softc)	 tun_list;
120 	struct cdev			*tun_alias;
121 	struct cdev			*tun_dev;
122 	u_short				 tun_flags;	/* misc flags */
123 #define	TUN_OPEN	0x0001
124 #define	TUN_INITED	0x0002
125 #define	TUN_UNUSED1	0x0008
126 #define	TUN_DSTADDR	0x0010
127 #define	TUN_LMODE	0x0020
128 #define	TUN_RWAIT	0x0040
129 #define	TUN_ASYNC	0x0080
130 #define	TUN_IFHEAD	0x0100
131 #define	TUN_DYING	0x0200
132 #define	TUN_L2		0x0400
133 #define	TUN_VMNET	0x0800
134 
135 #define	TUN_DRIVER_IDENT_MASK	(TUN_L2 | TUN_VMNET)
136 #define	TUN_READY		(TUN_OPEN | TUN_INITED)
137 
138 	pid_t			 tun_pid;	/* owning pid */
139 	struct ifnet		*tun_ifp;	/* the interface */
140 	struct sigio		*tun_sigio;	/* async I/O info */
141 	struct tuntap_driver	*tun_drv;	/* appropriate driver */
142 	struct selinfo		 tun_rsel;	/* read select */
143 	struct mtx		 tun_mtx;	/* softc field mutex */
144 	struct cv		 tun_cv;	/* for ref'd dev destroy */
145 	struct ether_addr	 tun_ether;	/* remote address */
146 	int			 tun_busy;	/* busy count */
147 	int			 tun_vhdrlen;	/* virtio-net header length */
148 };
149 #define	TUN2IFP(sc)	((sc)->tun_ifp)
150 
151 #define	TUNDEBUG	if (tundebug) if_printf
152 
153 #define	TUN_LOCK(tp)		mtx_lock(&(tp)->tun_mtx)
154 #define	TUN_UNLOCK(tp)		mtx_unlock(&(tp)->tun_mtx)
155 #define	TUN_LOCK_ASSERT(tp)	mtx_assert(&(tp)->tun_mtx, MA_OWNED);
156 
157 #define	TUN_VMIO_FLAG_MASK	0x0fff
158 
159 /*
160  * Interface capabilities of a tap device that supports the virtio-net
161  * header.
162  */
163 #define TAP_VNET_HDR_CAPS	(IFCAP_HWCSUM | IFCAP_HWCSUM_IPV6	\
164 				| IFCAP_VLAN_HWCSUM			\
165 				| IFCAP_TSO | IFCAP_LRO			\
166 				| IFCAP_VLAN_HWTSO)
167 
168 #define TAP_ALL_OFFLOAD		(CSUM_TSO | CSUM_TCP | CSUM_UDP |\
169 				    CSUM_TCP_IPV6 | CSUM_UDP_IPV6)
170 
171 /*
172  * All mutable global variables in if_tun are locked using tunmtx, with
173  * the exception of tundebug, which is used unlocked, and the drivers' *clones,
174  * which are static after setup.
175  */
176 static struct mtx tunmtx;
177 static eventhandler_tag arrival_tag;
178 static eventhandler_tag clone_tag;
179 static const char tunname[] = "tun";
180 static const char tapname[] = "tap";
181 static const char vmnetname[] = "vmnet";
182 static MALLOC_DEFINE(M_TUN, tunname, "Tunnel Interface");
183 static int tundebug = 0;
184 static int tundclone = 1;
185 static int tap_allow_uopen = 0;	/* allow user devfs cloning */
186 static int tapuponopen = 0;	/* IFF_UP on open() */
187 static int tapdclone = 1;	/* enable devfs cloning */
188 
189 static TAILQ_HEAD(,tuntap_softc)	tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
190 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
191 
192 static struct sx tun_ioctl_sx;
193 SX_SYSINIT(tun_ioctl_sx, &tun_ioctl_sx, "tun_ioctl");
194 
195 SYSCTL_DECL(_net_link);
196 /* tun */
197 static SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
198     "IP tunnel software network interface");
199 SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tundclone, 0,
200     "Enable legacy devfs interface creation");
201 
202 /* tap */
203 static SYSCTL_NODE(_net_link, OID_AUTO, tap, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
204     "Ethernet tunnel software network interface");
205 SYSCTL_INT(_net_link_tap, OID_AUTO, user_open, CTLFLAG_RW, &tap_allow_uopen, 0,
206     "Enable legacy devfs interface creation for all users");
207 SYSCTL_INT(_net_link_tap, OID_AUTO, up_on_open, CTLFLAG_RW, &tapuponopen, 0,
208     "Bring interface up when /dev/tap is opened");
209 SYSCTL_INT(_net_link_tap, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tapdclone, 0,
210     "Enable legacy devfs interface creation");
211 SYSCTL_INT(_net_link_tap, OID_AUTO, debug, CTLFLAG_RW, &tundebug, 0, "");
212 
213 static int	tun_create_device(struct tuntap_driver *drv, int unit,
214     struct ucred *cr, struct cdev **dev, const char *name);
215 static int	tun_busy_locked(struct tuntap_softc *tp);
216 static void	tun_unbusy_locked(struct tuntap_softc *tp);
217 static int	tun_busy(struct tuntap_softc *tp);
218 static void	tun_unbusy(struct tuntap_softc *tp);
219 
220 static int	tuntap_name2info(const char *name, int *unit, int *flags);
221 static void	tunclone(void *arg, struct ucred *cred, char *name,
222 		    int namelen, struct cdev **dev);
223 static void	tuncreate(struct cdev *dev);
224 static void	tundtor(void *data);
225 static void	tunrename(void *arg, struct ifnet *ifp);
226 static int	tunifioctl(struct ifnet *, u_long, caddr_t);
227 static void	tuninit(struct ifnet *);
228 static void	tunifinit(void *xtp);
229 static int	tuntapmodevent(module_t, int, void *);
230 static int	tunoutput(struct ifnet *, struct mbuf *,
231 		    const struct sockaddr *, struct route *ro);
232 static void	tunstart(struct ifnet *);
233 static void	tunstart_l2(struct ifnet *);
234 
235 static int	tun_clone_match(struct if_clone *ifc, const char *name);
236 static int	tap_clone_match(struct if_clone *ifc, const char *name);
237 static int	vmnet_clone_match(struct if_clone *ifc, const char *name);
238 static int	tun_clone_create(struct if_clone *, char *, size_t, caddr_t);
239 static int	tun_clone_destroy(struct if_clone *, struct ifnet *);
240 static void	tun_vnethdr_set(struct ifnet *ifp, int vhdrlen);
241 
242 static d_open_t		tunopen;
243 static d_read_t		tunread;
244 static d_write_t	tunwrite;
245 static d_ioctl_t	tunioctl;
246 static d_poll_t		tunpoll;
247 static d_kqfilter_t	tunkqfilter;
248 
249 static int		tunkqread(struct knote *, long);
250 static int		tunkqwrite(struct knote *, long);
251 static void		tunkqdetach(struct knote *);
252 
253 static struct filterops tun_read_filterops = {
254 	.f_isfd =	1,
255 	.f_attach =	NULL,
256 	.f_detach =	tunkqdetach,
257 	.f_event =	tunkqread,
258 };
259 
260 static struct filterops tun_write_filterops = {
261 	.f_isfd =	1,
262 	.f_attach =	NULL,
263 	.f_detach =	tunkqdetach,
264 	.f_event =	tunkqwrite,
265 };
266 
267 static struct tuntap_driver {
268 	struct cdevsw		 cdevsw;
269 	int			 ident_flags;
270 	struct unrhdr		*unrhdr;
271 	struct clonedevs	*clones;
272 	ifc_match_t		*clone_match_fn;
273 	ifc_create_t		*clone_create_fn;
274 	ifc_destroy_t		*clone_destroy_fn;
275 } tuntap_drivers[] = {
276 	{
277 		.ident_flags =	0,
278 		.cdevsw =	{
279 		    .d_version =	D_VERSION,
280 		    .d_flags =		D_NEEDMINOR,
281 		    .d_open =		tunopen,
282 		    .d_read =		tunread,
283 		    .d_write =		tunwrite,
284 		    .d_ioctl =		tunioctl,
285 		    .d_poll =		tunpoll,
286 		    .d_kqfilter =	tunkqfilter,
287 		    .d_name =		tunname,
288 		},
289 		.clone_match_fn =	tun_clone_match,
290 		.clone_create_fn =	tun_clone_create,
291 		.clone_destroy_fn =	tun_clone_destroy,
292 	},
293 	{
294 		.ident_flags =	TUN_L2,
295 		.cdevsw =	{
296 		    .d_version =	D_VERSION,
297 		    .d_flags =		D_NEEDMINOR,
298 		    .d_open =		tunopen,
299 		    .d_read =		tunread,
300 		    .d_write =		tunwrite,
301 		    .d_ioctl =		tunioctl,
302 		    .d_poll =		tunpoll,
303 		    .d_kqfilter =	tunkqfilter,
304 		    .d_name =		tapname,
305 		},
306 		.clone_match_fn =	tap_clone_match,
307 		.clone_create_fn =	tun_clone_create,
308 		.clone_destroy_fn =	tun_clone_destroy,
309 	},
310 	{
311 		.ident_flags =	TUN_L2 | TUN_VMNET,
312 		.cdevsw =	{
313 		    .d_version =	D_VERSION,
314 		    .d_flags =		D_NEEDMINOR,
315 		    .d_open =		tunopen,
316 		    .d_read =		tunread,
317 		    .d_write =		tunwrite,
318 		    .d_ioctl =		tunioctl,
319 		    .d_poll =		tunpoll,
320 		    .d_kqfilter =	tunkqfilter,
321 		    .d_name =		vmnetname,
322 		},
323 		.clone_match_fn =	vmnet_clone_match,
324 		.clone_create_fn =	tun_clone_create,
325 		.clone_destroy_fn =	tun_clone_destroy,
326 	},
327 };
328 
329 struct tuntap_driver_cloner {
330 	SLIST_ENTRY(tuntap_driver_cloner)	 link;
331 	struct tuntap_driver			*drv;
332 	struct if_clone				*cloner;
333 };
334 
335 VNET_DEFINE_STATIC(SLIST_HEAD(, tuntap_driver_cloner), tuntap_driver_cloners) =
336     SLIST_HEAD_INITIALIZER(tuntap_driver_cloners);
337 
338 #define	V_tuntap_driver_cloners	VNET(tuntap_driver_cloners)
339 
340 /*
341  * Mechanism for marking a tunnel device as busy so that we can safely do some
342  * orthogonal operations (such as operations on devices) without racing against
343  * tun_destroy.  tun_destroy will wait on the condvar if we're at all busy or
344  * open, to be woken up when the condition is alleviated.
345  */
346 static int
347 tun_busy_locked(struct tuntap_softc *tp)
348 {
349 
350 	TUN_LOCK_ASSERT(tp);
351 	if ((tp->tun_flags & TUN_DYING) != 0) {
352 		/*
353 		 * Perhaps unintuitive, but the device is busy going away.
354 		 * Other interpretations of EBUSY from tun_busy make little
355 		 * sense, since making a busy device even more busy doesn't
356 		 * sound like a problem.
357 		 */
358 		return (EBUSY);
359 	}
360 
361 	++tp->tun_busy;
362 	return (0);
363 }
364 
365 static void
366 tun_unbusy_locked(struct tuntap_softc *tp)
367 {
368 
369 	TUN_LOCK_ASSERT(tp);
370 	KASSERT(tp->tun_busy != 0, ("tun_unbusy: called for non-busy tunnel"));
371 
372 	--tp->tun_busy;
373 	/* Wake up anything that may be waiting on our busy tunnel. */
374 	if (tp->tun_busy == 0)
375 		cv_broadcast(&tp->tun_cv);
376 }
377 
378 static int
379 tun_busy(struct tuntap_softc *tp)
380 {
381 	int ret;
382 
383 	TUN_LOCK(tp);
384 	ret = tun_busy_locked(tp);
385 	TUN_UNLOCK(tp);
386 	return (ret);
387 }
388 
389 static void
390 tun_unbusy(struct tuntap_softc *tp)
391 {
392 
393 	TUN_LOCK(tp);
394 	tun_unbusy_locked(tp);
395 	TUN_UNLOCK(tp);
396 }
397 
398 /*
399  * Sets unit and/or flags given the device name.  Must be called with correct
400  * vnet context.
401  */
402 static int
403 tuntap_name2info(const char *name, int *outunit, int *outflags)
404 {
405 	struct tuntap_driver *drv;
406 	struct tuntap_driver_cloner *drvc;
407 	char *dname;
408 	int flags, unit;
409 	bool found;
410 
411 	if (name == NULL)
412 		return (EINVAL);
413 
414 	/*
415 	 * Needed for dev_stdclone, but dev_stdclone will not modify, it just
416 	 * wants to be able to pass back a char * through the second param. We
417 	 * will always set that as NULL here, so we'll fake it.
418 	 */
419 	dname = __DECONST(char *, name);
420 	found = false;
421 
422 	KASSERT(!SLIST_EMPTY(&V_tuntap_driver_cloners),
423 	    ("tuntap_driver_cloners failed to initialize"));
424 	SLIST_FOREACH(drvc, &V_tuntap_driver_cloners, link) {
425 		KASSERT(drvc->drv != NULL,
426 		    ("tuntap_driver_cloners entry not properly initialized"));
427 		drv = drvc->drv;
428 
429 		if (strcmp(name, drv->cdevsw.d_name) == 0) {
430 			found = true;
431 			unit = -1;
432 			flags = drv->ident_flags;
433 			break;
434 		}
435 
436 		if (dev_stdclone(dname, NULL, drv->cdevsw.d_name, &unit) == 1) {
437 			found = true;
438 			flags = drv->ident_flags;
439 			break;
440 		}
441 	}
442 
443 	if (!found)
444 		return (ENXIO);
445 
446 	if (outunit != NULL)
447 		*outunit = unit;
448 	if (outflags != NULL)
449 		*outflags = flags;
450 	return (0);
451 }
452 
453 /*
454  * Get driver information from a set of flags specified.  Masks the identifying
455  * part of the flags and compares it against all of the available
456  * tuntap_drivers. Must be called with correct vnet context.
457  */
458 static struct tuntap_driver *
459 tuntap_driver_from_flags(int tun_flags)
460 {
461 	struct tuntap_driver *drv;
462 	struct tuntap_driver_cloner *drvc;
463 
464 	KASSERT(!SLIST_EMPTY(&V_tuntap_driver_cloners),
465 	    ("tuntap_driver_cloners failed to initialize"));
466 	SLIST_FOREACH(drvc, &V_tuntap_driver_cloners, link) {
467 		KASSERT(drvc->drv != NULL,
468 		    ("tuntap_driver_cloners entry not properly initialized"));
469 		drv = drvc->drv;
470 		if ((tun_flags & TUN_DRIVER_IDENT_MASK) == drv->ident_flags)
471 			return (drv);
472 	}
473 
474 	return (NULL);
475 }
476 
477 static int
478 tun_clone_match(struct if_clone *ifc, const char *name)
479 {
480 	int tunflags;
481 
482 	if (tuntap_name2info(name, NULL, &tunflags) == 0) {
483 		if ((tunflags & TUN_L2) == 0)
484 			return (1);
485 	}
486 
487 	return (0);
488 }
489 
490 static int
491 tap_clone_match(struct if_clone *ifc, const char *name)
492 {
493 	int tunflags;
494 
495 	if (tuntap_name2info(name, NULL, &tunflags) == 0) {
496 		if ((tunflags & (TUN_L2 | TUN_VMNET)) == TUN_L2)
497 			return (1);
498 	}
499 
500 	return (0);
501 }
502 
503 static int
504 vmnet_clone_match(struct if_clone *ifc, const char *name)
505 {
506 	int tunflags;
507 
508 	if (tuntap_name2info(name, NULL, &tunflags) == 0) {
509 		if ((tunflags & TUN_VMNET) != 0)
510 			return (1);
511 	}
512 
513 	return (0);
514 }
515 
516 static int
517 tun_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
518 {
519 	struct tuntap_driver *drv;
520 	struct cdev *dev;
521 	int err, i, tunflags, unit;
522 
523 	tunflags = 0;
524 	/* The name here tells us exactly what we're creating */
525 	err = tuntap_name2info(name, &unit, &tunflags);
526 	if (err != 0)
527 		return (err);
528 
529 	drv = tuntap_driver_from_flags(tunflags);
530 	if (drv == NULL)
531 		return (ENXIO);
532 
533 	if (unit != -1) {
534 		/* If this unit number is still available that's okay. */
535 		if (alloc_unr_specific(drv->unrhdr, unit) == -1)
536 			return (EEXIST);
537 	} else {
538 		unit = alloc_unr(drv->unrhdr);
539 	}
540 
541 	snprintf(name, IFNAMSIZ, "%s%d", drv->cdevsw.d_name, unit);
542 
543 	/* find any existing device, or allocate new unit number */
544 	dev = NULL;
545 	i = clone_create(&drv->clones, &drv->cdevsw, &unit, &dev, 0);
546 	/* No preexisting struct cdev *, create one */
547 	if (i != 0)
548 		i = tun_create_device(drv, unit, NULL, &dev, name);
549 	if (i == 0)
550 		tuncreate(dev);
551 
552 	return (i);
553 }
554 
555 static void
556 tunclone(void *arg, struct ucred *cred, char *name, int namelen,
557     struct cdev **dev)
558 {
559 	char devname[SPECNAMELEN + 1];
560 	struct tuntap_driver *drv;
561 	int append_unit, i, u, tunflags;
562 	bool mayclone;
563 
564 	if (*dev != NULL)
565 		return;
566 
567 	tunflags = 0;
568 	CURVNET_SET(CRED_TO_VNET(cred));
569 	if (tuntap_name2info(name, &u, &tunflags) != 0)
570 		goto out;	/* Not recognized */
571 
572 	if (u != -1 && u > IF_MAXUNIT)
573 		goto out;	/* Unit number too high */
574 
575 	mayclone = priv_check_cred(cred, PRIV_NET_IFCREATE) == 0;
576 	if ((tunflags & TUN_L2) != 0) {
577 		/* tap/vmnet allow user open with a sysctl */
578 		mayclone = (mayclone || tap_allow_uopen) && tapdclone;
579 	} else {
580 		mayclone = mayclone && tundclone;
581 	}
582 
583 	/*
584 	 * If tun cloning is enabled, only the superuser can create an
585 	 * interface.
586 	 */
587 	if (!mayclone)
588 		goto out;
589 
590 	if (u == -1)
591 		append_unit = 1;
592 	else
593 		append_unit = 0;
594 
595 	drv = tuntap_driver_from_flags(tunflags);
596 	if (drv == NULL)
597 		goto out;
598 
599 	/* find any existing device, or allocate new unit number */
600 	i = clone_create(&drv->clones, &drv->cdevsw, &u, dev, 0);
601 	if (i) {
602 		if (append_unit) {
603 			namelen = snprintf(devname, sizeof(devname), "%s%d",
604 			    name, u);
605 			name = devname;
606 		}
607 
608 		i = tun_create_device(drv, u, cred, dev, name);
609 	}
610 	if (i == 0)
611 		if_clone_create(name, namelen, NULL);
612 out:
613 	CURVNET_RESTORE();
614 }
615 
616 static void
617 tun_destroy(struct tuntap_softc *tp)
618 {
619 
620 	TUN_LOCK(tp);
621 	tp->tun_flags |= TUN_DYING;
622 	if (tp->tun_busy != 0)
623 		cv_wait_unlock(&tp->tun_cv, &tp->tun_mtx);
624 	else
625 		TUN_UNLOCK(tp);
626 
627 	CURVNET_SET(TUN2IFP(tp)->if_vnet);
628 
629 	/* destroy_dev will take care of any alias. */
630 	destroy_dev(tp->tun_dev);
631 	seldrain(&tp->tun_rsel);
632 	knlist_clear(&tp->tun_rsel.si_note, 0);
633 	knlist_destroy(&tp->tun_rsel.si_note);
634 	if ((tp->tun_flags & TUN_L2) != 0) {
635 		ether_ifdetach(TUN2IFP(tp));
636 	} else {
637 		bpfdetach(TUN2IFP(tp));
638 		if_detach(TUN2IFP(tp));
639 	}
640 	sx_xlock(&tun_ioctl_sx);
641 	TUN2IFP(tp)->if_softc = NULL;
642 	sx_xunlock(&tun_ioctl_sx);
643 	free_unr(tp->tun_drv->unrhdr, TUN2IFP(tp)->if_dunit);
644 	if_free(TUN2IFP(tp));
645 	mtx_destroy(&tp->tun_mtx);
646 	cv_destroy(&tp->tun_cv);
647 	free(tp, M_TUN);
648 	CURVNET_RESTORE();
649 }
650 
651 static int
652 tun_clone_destroy(struct if_clone *ifc __unused, struct ifnet *ifp)
653 {
654 	struct tuntap_softc *tp = ifp->if_softc;
655 
656 	mtx_lock(&tunmtx);
657 	TAILQ_REMOVE(&tunhead, tp, tun_list);
658 	mtx_unlock(&tunmtx);
659 	tun_destroy(tp);
660 
661 	return (0);
662 }
663 
664 static void
665 vnet_tun_init(const void *unused __unused)
666 {
667 	struct tuntap_driver *drv;
668 	struct tuntap_driver_cloner *drvc;
669 	int i;
670 
671 	for (i = 0; i < nitems(tuntap_drivers); ++i) {
672 		drv = &tuntap_drivers[i];
673 		drvc = malloc(sizeof(*drvc), M_TUN, M_WAITOK | M_ZERO);
674 
675 		drvc->drv = drv;
676 		drvc->cloner = if_clone_advanced(drv->cdevsw.d_name, 0,
677 		    drv->clone_match_fn, drv->clone_create_fn,
678 		    drv->clone_destroy_fn);
679 		SLIST_INSERT_HEAD(&V_tuntap_driver_cloners, drvc, link);
680 	};
681 }
682 VNET_SYSINIT(vnet_tun_init, SI_SUB_PROTO_IF, SI_ORDER_ANY,
683 		vnet_tun_init, NULL);
684 
685 static void
686 vnet_tun_uninit(const void *unused __unused)
687 {
688 	struct tuntap_driver_cloner *drvc;
689 
690 	while (!SLIST_EMPTY(&V_tuntap_driver_cloners)) {
691 		drvc = SLIST_FIRST(&V_tuntap_driver_cloners);
692 		SLIST_REMOVE_HEAD(&V_tuntap_driver_cloners, link);
693 
694 		if_clone_detach(drvc->cloner);
695 		free(drvc, M_TUN);
696 	}
697 }
698 VNET_SYSUNINIT(vnet_tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY,
699     vnet_tun_uninit, NULL);
700 
701 static void
702 tun_uninit(const void *unused __unused)
703 {
704 	struct tuntap_driver *drv;
705 	struct tuntap_softc *tp;
706 	int i;
707 
708 	EVENTHANDLER_DEREGISTER(ifnet_arrival_event, arrival_tag);
709 	EVENTHANDLER_DEREGISTER(dev_clone, clone_tag);
710 	drain_dev_clone_events();
711 
712 	mtx_lock(&tunmtx);
713 	while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
714 		TAILQ_REMOVE(&tunhead, tp, tun_list);
715 		mtx_unlock(&tunmtx);
716 		tun_destroy(tp);
717 		mtx_lock(&tunmtx);
718 	}
719 	mtx_unlock(&tunmtx);
720 	for (i = 0; i < nitems(tuntap_drivers); ++i) {
721 		drv = &tuntap_drivers[i];
722 		delete_unrhdr(drv->unrhdr);
723 		clone_cleanup(&drv->clones);
724 	}
725 	mtx_destroy(&tunmtx);
726 }
727 SYSUNINIT(tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY, tun_uninit, NULL);
728 
729 static struct tuntap_driver *
730 tuntap_driver_from_ifnet(const struct ifnet *ifp)
731 {
732 	struct tuntap_driver *drv;
733 	int i;
734 
735 	if (ifp == NULL)
736 		return (NULL);
737 
738 	for (i = 0; i < nitems(tuntap_drivers); ++i) {
739 		drv = &tuntap_drivers[i];
740 		if (strcmp(ifp->if_dname, drv->cdevsw.d_name) == 0)
741 			return (drv);
742 	}
743 
744 	return (NULL);
745 }
746 
747 static int
748 tuntapmodevent(module_t mod, int type, void *data)
749 {
750 	struct tuntap_driver *drv;
751 	int i;
752 
753 	switch (type) {
754 	case MOD_LOAD:
755 		mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
756 		for (i = 0; i < nitems(tuntap_drivers); ++i) {
757 			drv = &tuntap_drivers[i];
758 			clone_setup(&drv->clones);
759 			drv->unrhdr = new_unrhdr(0, IF_MAXUNIT, &tunmtx);
760 		}
761 		arrival_tag = EVENTHANDLER_REGISTER(ifnet_arrival_event,
762 		   tunrename, 0, 1000);
763 		if (arrival_tag == NULL)
764 			return (ENOMEM);
765 		clone_tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
766 		if (clone_tag == NULL)
767 			return (ENOMEM);
768 		break;
769 	case MOD_UNLOAD:
770 		/* See tun_uninit, so it's done after the vnet_sysuninit() */
771 		break;
772 	default:
773 		return EOPNOTSUPP;
774 	}
775 	return 0;
776 }
777 
778 static moduledata_t tuntap_mod = {
779 	"if_tuntap",
780 	tuntapmodevent,
781 	0
782 };
783 
784 /* We'll only ever have these two, so no need for a macro. */
785 static moduledata_t tun_mod = { "if_tun", NULL, 0 };
786 static moduledata_t tap_mod = { "if_tap", NULL, 0 };
787 
788 DECLARE_MODULE(if_tuntap, tuntap_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
789 MODULE_VERSION(if_tuntap, 1);
790 DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
791 MODULE_VERSION(if_tun, 1);
792 DECLARE_MODULE(if_tap, tap_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
793 MODULE_VERSION(if_tap, 1);
794 
795 static int
796 tun_create_device(struct tuntap_driver *drv, int unit, struct ucred *cr,
797     struct cdev **dev, const char *name)
798 {
799 	struct make_dev_args args;
800 	struct tuntap_softc *tp;
801 	int error;
802 
803 	tp = malloc(sizeof(*tp), M_TUN, M_WAITOK | M_ZERO);
804 	mtx_init(&tp->tun_mtx, "tun_mtx", NULL, MTX_DEF);
805 	cv_init(&tp->tun_cv, "tun_condvar");
806 	tp->tun_flags = drv->ident_flags;
807 	tp->tun_drv = drv;
808 
809 	make_dev_args_init(&args);
810 	if (cr != NULL)
811 		args.mda_flags = MAKEDEV_REF;
812 	args.mda_devsw = &drv->cdevsw;
813 	args.mda_cr = cr;
814 	args.mda_uid = UID_UUCP;
815 	args.mda_gid = GID_DIALER;
816 	args.mda_mode = 0600;
817 	args.mda_unit = unit;
818 	args.mda_si_drv1 = tp;
819 	error = make_dev_s(&args, dev, "%s", name);
820 	if (error != 0) {
821 		free(tp, M_TUN);
822 		return (error);
823 	}
824 
825 	KASSERT((*dev)->si_drv1 != NULL,
826 	    ("Failed to set si_drv1 at %s creation", name));
827 	tp->tun_dev = *dev;
828 	knlist_init_mtx(&tp->tun_rsel.si_note, &tp->tun_mtx);
829 	mtx_lock(&tunmtx);
830 	TAILQ_INSERT_TAIL(&tunhead, tp, tun_list);
831 	mtx_unlock(&tunmtx);
832 	return (0);
833 }
834 
835 static void
836 tunstart(struct ifnet *ifp)
837 {
838 	struct tuntap_softc *tp = ifp->if_softc;
839 	struct mbuf *m;
840 
841 	TUNDEBUG(ifp, "starting\n");
842 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
843 		IFQ_LOCK(&ifp->if_snd);
844 		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
845 		if (m == NULL) {
846 			IFQ_UNLOCK(&ifp->if_snd);
847 			return;
848 		}
849 		IFQ_UNLOCK(&ifp->if_snd);
850 	}
851 
852 	TUN_LOCK(tp);
853 	if (tp->tun_flags & TUN_RWAIT) {
854 		tp->tun_flags &= ~TUN_RWAIT;
855 		wakeup(tp);
856 	}
857 	selwakeuppri(&tp->tun_rsel, PZERO + 1);
858 	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
859 	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
860 		TUN_UNLOCK(tp);
861 		pgsigio(&tp->tun_sigio, SIGIO, 0);
862 	} else
863 		TUN_UNLOCK(tp);
864 }
865 
866 /*
867  * tunstart_l2
868  *
869  * queue packets from higher level ready to put out
870  */
871 static void
872 tunstart_l2(struct ifnet *ifp)
873 {
874 	struct tuntap_softc	*tp = ifp->if_softc;
875 
876 	TUNDEBUG(ifp, "starting\n");
877 
878 	/*
879 	 * do not junk pending output if we are in VMnet mode.
880 	 * XXX: can this do any harm because of queue overflow?
881 	 */
882 
883 	TUN_LOCK(tp);
884 	if (((tp->tun_flags & TUN_VMNET) == 0) &&
885 	    ((tp->tun_flags & TUN_READY) != TUN_READY)) {
886 		struct mbuf *m;
887 
888 		/* Unlocked read. */
889 		TUNDEBUG(ifp, "not ready, tun_flags = 0x%x\n", tp->tun_flags);
890 
891 		for (;;) {
892 			IF_DEQUEUE(&ifp->if_snd, m);
893 			if (m != NULL) {
894 				m_freem(m);
895 				if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
896 			} else
897 				break;
898 		}
899 		TUN_UNLOCK(tp);
900 
901 		return;
902 	}
903 
904 	ifp->if_drv_flags |= IFF_DRV_OACTIVE;
905 
906 	if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
907 		if (tp->tun_flags & TUN_RWAIT) {
908 			tp->tun_flags &= ~TUN_RWAIT;
909 			wakeup(tp);
910 		}
911 
912 		if ((tp->tun_flags & TUN_ASYNC) && (tp->tun_sigio != NULL)) {
913 			TUN_UNLOCK(tp);
914 			pgsigio(&tp->tun_sigio, SIGIO, 0);
915 			TUN_LOCK(tp);
916 		}
917 
918 		selwakeuppri(&tp->tun_rsel, PZERO+1);
919 		KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
920 		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* obytes are counted in ether_output */
921 	}
922 
923 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
924 	TUN_UNLOCK(tp);
925 } /* tunstart_l2 */
926 
927 /* XXX: should return an error code so it can fail. */
928 static void
929 tuncreate(struct cdev *dev)
930 {
931 	struct tuntap_driver *drv;
932 	struct tuntap_softc *tp;
933 	struct ifnet *ifp;
934 	struct ether_addr eaddr;
935 	int iflags;
936 	u_char type;
937 
938 	tp = dev->si_drv1;
939 	KASSERT(tp != NULL,
940 	    ("si_drv1 should have been initialized at creation"));
941 
942 	drv = tp->tun_drv;
943 	iflags = IFF_MULTICAST;
944 	if ((tp->tun_flags & TUN_L2) != 0) {
945 		type = IFT_ETHER;
946 		iflags |= IFF_BROADCAST | IFF_SIMPLEX;
947 	} else {
948 		type = IFT_PPP;
949 		iflags |= IFF_POINTOPOINT;
950 	}
951 	ifp = tp->tun_ifp = if_alloc(type);
952 	if (ifp == NULL)
953 		panic("%s%d: failed to if_alloc() interface.\n",
954 		    drv->cdevsw.d_name, dev2unit(dev));
955 	ifp->if_softc = tp;
956 	if_initname(ifp, drv->cdevsw.d_name, dev2unit(dev));
957 	ifp->if_ioctl = tunifioctl;
958 	ifp->if_flags = iflags;
959 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
960 	ifp->if_capabilities |= IFCAP_LINKSTATE;
961 	ifp->if_capenable |= IFCAP_LINKSTATE;
962 
963 	if ((tp->tun_flags & TUN_L2) != 0) {
964 		ifp->if_init = tunifinit;
965 		ifp->if_start = tunstart_l2;
966 
967 		ether_gen_addr(ifp, &eaddr);
968 		ether_ifattach(ifp, eaddr.octet);
969 	} else {
970 		ifp->if_mtu = TUNMTU;
971 		ifp->if_start = tunstart;
972 		ifp->if_output = tunoutput;
973 
974 		ifp->if_snd.ifq_drv_maxlen = 0;
975 		IFQ_SET_READY(&ifp->if_snd);
976 
977 		if_attach(ifp);
978 		bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
979 	}
980 
981 	TUN_LOCK(tp);
982 	tp->tun_flags |= TUN_INITED;
983 	TUN_UNLOCK(tp);
984 
985 	TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
986 	    ifp->if_xname, dev2unit(dev));
987 }
988 
989 static void
990 tunrename(void *arg __unused, struct ifnet *ifp)
991 {
992 	struct tuntap_softc *tp;
993 	int error;
994 
995 	if ((ifp->if_flags & IFF_RENAMING) == 0)
996 		return;
997 
998 	if (tuntap_driver_from_ifnet(ifp) == NULL)
999 		return;
1000 
1001 	/*
1002 	 * We need to grab the ioctl sx long enough to make sure the softc is
1003 	 * still there.  If it is, we can safely try to busy the tun device.
1004 	 * The busy may fail if the device is currently dying, in which case
1005 	 * we do nothing.  If it doesn't fail, the busy count stops the device
1006 	 * from dying until we've created the alias (that will then be
1007 	 * subsequently destroyed).
1008 	 */
1009 	sx_xlock(&tun_ioctl_sx);
1010 	tp = ifp->if_softc;
1011 	if (tp == NULL) {
1012 		sx_xunlock(&tun_ioctl_sx);
1013 		return;
1014 	}
1015 	error = tun_busy(tp);
1016 	sx_xunlock(&tun_ioctl_sx);
1017 	if (error != 0)
1018 		return;
1019 	if (tp->tun_alias != NULL) {
1020 		destroy_dev(tp->tun_alias);
1021 		tp->tun_alias = NULL;
1022 	}
1023 
1024 	if (strcmp(ifp->if_xname, tp->tun_dev->si_name) == 0)
1025 		goto out;
1026 
1027 	/*
1028 	 * Failure's ok, aliases are created on a best effort basis.  If a
1029 	 * tun user/consumer decides to rename the interface to conflict with
1030 	 * another device (non-ifnet) on the system, we will assume they know
1031 	 * what they are doing.  make_dev_alias_p won't touch tun_alias on
1032 	 * failure, so we use it but ignore the return value.
1033 	 */
1034 	make_dev_alias_p(MAKEDEV_CHECKNAME, &tp->tun_alias, tp->tun_dev, "%s",
1035 	    ifp->if_xname);
1036 out:
1037 	tun_unbusy(tp);
1038 }
1039 
1040 static int
1041 tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
1042 {
1043 	struct ifnet	*ifp;
1044 	struct tuntap_softc *tp;
1045 	int error, tunflags;
1046 
1047 	tunflags = 0;
1048 	CURVNET_SET(TD_TO_VNET(td));
1049 	error = tuntap_name2info(dev->si_name, NULL, &tunflags);
1050 	if (error != 0) {
1051 		CURVNET_RESTORE();
1052 		return (error);	/* Shouldn't happen */
1053 	}
1054 
1055 	tp = dev->si_drv1;
1056 	KASSERT(tp != NULL,
1057 	    ("si_drv1 should have been initialized at creation"));
1058 
1059 	TUN_LOCK(tp);
1060 	if ((tp->tun_flags & TUN_INITED) == 0) {
1061 		TUN_UNLOCK(tp);
1062 		CURVNET_RESTORE();
1063 		return (ENXIO);
1064 	}
1065 	if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) {
1066 		TUN_UNLOCK(tp);
1067 		CURVNET_RESTORE();
1068 		return (EBUSY);
1069 	}
1070 
1071 	error = tun_busy_locked(tp);
1072 	KASSERT(error == 0, ("Must be able to busy an unopen tunnel"));
1073 	ifp = TUN2IFP(tp);
1074 
1075 	if ((tp->tun_flags & TUN_L2) != 0) {
1076 		bcopy(IF_LLADDR(ifp), tp->tun_ether.octet,
1077 		    sizeof(tp->tun_ether.octet));
1078 
1079 		ifp->if_drv_flags |= IFF_DRV_RUNNING;
1080 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1081 
1082 		if (tapuponopen)
1083 			ifp->if_flags |= IFF_UP;
1084 	}
1085 
1086 	tp->tun_pid = td->td_proc->p_pid;
1087 	tp->tun_flags |= TUN_OPEN;
1088 
1089 	if_link_state_change(ifp, LINK_STATE_UP);
1090 	TUNDEBUG(ifp, "open\n");
1091 	TUN_UNLOCK(tp);
1092 
1093 	/*
1094 	 * This can fail with either ENOENT or EBUSY.  This is in the middle of
1095 	 * d_open, so ENOENT should not be possible.  EBUSY is possible, but
1096 	 * the only cdevpriv dtor being set will be tundtor and the softc being
1097 	 * passed is constant for a given cdev.  We ignore the possible error
1098 	 * because of this as either "unlikely" or "not actually a problem."
1099 	 */
1100 	(void)devfs_set_cdevpriv(tp, tundtor);
1101 	CURVNET_RESTORE();
1102 	return (0);
1103 }
1104 
1105 /*
1106  * tundtor - tear down the device - mark i/f down & delete
1107  * routing info
1108  */
1109 static void
1110 tundtor(void *data)
1111 {
1112 	struct proc *p;
1113 	struct tuntap_softc *tp;
1114 	struct ifnet *ifp;
1115 	bool l2tun;
1116 
1117 	tp = data;
1118 	p = curproc;
1119 	ifp = TUN2IFP(tp);
1120 
1121 	TUN_LOCK(tp);
1122 
1123 	/*
1124 	 * Realistically, we can't be obstinate here.  This only means that the
1125 	 * tuntap device was closed out of order, and the last closer wasn't the
1126 	 * controller.  These are still good to know about, though, as software
1127 	 * should avoid multiple processes with a tuntap device open and
1128 	 * ill-defined transfer of control (e.g., handoff, TUNSIFPID, close in
1129 	 * parent).
1130 	 */
1131 	if (p->p_pid != tp->tun_pid) {
1132 		log(LOG_INFO,
1133 		    "pid %d (%s), %s: tun/tap protocol violation, non-controlling process closed last.\n",
1134 		    p->p_pid, p->p_comm, tp->tun_dev->si_name);
1135 	}
1136 
1137 	/*
1138 	 * junk all pending output
1139 	 */
1140 	CURVNET_SET(ifp->if_vnet);
1141 
1142 	l2tun = false;
1143 	if ((tp->tun_flags & TUN_L2) != 0) {
1144 		l2tun = true;
1145 		IF_DRAIN(&ifp->if_snd);
1146 	} else {
1147 		IFQ_PURGE(&ifp->if_snd);
1148 	}
1149 
1150 	/* For vmnet, we won't do most of the address/route bits */
1151 	if ((tp->tun_flags & TUN_VMNET) != 0 ||
1152 	    (l2tun && (ifp->if_flags & IFF_LINK0) != 0))
1153 		goto out;
1154 
1155 	if (ifp->if_flags & IFF_UP) {
1156 		TUN_UNLOCK(tp);
1157 		if_down(ifp);
1158 		TUN_LOCK(tp);
1159 	}
1160 
1161 	/* Delete all addresses and routes which reference this interface. */
1162 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1163 		struct ifaddr *ifa;
1164 
1165 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1166 		TUN_UNLOCK(tp);
1167 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1168 			/* deal w/IPv4 PtP destination; unlocked read */
1169 			if (!l2tun && ifa->ifa_addr->sa_family == AF_INET) {
1170 				rtinit(ifa, (int)RTM_DELETE,
1171 				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
1172 			} else {
1173 				rtinit(ifa, (int)RTM_DELETE, 0);
1174 			}
1175 		}
1176 		if_purgeaddrs(ifp);
1177 		TUN_LOCK(tp);
1178 	}
1179 
1180 out:
1181 	if_link_state_change(ifp, LINK_STATE_DOWN);
1182 	CURVNET_RESTORE();
1183 
1184 	funsetown(&tp->tun_sigio);
1185 	selwakeuppri(&tp->tun_rsel, PZERO + 1);
1186 	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
1187 	TUNDEBUG (ifp, "closed\n");
1188 	tp->tun_flags &= ~TUN_OPEN;
1189 	tp->tun_pid = 0;
1190 	tun_vnethdr_set(ifp, 0);
1191 
1192 	tun_unbusy_locked(tp);
1193 	TUN_UNLOCK(tp);
1194 }
1195 
1196 static void
1197 tuninit(struct ifnet *ifp)
1198 {
1199 	struct tuntap_softc *tp = ifp->if_softc;
1200 #ifdef INET
1201 	struct epoch_tracker et;
1202 	struct ifaddr *ifa;
1203 #endif
1204 
1205 	TUNDEBUG(ifp, "tuninit\n");
1206 
1207 	TUN_LOCK(tp);
1208 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1209 	if ((tp->tun_flags & TUN_L2) == 0) {
1210 		ifp->if_flags |= IFF_UP;
1211 		getmicrotime(&ifp->if_lastchange);
1212 #ifdef INET
1213 		NET_EPOCH_ENTER(et);
1214 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1215 			if (ifa->ifa_addr->sa_family == AF_INET) {
1216 				struct sockaddr_in *si;
1217 
1218 				si = (struct sockaddr_in *)ifa->ifa_dstaddr;
1219 				if (si && si->sin_addr.s_addr) {
1220 					tp->tun_flags |= TUN_DSTADDR;
1221 					break;
1222 				}
1223 			}
1224 		}
1225 		NET_EPOCH_EXIT(et);
1226 #endif
1227 		TUN_UNLOCK(tp);
1228 	} else {
1229 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1230 		TUN_UNLOCK(tp);
1231 		/* attempt to start output */
1232 		tunstart_l2(ifp);
1233 	}
1234 
1235 }
1236 
1237 /*
1238  * Used only for l2 tunnel.
1239  */
1240 static void
1241 tunifinit(void *xtp)
1242 {
1243 	struct tuntap_softc *tp;
1244 
1245 	tp = (struct tuntap_softc *)xtp;
1246 	tuninit(tp->tun_ifp);
1247 }
1248 
1249 /*
1250  * To be called under TUN_LOCK. Update ifp->if_hwassist according to the
1251  * current value of ifp->if_capenable.
1252  */
1253 static void
1254 tun_caps_changed(struct ifnet *ifp)
1255 {
1256 	uint64_t hwassist = 0;
1257 
1258 	TUN_LOCK_ASSERT((struct tuntap_softc *)ifp->if_softc);
1259 	if (ifp->if_capenable & IFCAP_TXCSUM)
1260 		hwassist |= CSUM_TCP | CSUM_UDP;
1261 	if (ifp->if_capenable & IFCAP_TXCSUM_IPV6)
1262 		hwassist |= CSUM_TCP_IPV6
1263 		    | CSUM_UDP_IPV6;
1264 	if (ifp->if_capenable & IFCAP_TSO4)
1265 		hwassist |= CSUM_IP_TSO;
1266 	if (ifp->if_capenable & IFCAP_TSO6)
1267 		hwassist |= CSUM_IP6_TSO;
1268 	ifp->if_hwassist = hwassist;
1269 }
1270 
1271 /*
1272  * To be called under TUN_LOCK. Update tp->tun_vhdrlen and adjust
1273  * if_capabilities and if_capenable as needed.
1274  */
1275 static void
1276 tun_vnethdr_set(struct ifnet *ifp, int vhdrlen)
1277 {
1278 	struct tuntap_softc *tp = ifp->if_softc;
1279 
1280 	TUN_LOCK_ASSERT(tp);
1281 
1282 	if (tp->tun_vhdrlen == vhdrlen)
1283 		return;
1284 
1285 	/*
1286 	 * Update if_capabilities to reflect the
1287 	 * functionalities offered by the virtio-net
1288 	 * header.
1289 	 */
1290 	if (vhdrlen != 0)
1291 		ifp->if_capabilities |=
1292 			TAP_VNET_HDR_CAPS;
1293 	else
1294 		ifp->if_capabilities &=
1295 			~TAP_VNET_HDR_CAPS;
1296 	/*
1297 	 * Disable any capabilities that we don't
1298 	 * support anymore.
1299 	 */
1300 	ifp->if_capenable &= ifp->if_capabilities;
1301 	tun_caps_changed(ifp);
1302 	tp->tun_vhdrlen = vhdrlen;
1303 
1304 	TUNDEBUG(ifp, "vnet_hdr_len=%d, if_capabilities=%x\n",
1305 	    vhdrlen, ifp->if_capabilities);
1306 }
1307 
1308 /*
1309  * Process an ioctl request.
1310  */
1311 static int
1312 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1313 {
1314 	struct ifreq *ifr = (struct ifreq *)data;
1315 	struct tuntap_softc *tp;
1316 	struct ifstat *ifs;
1317 	struct ifmediareq	*ifmr;
1318 	int		dummy, error = 0;
1319 	bool		l2tun;
1320 
1321 	ifmr = NULL;
1322 	sx_xlock(&tun_ioctl_sx);
1323 	tp = ifp->if_softc;
1324 	if (tp == NULL) {
1325 		error = ENXIO;
1326 		goto bad;
1327 	}
1328 	l2tun = (tp->tun_flags & TUN_L2) != 0;
1329 	switch(cmd) {
1330 	case SIOCGIFSTATUS:
1331 		ifs = (struct ifstat *)data;
1332 		TUN_LOCK(tp);
1333 		if (tp->tun_pid)
1334 			snprintf(ifs->ascii, sizeof(ifs->ascii),
1335 			    "\tOpened by PID %d\n", tp->tun_pid);
1336 		else
1337 			ifs->ascii[0] = '\0';
1338 		TUN_UNLOCK(tp);
1339 		break;
1340 	case SIOCSIFADDR:
1341 		if (l2tun)
1342 			error = ether_ioctl(ifp, cmd, data);
1343 		else
1344 			tuninit(ifp);
1345 		if (error == 0)
1346 		    TUNDEBUG(ifp, "address set\n");
1347 		break;
1348 	case SIOCSIFMTU:
1349 		ifp->if_mtu = ifr->ifr_mtu;
1350 		TUNDEBUG(ifp, "mtu set\n");
1351 		break;
1352 	case SIOCSIFFLAGS:
1353 	case SIOCADDMULTI:
1354 	case SIOCDELMULTI:
1355 		break;
1356 	case SIOCGIFMEDIA:
1357 		if (!l2tun) {
1358 			error = EINVAL;
1359 			break;
1360 		}
1361 
1362 		ifmr = (struct ifmediareq *)data;
1363 		dummy = ifmr->ifm_count;
1364 		ifmr->ifm_count = 1;
1365 		ifmr->ifm_status = IFM_AVALID;
1366 		ifmr->ifm_active = IFM_ETHER;
1367 		if (tp->tun_flags & TUN_OPEN)
1368 			ifmr->ifm_status |= IFM_ACTIVE;
1369 		ifmr->ifm_current = ifmr->ifm_active;
1370 		if (dummy >= 1) {
1371 			int media = IFM_ETHER;
1372 			error = copyout(&media, ifmr->ifm_ulist, sizeof(int));
1373 		}
1374 		break;
1375 	case SIOCSIFCAP:
1376 		TUN_LOCK(tp);
1377 		ifp->if_capenable = ifr->ifr_reqcap;
1378 		tun_caps_changed(ifp);
1379 		TUN_UNLOCK(tp);
1380 		VLAN_CAPABILITIES(ifp);
1381 		break;
1382 	default:
1383 		if (l2tun) {
1384 			error = ether_ioctl(ifp, cmd, data);
1385 		} else {
1386 			error = EINVAL;
1387 		}
1388 	}
1389 bad:
1390 	sx_xunlock(&tun_ioctl_sx);
1391 	return (error);
1392 }
1393 
1394 /*
1395  * tunoutput - queue packets from higher level ready to put out.
1396  */
1397 static int
1398 tunoutput(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst,
1399     struct route *ro)
1400 {
1401 	struct tuntap_softc *tp = ifp->if_softc;
1402 	u_short cached_tun_flags;
1403 	int error;
1404 	u_int32_t af;
1405 
1406 	TUNDEBUG (ifp, "tunoutput\n");
1407 
1408 #ifdef MAC
1409 	error = mac_ifnet_check_transmit(ifp, m0);
1410 	if (error) {
1411 		m_freem(m0);
1412 		return (error);
1413 	}
1414 #endif
1415 
1416 	/* Could be unlocked read? */
1417 	TUN_LOCK(tp);
1418 	cached_tun_flags = tp->tun_flags;
1419 	TUN_UNLOCK(tp);
1420 	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
1421 		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
1422 		m_freem (m0);
1423 		return (EHOSTDOWN);
1424 	}
1425 
1426 	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
1427 		m_freem (m0);
1428 		return (EHOSTDOWN);
1429 	}
1430 
1431 	/* BPF writes need to be handled specially. */
1432 	if (dst->sa_family == AF_UNSPEC)
1433 		bcopy(dst->sa_data, &af, sizeof(af));
1434 	else
1435 		af = dst->sa_family;
1436 
1437 	if (bpf_peers_present(ifp->if_bpf))
1438 		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
1439 
1440 	/* prepend sockaddr? this may abort if the mbuf allocation fails */
1441 	if (cached_tun_flags & TUN_LMODE) {
1442 		/* allocate space for sockaddr */
1443 		M_PREPEND(m0, dst->sa_len, M_NOWAIT);
1444 
1445 		/* if allocation failed drop packet */
1446 		if (m0 == NULL) {
1447 			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1448 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1449 			return (ENOBUFS);
1450 		} else {
1451 			bcopy(dst, m0->m_data, dst->sa_len);
1452 		}
1453 	}
1454 
1455 	if (cached_tun_flags & TUN_IFHEAD) {
1456 		/* Prepend the address family */
1457 		M_PREPEND(m0, 4, M_NOWAIT);
1458 
1459 		/* if allocation failed drop packet */
1460 		if (m0 == NULL) {
1461 			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1462 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1463 			return (ENOBUFS);
1464 		} else
1465 			*(u_int32_t *)m0->m_data = htonl(af);
1466 	} else {
1467 #ifdef INET
1468 		if (af != AF_INET)
1469 #endif
1470 		{
1471 			m_freem(m0);
1472 			return (EAFNOSUPPORT);
1473 		}
1474 	}
1475 
1476 	error = (ifp->if_transmit)(ifp, m0);
1477 	if (error)
1478 		return (ENOBUFS);
1479 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1480 	return (0);
1481 }
1482 
1483 /*
1484  * the cdevsw interface is now pretty minimal.
1485  */
1486 static	int
1487 tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
1488     struct thread *td)
1489 {
1490 	struct ifreq ifr, *ifrp;
1491 	struct tuntap_softc *tp = dev->si_drv1;
1492 	struct ifnet *ifp = TUN2IFP(tp);
1493 	struct tuninfo *tunp;
1494 	int error, iflags, ival;
1495 	bool	l2tun;
1496 
1497 	l2tun = (tp->tun_flags & TUN_L2) != 0;
1498 	if (l2tun) {
1499 		/* tap specific ioctls */
1500 		switch(cmd) {
1501 		/* VMware/VMnet port ioctl's */
1502 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1503     defined(COMPAT_FREEBSD4)
1504 		case _IO('V', 0):
1505 			ival = IOCPARM_IVAL(data);
1506 			data = (caddr_t)&ival;
1507 			/* FALLTHROUGH */
1508 #endif
1509 		case VMIO_SIOCSIFFLAGS: /* VMware/VMnet SIOCSIFFLAGS */
1510 			iflags = *(int *)data;
1511 			iflags &= TUN_VMIO_FLAG_MASK;
1512 			iflags &= ~IFF_CANTCHANGE;
1513 			iflags |= IFF_UP;
1514 
1515 			TUN_LOCK(tp);
1516 			ifp->if_flags = iflags |
1517 			    (ifp->if_flags & IFF_CANTCHANGE);
1518 			TUN_UNLOCK(tp);
1519 
1520 			return (0);
1521 		case SIOCGIFADDR:	/* get MAC address of the remote side */
1522 			TUN_LOCK(tp);
1523 			bcopy(&tp->tun_ether.octet, data,
1524 			    sizeof(tp->tun_ether.octet));
1525 			TUN_UNLOCK(tp);
1526 
1527 			return (0);
1528 		case SIOCSIFADDR:	/* set MAC address of the remote side */
1529 			TUN_LOCK(tp);
1530 			bcopy(data, &tp->tun_ether.octet,
1531 			    sizeof(tp->tun_ether.octet));
1532 			TUN_UNLOCK(tp);
1533 
1534 			return (0);
1535 		case TAPSVNETHDR:
1536 			ival = *(int *)data;
1537 			if (ival != 0 &&
1538 			    ival != sizeof(struct virtio_net_hdr) &&
1539 			    ival != sizeof(struct virtio_net_hdr_mrg_rxbuf)) {
1540 				return (EINVAL);
1541 			}
1542 			TUN_LOCK(tp);
1543 			tun_vnethdr_set(ifp, ival);
1544 			TUN_UNLOCK(tp);
1545 
1546 			return (0);
1547 		case TAPGVNETHDR:
1548 			TUN_LOCK(tp);
1549 			*(int *)data = tp->tun_vhdrlen;
1550 			TUN_UNLOCK(tp);
1551 
1552 			return (0);
1553 		}
1554 
1555 		/* Fall through to the common ioctls if unhandled */
1556 	} else {
1557 		switch (cmd) {
1558 		case TUNSLMODE:
1559 			TUN_LOCK(tp);
1560 			if (*(int *)data) {
1561 				tp->tun_flags |= TUN_LMODE;
1562 				tp->tun_flags &= ~TUN_IFHEAD;
1563 			} else
1564 				tp->tun_flags &= ~TUN_LMODE;
1565 			TUN_UNLOCK(tp);
1566 
1567 			return (0);
1568 		case TUNSIFHEAD:
1569 			TUN_LOCK(tp);
1570 			if (*(int *)data) {
1571 				tp->tun_flags |= TUN_IFHEAD;
1572 				tp->tun_flags &= ~TUN_LMODE;
1573 			} else
1574 				tp->tun_flags &= ~TUN_IFHEAD;
1575 			TUN_UNLOCK(tp);
1576 
1577 			return (0);
1578 		case TUNGIFHEAD:
1579 			TUN_LOCK(tp);
1580 			*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
1581 			TUN_UNLOCK(tp);
1582 
1583 			return (0);
1584 		case TUNSIFMODE:
1585 			/* deny this if UP */
1586 			if (TUN2IFP(tp)->if_flags & IFF_UP)
1587 				return (EBUSY);
1588 
1589 			switch (*(int *)data & ~IFF_MULTICAST) {
1590 			case IFF_POINTOPOINT:
1591 			case IFF_BROADCAST:
1592 				TUN_LOCK(tp);
1593 				TUN2IFP(tp)->if_flags &=
1594 				    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
1595 				TUN2IFP(tp)->if_flags |= *(int *)data;
1596 				TUN_UNLOCK(tp);
1597 
1598 				break;
1599 			default:
1600 				return (EINVAL);
1601 			}
1602 
1603 			return (0);
1604 		case TUNSIFPID:
1605 			TUN_LOCK(tp);
1606 			tp->tun_pid = curthread->td_proc->p_pid;
1607 			TUN_UNLOCK(tp);
1608 
1609 			return (0);
1610 		}
1611 		/* Fall through to the common ioctls if unhandled */
1612 	}
1613 
1614 	switch (cmd) {
1615 	case TUNGIFNAME:
1616 		ifrp = (struct ifreq *)data;
1617 		strlcpy(ifrp->ifr_name, TUN2IFP(tp)->if_xname, IFNAMSIZ);
1618 
1619 		return (0);
1620 	case TUNSIFINFO:
1621 		tunp = (struct tuninfo *)data;
1622 		if (TUN2IFP(tp)->if_type != tunp->type)
1623 			return (EPROTOTYPE);
1624 		TUN_LOCK(tp);
1625 		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
1626 			strlcpy(ifr.ifr_name, if_name(TUN2IFP(tp)), IFNAMSIZ);
1627 			ifr.ifr_mtu = tunp->mtu;
1628 			CURVNET_SET(TUN2IFP(tp)->if_vnet);
1629 			error = ifhwioctl(SIOCSIFMTU, TUN2IFP(tp),
1630 			    (caddr_t)&ifr, td);
1631 			CURVNET_RESTORE();
1632 			if (error) {
1633 				TUN_UNLOCK(tp);
1634 				return (error);
1635 			}
1636 		}
1637 		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
1638 		TUN_UNLOCK(tp);
1639 		break;
1640 	case TUNGIFINFO:
1641 		tunp = (struct tuninfo *)data;
1642 		TUN_LOCK(tp);
1643 		tunp->mtu = TUN2IFP(tp)->if_mtu;
1644 		tunp->type = TUN2IFP(tp)->if_type;
1645 		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
1646 		TUN_UNLOCK(tp);
1647 		break;
1648 	case TUNSDEBUG:
1649 		tundebug = *(int *)data;
1650 		break;
1651 	case TUNGDEBUG:
1652 		*(int *)data = tundebug;
1653 		break;
1654 	case FIONBIO:
1655 		break;
1656 	case FIOASYNC:
1657 		TUN_LOCK(tp);
1658 		if (*(int *)data)
1659 			tp->tun_flags |= TUN_ASYNC;
1660 		else
1661 			tp->tun_flags &= ~TUN_ASYNC;
1662 		TUN_UNLOCK(tp);
1663 		break;
1664 	case FIONREAD:
1665 		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
1666 			struct mbuf *mb;
1667 			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
1668 			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
1669 			for (*(int *)data = 0; mb != NULL; mb = mb->m_next)
1670 				*(int *)data += mb->m_len;
1671 			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
1672 		} else
1673 			*(int *)data = 0;
1674 		break;
1675 	case FIOSETOWN:
1676 		return (fsetown(*(int *)data, &tp->tun_sigio));
1677 
1678 	case FIOGETOWN:
1679 		*(int *)data = fgetown(&tp->tun_sigio);
1680 		return (0);
1681 
1682 	/* This is deprecated, FIOSETOWN should be used instead. */
1683 	case TIOCSPGRP:
1684 		return (fsetown(-(*(int *)data), &tp->tun_sigio));
1685 
1686 	/* This is deprecated, FIOGETOWN should be used instead. */
1687 	case TIOCGPGRP:
1688 		*(int *)data = -fgetown(&tp->tun_sigio);
1689 		return (0);
1690 
1691 	default:
1692 		return (ENOTTY);
1693 	}
1694 	return (0);
1695 }
1696 
1697 /*
1698  * The cdevsw read interface - reads a packet at a time, or at
1699  * least as much of a packet as can be read.
1700  */
1701 static	int
1702 tunread(struct cdev *dev, struct uio *uio, int flag)
1703 {
1704 	struct tuntap_softc *tp = dev->si_drv1;
1705 	struct ifnet	*ifp = TUN2IFP(tp);
1706 	struct mbuf	*m;
1707 	size_t		len;
1708 	int		error = 0;
1709 
1710 	TUNDEBUG (ifp, "read\n");
1711 	TUN_LOCK(tp);
1712 	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
1713 		TUN_UNLOCK(tp);
1714 		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
1715 		return (EHOSTDOWN);
1716 	}
1717 
1718 	tp->tun_flags &= ~TUN_RWAIT;
1719 
1720 	for (;;) {
1721 		IFQ_DEQUEUE(&ifp->if_snd, m);
1722 		if (m != NULL)
1723 			break;
1724 		if (flag & O_NONBLOCK) {
1725 			TUN_UNLOCK(tp);
1726 			return (EWOULDBLOCK);
1727 		}
1728 		tp->tun_flags |= TUN_RWAIT;
1729 		error = mtx_sleep(tp, &tp->tun_mtx, PCATCH | (PZERO + 1),
1730 		    "tunread", 0);
1731 		if (error != 0) {
1732 			TUN_UNLOCK(tp);
1733 			return (error);
1734 		}
1735 	}
1736 	TUN_UNLOCK(tp);
1737 
1738 	if ((tp->tun_flags & TUN_L2) != 0)
1739 		BPF_MTAP(ifp, m);
1740 
1741 	len = min(tp->tun_vhdrlen, uio->uio_resid);
1742 	if (len > 0) {
1743 		struct virtio_net_hdr_mrg_rxbuf vhdr;
1744 
1745 		bzero(&vhdr, sizeof(vhdr));
1746 		if (m->m_pkthdr.csum_flags & TAP_ALL_OFFLOAD) {
1747 			m = virtio_net_tx_offload(ifp, m, false, &vhdr.hdr);
1748 		}
1749 
1750 		TUNDEBUG(ifp, "txvhdr: f %u, gt %u, hl %u, "
1751 		    "gs %u, cs %u, co %u\n", vhdr.hdr.flags,
1752 		    vhdr.hdr.gso_type, vhdr.hdr.hdr_len,
1753 		    vhdr.hdr.gso_size, vhdr.hdr.csum_start,
1754 		    vhdr.hdr.csum_offset);
1755 		error = uiomove(&vhdr, len, uio);
1756 	}
1757 
1758 	while (m && uio->uio_resid > 0 && error == 0) {
1759 		len = min(uio->uio_resid, m->m_len);
1760 		if (len != 0)
1761 			error = uiomove(mtod(m, void *), len, uio);
1762 		m = m_free(m);
1763 	}
1764 
1765 	if (m) {
1766 		TUNDEBUG(ifp, "Dropping mbuf\n");
1767 		m_freem(m);
1768 	}
1769 	return (error);
1770 }
1771 
1772 static int
1773 tunwrite_l2(struct tuntap_softc *tp, struct mbuf *m,
1774 	    struct virtio_net_hdr_mrg_rxbuf *vhdr)
1775 {
1776 	struct epoch_tracker et;
1777 	struct ether_header *eh;
1778 	struct ifnet *ifp;
1779 
1780 	ifp = TUN2IFP(tp);
1781 
1782 	/*
1783 	 * Only pass a unicast frame to ether_input(), if it would
1784 	 * actually have been received by non-virtual hardware.
1785 	 */
1786 	if (m->m_len < sizeof(struct ether_header)) {
1787 		m_freem(m);
1788 		return (0);
1789 	}
1790 
1791 	eh = mtod(m, struct ether_header *);
1792 
1793 	if (eh && (ifp->if_flags & IFF_PROMISC) == 0 &&
1794 	    !ETHER_IS_MULTICAST(eh->ether_dhost) &&
1795 	    bcmp(eh->ether_dhost, IF_LLADDR(ifp), ETHER_ADDR_LEN) != 0) {
1796 		m_freem(m);
1797 		return (0);
1798 	}
1799 
1800 	if (vhdr != NULL && virtio_net_rx_csum(m, &vhdr->hdr)) {
1801 		m_freem(m);
1802 		return (0);
1803 	}
1804 
1805 	/* Pass packet up to parent. */
1806 	CURVNET_SET(ifp->if_vnet);
1807 	NET_EPOCH_ENTER(et);
1808 	(*ifp->if_input)(ifp, m);
1809 	NET_EPOCH_EXIT(et);
1810 	CURVNET_RESTORE();
1811 	/* ibytes are counted in parent */
1812 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1813 	return (0);
1814 }
1815 
1816 static int
1817 tunwrite_l3(struct tuntap_softc *tp, struct mbuf *m)
1818 {
1819 	struct epoch_tracker et;
1820 	struct ifnet *ifp;
1821 	int family, isr;
1822 
1823 	ifp = TUN2IFP(tp);
1824 	/* Could be unlocked read? */
1825 	TUN_LOCK(tp);
1826 	if (tp->tun_flags & TUN_IFHEAD) {
1827 		TUN_UNLOCK(tp);
1828 		if (m->m_len < sizeof(family) &&
1829 		(m = m_pullup(m, sizeof(family))) == NULL)
1830 			return (ENOBUFS);
1831 		family = ntohl(*mtod(m, u_int32_t *));
1832 		m_adj(m, sizeof(family));
1833 	} else {
1834 		TUN_UNLOCK(tp);
1835 		family = AF_INET;
1836 	}
1837 
1838 	BPF_MTAP2(ifp, &family, sizeof(family), m);
1839 
1840 	switch (family) {
1841 #ifdef INET
1842 	case AF_INET:
1843 		isr = NETISR_IP;
1844 		break;
1845 #endif
1846 #ifdef INET6
1847 	case AF_INET6:
1848 		isr = NETISR_IPV6;
1849 		break;
1850 #endif
1851 	default:
1852 		m_freem(m);
1853 		return (EAFNOSUPPORT);
1854 	}
1855 	random_harvest_queue(m, sizeof(*m), RANDOM_NET_TUN);
1856 	if_inc_counter(ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
1857 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1858 	CURVNET_SET(ifp->if_vnet);
1859 	M_SETFIB(m, ifp->if_fib);
1860 	NET_EPOCH_ENTER(et);
1861 	netisr_dispatch(isr, m);
1862 	NET_EPOCH_EXIT(et);
1863 	CURVNET_RESTORE();
1864 	return (0);
1865 }
1866 
1867 /*
1868  * the cdevsw write interface - an atomic write is a packet - or else!
1869  */
1870 static	int
1871 tunwrite(struct cdev *dev, struct uio *uio, int flag)
1872 {
1873 	struct virtio_net_hdr_mrg_rxbuf vhdr;
1874 	struct tuntap_softc *tp;
1875 	struct ifnet	*ifp;
1876 	struct mbuf	*m;
1877 	uint32_t	mru;
1878 	int		align, vhdrlen, error;
1879 	bool		l2tun;
1880 
1881 	tp = dev->si_drv1;
1882 	ifp = TUN2IFP(tp);
1883 	TUNDEBUG(ifp, "tunwrite\n");
1884 	if ((ifp->if_flags & IFF_UP) != IFF_UP)
1885 		/* ignore silently */
1886 		return (0);
1887 
1888 	if (uio->uio_resid == 0)
1889 		return (0);
1890 
1891 	l2tun = (tp->tun_flags & TUN_L2) != 0;
1892 	mru = l2tun ? TAPMRU : TUNMRU;
1893 	vhdrlen = tp->tun_vhdrlen;
1894 	align = 0;
1895 	if (l2tun) {
1896 		align = ETHER_ALIGN;
1897 		mru += vhdrlen;
1898 	} else if ((tp->tun_flags & TUN_IFHEAD) != 0)
1899 		mru += sizeof(uint32_t);	/* family */
1900 	if (uio->uio_resid < 0 || uio->uio_resid > mru) {
1901 		TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
1902 		return (EIO);
1903 	}
1904 
1905 	if (vhdrlen > 0) {
1906 		error = uiomove(&vhdr, vhdrlen, uio);
1907 		if (error != 0)
1908 			return (error);
1909 		TUNDEBUG(ifp, "txvhdr: f %u, gt %u, hl %u, "
1910 		    "gs %u, cs %u, co %u\n", vhdr.hdr.flags,
1911 		    vhdr.hdr.gso_type, vhdr.hdr.hdr_len,
1912 		    vhdr.hdr.gso_size, vhdr.hdr.csum_start,
1913 		    vhdr.hdr.csum_offset);
1914 	}
1915 
1916 	if ((m = m_uiotombuf(uio, M_NOWAIT, 0, align, M_PKTHDR)) == NULL) {
1917 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1918 		return (ENOBUFS);
1919 	}
1920 
1921 	m->m_pkthdr.rcvif = ifp;
1922 #ifdef MAC
1923 	mac_ifnet_create_mbuf(ifp, m);
1924 #endif
1925 
1926 	if (l2tun)
1927 		return (tunwrite_l2(tp, m, vhdrlen > 0 ? &vhdr : NULL));
1928 
1929 	return (tunwrite_l3(tp, m));
1930 }
1931 
1932 /*
1933  * tunpoll - the poll interface, this is only useful on reads
1934  * really. The write detect always returns true, write never blocks
1935  * anyway, it either accepts the packet or drops it.
1936  */
1937 static	int
1938 tunpoll(struct cdev *dev, int events, struct thread *td)
1939 {
1940 	struct tuntap_softc *tp = dev->si_drv1;
1941 	struct ifnet	*ifp = TUN2IFP(tp);
1942 	int		revents = 0;
1943 
1944 	TUNDEBUG(ifp, "tunpoll\n");
1945 
1946 	if (events & (POLLIN | POLLRDNORM)) {
1947 		IFQ_LOCK(&ifp->if_snd);
1948 		if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
1949 			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
1950 			revents |= events & (POLLIN | POLLRDNORM);
1951 		} else {
1952 			TUNDEBUG(ifp, "tunpoll waiting\n");
1953 			selrecord(td, &tp->tun_rsel);
1954 		}
1955 		IFQ_UNLOCK(&ifp->if_snd);
1956 	}
1957 	revents |= events & (POLLOUT | POLLWRNORM);
1958 
1959 	return (revents);
1960 }
1961 
1962 /*
1963  * tunkqfilter - support for the kevent() system call.
1964  */
1965 static int
1966 tunkqfilter(struct cdev *dev, struct knote *kn)
1967 {
1968 	struct tuntap_softc	*tp = dev->si_drv1;
1969 	struct ifnet	*ifp = TUN2IFP(tp);
1970 
1971 	switch(kn->kn_filter) {
1972 	case EVFILT_READ:
1973 		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
1974 		    ifp->if_xname, dev2unit(dev));
1975 		kn->kn_fop = &tun_read_filterops;
1976 		break;
1977 
1978 	case EVFILT_WRITE:
1979 		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
1980 		    ifp->if_xname, dev2unit(dev));
1981 		kn->kn_fop = &tun_write_filterops;
1982 		break;
1983 
1984 	default:
1985 		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1986 		    ifp->if_xname, dev2unit(dev));
1987 		return(EINVAL);
1988 	}
1989 
1990 	kn->kn_hook = tp;
1991 	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1992 
1993 	return (0);
1994 }
1995 
1996 /*
1997  * Return true of there is data in the interface queue.
1998  */
1999 static int
2000 tunkqread(struct knote *kn, long hint)
2001 {
2002 	int			ret;
2003 	struct tuntap_softc	*tp = kn->kn_hook;
2004 	struct cdev		*dev = tp->tun_dev;
2005 	struct ifnet	*ifp = TUN2IFP(tp);
2006 
2007 	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
2008 		TUNDEBUG(ifp,
2009 		    "%s have data in the queue.  Len = %d, minor = %#x\n",
2010 		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
2011 		ret = 1;
2012 	} else {
2013 		TUNDEBUG(ifp,
2014 		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
2015 		    dev2unit(dev));
2016 		ret = 0;
2017 	}
2018 
2019 	return (ret);
2020 }
2021 
2022 /*
2023  * Always can write, always return MTU in kn->data.
2024  */
2025 static int
2026 tunkqwrite(struct knote *kn, long hint)
2027 {
2028 	struct tuntap_softc	*tp = kn->kn_hook;
2029 	struct ifnet	*ifp = TUN2IFP(tp);
2030 
2031 	kn->kn_data = ifp->if_mtu;
2032 
2033 	return (1);
2034 }
2035 
2036 static void
2037 tunkqdetach(struct knote *kn)
2038 {
2039 	struct tuntap_softc	*tp = kn->kn_hook;
2040 
2041 	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
2042 }
2043