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