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