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