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