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