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