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