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