xref: /freebsd-12.1/sys/net/if_tun.c (revision b3fcb59d)
1 /*	$NetBSD: if_tun.c,v 1.14 1994/06/29 06:36:25 cgd Exp $	*/
2 
3 /*-
4  * Copyright (c) 1988, Julian Onions <[email protected]>
5  * Nottingham University 1987.
6  *
7  * This source may be freely distributed, however I would be interested
8  * in any changes that are made.
9  *
10  * This driver takes packets off the IP i/f and hands them up to a
11  * user process to have its wicked way with. This driver has it's
12  * roots in a similar driver written by Phil Cockcroft (formerly) at
13  * UCL. This driver is based much more on read/write/poll mode of
14  * operation though.
15  *
16  * $FreeBSD$
17  */
18 
19 #include "opt_inet.h"
20 #include "opt_inet6.h"
21 
22 #include <sys/param.h>
23 #include <sys/lock.h>
24 #include <sys/priv.h>
25 #include <sys/proc.h>
26 #include <sys/systm.h>
27 #include <sys/jail.h>
28 #include <sys/mbuf.h>
29 #include <sys/module.h>
30 #include <sys/socket.h>
31 #include <sys/fcntl.h>
32 #include <sys/filio.h>
33 #include <sys/sockio.h>
34 #include <sys/sx.h>
35 #include <sys/ttycom.h>
36 #include <sys/poll.h>
37 #include <sys/selinfo.h>
38 #include <sys/signalvar.h>
39 #include <sys/filedesc.h>
40 #include <sys/kernel.h>
41 #include <sys/sysctl.h>
42 #include <sys/conf.h>
43 #include <sys/uio.h>
44 #include <sys/malloc.h>
45 #include <sys/random.h>
46 #include <sys/ctype.h>
47 
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_clone.h>
51 #include <net/if_types.h>
52 #include <net/netisr.h>
53 #include <net/route.h>
54 #include <net/vnet.h>
55 #ifdef INET
56 #include <netinet/in.h>
57 #endif
58 #include <net/bpf.h>
59 #include <net/if_tun.h>
60 
61 #include <sys/queue.h>
62 #include <sys/condvar.h>
63 
64 #include <security/mac/mac_framework.h>
65 
66 /*
67  * tun_list is protected by global tunmtx.  Other mutable fields are
68  * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
69  * static for the duration of a tunnel interface.
70  */
71 struct tun_softc {
72 	TAILQ_ENTRY(tun_softc)	tun_list;
73 	struct cdev *tun_dev;
74 	u_short	tun_flags;		/* misc flags */
75 #define	TUN_OPEN	0x0001
76 #define	TUN_INITED	0x0002
77 #define	TUN_RCOLL	0x0004
78 #define	TUN_IASET	0x0008
79 #define	TUN_DSTADDR	0x0010
80 #define	TUN_LMODE	0x0020
81 #define	TUN_RWAIT	0x0040
82 #define	TUN_ASYNC	0x0080
83 #define	TUN_IFHEAD	0x0100
84 #define	TUN_DYING	0x0200
85 
86 #define TUN_READY       (TUN_OPEN | TUN_INITED)
87 
88 	pid_t	tun_pid;		/* owning pid */
89 	struct	ifnet *tun_ifp;		/* the interface */
90 	struct  sigio *tun_sigio;	/* information for async I/O */
91 	struct	selinfo	tun_rsel;	/* read select */
92 	struct mtx	tun_mtx;	/* protect mutable softc fields */
93 	struct cv	tun_cv;		/* protect against ref'd dev destroy */
94 };
95 #define TUN2IFP(sc)	((sc)->tun_ifp)
96 
97 #define TUNDEBUG	if (tundebug) if_printf
98 
99 /*
100  * All mutable global variables in if_tun are locked using tunmtx, with
101  * the exception of tundebug, which is used unlocked, and tunclones,
102  * which is static after setup.
103  */
104 static struct mtx tunmtx;
105 static eventhandler_tag tag;
106 static const char tunname[] = "tun";
107 static MALLOC_DEFINE(M_TUN, tunname, "Tunnel Interface");
108 static int tundebug = 0;
109 static int tundclone = 1;
110 static struct clonedevs *tunclones;
111 static TAILQ_HEAD(,tun_softc)	tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
112 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
113 
114 static struct sx tun_ioctl_sx;
115 SX_SYSINIT(tun_ioctl_sx, &tun_ioctl_sx, "tun_ioctl");
116 
117 SYSCTL_DECL(_net_link);
118 static SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
119     "IP tunnel software network interface.");
120 SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tundclone, 0,
121     "Enable legacy devfs interface creation.");
122 
123 static void	tunclone(void *arg, struct ucred *cred, char *name,
124 		    int namelen, struct cdev **dev);
125 static void	tuncreate(const char *name, struct cdev *dev);
126 static int	tunifioctl(struct ifnet *, u_long, caddr_t);
127 static void	tuninit(struct ifnet *);
128 static int	tunmodevent(module_t, int, void *);
129 static int	tunoutput(struct ifnet *, struct mbuf *,
130 		    const struct sockaddr *, struct route *ro);
131 static void	tunstart(struct ifnet *);
132 
133 static int	tun_clone_match(struct if_clone *ifc, const char *name);
134 static int	tun_clone_create(struct if_clone *, char *, size_t, caddr_t);
135 static int	tun_clone_destroy(struct if_clone *, struct ifnet *);
136 static struct unrhdr	*tun_unrhdr;
137 VNET_DEFINE_STATIC(struct if_clone *, tun_cloner);
138 #define V_tun_cloner VNET(tun_cloner)
139 
140 static d_open_t		tunopen;
141 static d_close_t	tunclose;
142 static d_read_t		tunread;
143 static d_write_t	tunwrite;
144 static d_ioctl_t	tunioctl;
145 static d_poll_t		tunpoll;
146 static d_kqfilter_t	tunkqfilter;
147 
148 static int		tunkqread(struct knote *, long);
149 static int		tunkqwrite(struct knote *, long);
150 static void		tunkqdetach(struct knote *);
151 
152 static struct filterops tun_read_filterops = {
153 	.f_isfd =	1,
154 	.f_attach =	NULL,
155 	.f_detach =	tunkqdetach,
156 	.f_event =	tunkqread,
157 };
158 
159 static struct filterops tun_write_filterops = {
160 	.f_isfd =	1,
161 	.f_attach =	NULL,
162 	.f_detach =	tunkqdetach,
163 	.f_event =	tunkqwrite,
164 };
165 
166 static struct cdevsw tun_cdevsw = {
167 	.d_version =	D_VERSION,
168 	.d_flags =	D_NEEDMINOR,
169 	.d_open =	tunopen,
170 	.d_close =	tunclose,
171 	.d_read =	tunread,
172 	.d_write =	tunwrite,
173 	.d_ioctl =	tunioctl,
174 	.d_poll =	tunpoll,
175 	.d_kqfilter =	tunkqfilter,
176 	.d_name =	tunname,
177 };
178 
179 static int
180 tun_clone_match(struct if_clone *ifc, const char *name)
181 {
182 	if (strncmp(tunname, name, 3) == 0 &&
183 	    (name[3] == '\0' || isdigit(name[3])))
184 		return (1);
185 
186 	return (0);
187 }
188 
189 static int
190 tun_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
191 {
192 	struct cdev *dev;
193 	int err, unit, i;
194 
195 	err = ifc_name2unit(name, &unit);
196 	if (err != 0)
197 		return (err);
198 
199 	if (unit != -1) {
200 		/* If this unit number is still available that/s okay. */
201 		if (alloc_unr_specific(tun_unrhdr, unit) == -1)
202 			return (EEXIST);
203 	} else {
204 		unit = alloc_unr(tun_unrhdr);
205 	}
206 
207 	snprintf(name, IFNAMSIZ, "%s%d", tunname, unit);
208 
209 	/* find any existing device, or allocate new unit number */
210 	i = clone_create(&tunclones, &tun_cdevsw, &unit, &dev, 0);
211 	if (i) {
212 		/* No preexisting struct cdev *, create one */
213 		dev = make_dev(&tun_cdevsw, unit,
214 		    UID_UUCP, GID_DIALER, 0600, "%s%d", tunname, unit);
215 	}
216 	tuncreate(tunname, dev);
217 
218 	return (0);
219 }
220 
221 static void
222 tunclone(void *arg, struct ucred *cred, char *name, int namelen,
223     struct cdev **dev)
224 {
225 	char devname[SPECNAMELEN + 1];
226 	int u, i, append_unit;
227 
228 	if (*dev != NULL)
229 		return;
230 
231 	/*
232 	 * If tun cloning is enabled, only the superuser can create an
233 	 * interface.
234 	 */
235 	if (!tundclone || priv_check_cred(cred, PRIV_NET_IFCREATE, 0) != 0)
236 		return;
237 
238 	if (strcmp(name, tunname) == 0) {
239 		u = -1;
240 	} else if (dev_stdclone(name, NULL, tunname, &u) != 1)
241 		return;	/* Don't recognise the name */
242 	if (u != -1 && u > IF_MAXUNIT)
243 		return;	/* Unit number too high */
244 
245 	if (u == -1)
246 		append_unit = 1;
247 	else
248 		append_unit = 0;
249 
250 	CURVNET_SET(CRED_TO_VNET(cred));
251 	/* find any existing device, or allocate new unit number */
252 	i = clone_create(&tunclones, &tun_cdevsw, &u, dev, 0);
253 	if (i) {
254 		if (append_unit) {
255 			namelen = snprintf(devname, sizeof(devname), "%s%d",
256 			    name, u);
257 			name = devname;
258 		}
259 		/* No preexisting struct cdev *, create one */
260 		*dev = make_dev_credf(MAKEDEV_REF, &tun_cdevsw, u, cred,
261 		    UID_UUCP, GID_DIALER, 0600, "%s", name);
262 	}
263 
264 	if_clone_create(name, namelen, NULL);
265 	CURVNET_RESTORE();
266 }
267 
268 static void
269 tun_destroy(struct tun_softc *tp)
270 {
271 	struct cdev *dev;
272 
273 	mtx_lock(&tp->tun_mtx);
274 	tp->tun_flags |= TUN_DYING;
275 	if ((tp->tun_flags & TUN_OPEN) != 0)
276 		cv_wait_unlock(&tp->tun_cv, &tp->tun_mtx);
277 	else
278 		mtx_unlock(&tp->tun_mtx);
279 
280 	CURVNET_SET(TUN2IFP(tp)->if_vnet);
281 
282 	dev = tp->tun_dev;
283 	bpfdetach(TUN2IFP(tp));
284 	if_detach(TUN2IFP(tp));
285 
286 	sx_xlock(&tun_ioctl_sx);
287 	TUN2IFP(tp)->if_softc = NULL;
288 	sx_xunlock(&tun_ioctl_sx);
289 
290 	free_unr(tun_unrhdr, TUN2IFP(tp)->if_dunit);
291 	if_free(TUN2IFP(tp));
292 	destroy_dev(dev);
293 	seldrain(&tp->tun_rsel);
294 	knlist_clear(&tp->tun_rsel.si_note, 0);
295 	knlist_destroy(&tp->tun_rsel.si_note);
296 	mtx_destroy(&tp->tun_mtx);
297 	cv_destroy(&tp->tun_cv);
298 	free(tp, M_TUN);
299 	CURVNET_RESTORE();
300 }
301 
302 static int
303 tun_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
304 {
305 	struct tun_softc *tp = ifp->if_softc;
306 
307 	mtx_lock(&tunmtx);
308 	TAILQ_REMOVE(&tunhead, tp, tun_list);
309 	mtx_unlock(&tunmtx);
310 	tun_destroy(tp);
311 
312 	return (0);
313 }
314 
315 static void
316 vnet_tun_init(const void *unused __unused)
317 {
318 	V_tun_cloner = if_clone_advanced(tunname, 0, tun_clone_match,
319 			tun_clone_create, tun_clone_destroy);
320 }
321 VNET_SYSINIT(vnet_tun_init, SI_SUB_PROTO_IF, SI_ORDER_ANY,
322 		vnet_tun_init, NULL);
323 
324 static void
325 vnet_tun_uninit(const void *unused __unused)
326 {
327 	if_clone_detach(V_tun_cloner);
328 }
329 VNET_SYSUNINIT(vnet_tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY,
330     vnet_tun_uninit, NULL);
331 
332 static void
333 tun_uninit(const void *unused __unused)
334 {
335 	struct tun_softc *tp;
336 
337 	EVENTHANDLER_DEREGISTER(dev_clone, tag);
338 	drain_dev_clone_events();
339 
340 	mtx_lock(&tunmtx);
341 	while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
342 		TAILQ_REMOVE(&tunhead, tp, tun_list);
343 		mtx_unlock(&tunmtx);
344 		tun_destroy(tp);
345 		mtx_lock(&tunmtx);
346 	}
347 	mtx_unlock(&tunmtx);
348 	delete_unrhdr(tun_unrhdr);
349 	clone_cleanup(&tunclones);
350 	mtx_destroy(&tunmtx);
351 }
352 SYSUNINIT(tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY, tun_uninit, NULL);
353 
354 static int
355 tunmodevent(module_t mod, int type, void *data)
356 {
357 
358 	switch (type) {
359 	case MOD_LOAD:
360 		mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
361 		clone_setup(&tunclones);
362 		tun_unrhdr = new_unrhdr(0, IF_MAXUNIT, &tunmtx);
363 		tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
364 		if (tag == NULL)
365 			return (ENOMEM);
366 		break;
367 	case MOD_UNLOAD:
368 		/* See tun_uninit, so it's done after the vnet_sysuninit() */
369 		break;
370 	default:
371 		return EOPNOTSUPP;
372 	}
373 	return 0;
374 }
375 
376 static moduledata_t tun_mod = {
377 	"if_tun",
378 	tunmodevent,
379 	0
380 };
381 
382 DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
383 MODULE_VERSION(if_tun, 1);
384 
385 static void
386 tunstart(struct ifnet *ifp)
387 {
388 	struct tun_softc *tp = ifp->if_softc;
389 	struct mbuf *m;
390 
391 	TUNDEBUG(ifp,"%s starting\n", ifp->if_xname);
392 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
393 		IFQ_LOCK(&ifp->if_snd);
394 		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
395 		if (m == NULL) {
396 			IFQ_UNLOCK(&ifp->if_snd);
397 			return;
398 		}
399 		IFQ_UNLOCK(&ifp->if_snd);
400 	}
401 
402 	mtx_lock(&tp->tun_mtx);
403 	if (tp->tun_flags & TUN_RWAIT) {
404 		tp->tun_flags &= ~TUN_RWAIT;
405 		wakeup(tp);
406 	}
407 	selwakeuppri(&tp->tun_rsel, PZERO + 1);
408 	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
409 	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
410 		mtx_unlock(&tp->tun_mtx);
411 		pgsigio(&tp->tun_sigio, SIGIO, 0);
412 	} else
413 		mtx_unlock(&tp->tun_mtx);
414 }
415 
416 /* XXX: should return an error code so it can fail. */
417 static void
418 tuncreate(const char *name, struct cdev *dev)
419 {
420 	struct tun_softc *sc;
421 	struct ifnet *ifp;
422 
423 	sc = malloc(sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
424 	mtx_init(&sc->tun_mtx, "tun_mtx", NULL, MTX_DEF);
425 	cv_init(&sc->tun_cv, "tun_condvar");
426 	sc->tun_flags = TUN_INITED;
427 	sc->tun_dev = dev;
428 	mtx_lock(&tunmtx);
429 	TAILQ_INSERT_TAIL(&tunhead, sc, tun_list);
430 	mtx_unlock(&tunmtx);
431 
432 	ifp = sc->tun_ifp = if_alloc(IFT_PPP);
433 	if (ifp == NULL)
434 		panic("%s%d: failed to if_alloc() interface.\n",
435 		    name, dev2unit(dev));
436 	if_initname(ifp, name, dev2unit(dev));
437 	ifp->if_mtu = TUNMTU;
438 	ifp->if_ioctl = tunifioctl;
439 	ifp->if_output = tunoutput;
440 	ifp->if_start = tunstart;
441 	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
442 	ifp->if_softc = sc;
443 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
444 	ifp->if_snd.ifq_drv_maxlen = 0;
445 	IFQ_SET_READY(&ifp->if_snd);
446 	knlist_init_mtx(&sc->tun_rsel.si_note, &sc->tun_mtx);
447 	ifp->if_capabilities |= IFCAP_LINKSTATE;
448 	ifp->if_capenable |= IFCAP_LINKSTATE;
449 
450 	if_attach(ifp);
451 	bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
452 	dev->si_drv1 = sc;
453 	TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
454 	    ifp->if_xname, dev2unit(dev));
455 }
456 
457 static int
458 tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
459 {
460 	struct ifnet	*ifp;
461 	struct tun_softc *tp;
462 
463 	/*
464 	 * XXXRW: Non-atomic test and set of dev->si_drv1 requires
465 	 * synchronization.
466 	 */
467 	tp = dev->si_drv1;
468 	if (!tp) {
469 		tuncreate(tunname, dev);
470 		tp = dev->si_drv1;
471 	}
472 
473 	mtx_lock(&tp->tun_mtx);
474 	if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) {
475 		mtx_unlock(&tp->tun_mtx);
476 		return (EBUSY);
477 	}
478 
479 	tp->tun_pid = td->td_proc->p_pid;
480 	tp->tun_flags |= TUN_OPEN;
481 	ifp = TUN2IFP(tp);
482 	if_link_state_change(ifp, LINK_STATE_UP);
483 	TUNDEBUG(ifp, "open\n");
484 	mtx_unlock(&tp->tun_mtx);
485 
486 	return (0);
487 }
488 
489 /*
490  * tunclose - close the device - mark i/f down & delete
491  * routing info
492  */
493 static	int
494 tunclose(struct cdev *dev, int foo, int bar, struct thread *td)
495 {
496 	struct tun_softc *tp;
497 	struct ifnet *ifp;
498 
499 	tp = dev->si_drv1;
500 	ifp = TUN2IFP(tp);
501 
502 	mtx_lock(&tp->tun_mtx);
503 	/*
504 	 * Simply close the device if this isn't the controlling process.  This
505 	 * may happen if, for instance, the tunnel has been handed off to
506 	 * another process.  The original controller should be able to close it
507 	 * without putting us into an inconsistent state.
508 	 */
509 	if (td->td_proc->p_pid != tp->tun_pid) {
510 		mtx_unlock(&tp->tun_mtx);
511 		return (0);
512 	}
513 
514 	/*
515 	 * junk all pending output
516 	 */
517 	CURVNET_SET(ifp->if_vnet);
518 	IFQ_PURGE(&ifp->if_snd);
519 
520 	if (ifp->if_flags & IFF_UP) {
521 		mtx_unlock(&tp->tun_mtx);
522 		if_down(ifp);
523 		mtx_lock(&tp->tun_mtx);
524 	}
525 
526 	/* Delete all addresses and routes which reference this interface. */
527 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
528 		struct ifaddr *ifa;
529 
530 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
531 		mtx_unlock(&tp->tun_mtx);
532 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
533 			/* deal w/IPv4 PtP destination; unlocked read */
534 			if (ifa->ifa_addr->sa_family == AF_INET) {
535 				rtinit(ifa, (int)RTM_DELETE,
536 				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
537 			} else {
538 				rtinit(ifa, (int)RTM_DELETE, 0);
539 			}
540 		}
541 		if_purgeaddrs(ifp);
542 		mtx_lock(&tp->tun_mtx);
543 	}
544 	if_link_state_change(ifp, LINK_STATE_DOWN);
545 	CURVNET_RESTORE();
546 
547 	funsetown(&tp->tun_sigio);
548 	selwakeuppri(&tp->tun_rsel, PZERO + 1);
549 	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
550 	TUNDEBUG (ifp, "closed\n");
551 	tp->tun_flags &= ~TUN_OPEN;
552 	tp->tun_pid = 0;
553 
554 	cv_broadcast(&tp->tun_cv);
555 	mtx_unlock(&tp->tun_mtx);
556 	return (0);
557 }
558 
559 static void
560 tuninit(struct ifnet *ifp)
561 {
562 	struct tun_softc *tp = ifp->if_softc;
563 #ifdef INET
564 	struct ifaddr *ifa;
565 #endif
566 
567 	TUNDEBUG(ifp, "tuninit\n");
568 
569 	mtx_lock(&tp->tun_mtx);
570 	ifp->if_flags |= IFF_UP;
571 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
572 	getmicrotime(&ifp->if_lastchange);
573 
574 #ifdef INET
575 	if_addr_rlock(ifp);
576 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
577 		if (ifa->ifa_addr->sa_family == AF_INET) {
578 			struct sockaddr_in *si;
579 
580 			si = (struct sockaddr_in *)ifa->ifa_addr;
581 			if (si->sin_addr.s_addr)
582 				tp->tun_flags |= TUN_IASET;
583 
584 			si = (struct sockaddr_in *)ifa->ifa_dstaddr;
585 			if (si && si->sin_addr.s_addr)
586 				tp->tun_flags |= TUN_DSTADDR;
587 		}
588 	}
589 	if_addr_runlock(ifp);
590 #endif
591 	mtx_unlock(&tp->tun_mtx);
592 }
593 
594 /*
595  * Process an ioctl request.
596  */
597 static int
598 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
599 {
600 	struct ifreq *ifr = (struct ifreq *)data;
601 	struct tun_softc *tp;
602 	struct ifstat *ifs;
603 	int		error = 0;
604 
605 	sx_xlock(&tun_ioctl_sx);
606 	tp = ifp->if_softc;
607 	if (tp == NULL) {
608 		error = ENXIO;
609 		goto bad;
610 	}
611 	switch(cmd) {
612 	case SIOCGIFSTATUS:
613 		ifs = (struct ifstat *)data;
614 		mtx_lock(&tp->tun_mtx);
615 		if (tp->tun_pid)
616 			snprintf(ifs->ascii, sizeof(ifs->ascii),
617 			    "\tOpened by PID %d\n", tp->tun_pid);
618 		else
619 			ifs->ascii[0] = '\0';
620 		mtx_unlock(&tp->tun_mtx);
621 		break;
622 	case SIOCSIFADDR:
623 		tuninit(ifp);
624 		TUNDEBUG(ifp, "address set\n");
625 		break;
626 	case SIOCSIFMTU:
627 		ifp->if_mtu = ifr->ifr_mtu;
628 		TUNDEBUG(ifp, "mtu set\n");
629 		break;
630 	case SIOCSIFFLAGS:
631 	case SIOCADDMULTI:
632 	case SIOCDELMULTI:
633 		break;
634 	default:
635 		error = EINVAL;
636 	}
637 bad:
638 	sx_xunlock(&tun_ioctl_sx);
639 	return (error);
640 }
641 
642 /*
643  * tunoutput - queue packets from higher level ready to put out.
644  */
645 static int
646 tunoutput(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst,
647     struct route *ro)
648 {
649 	struct tun_softc *tp = ifp->if_softc;
650 	u_short cached_tun_flags;
651 	int error;
652 	u_int32_t af;
653 
654 	TUNDEBUG (ifp, "tunoutput\n");
655 
656 #ifdef MAC
657 	error = mac_ifnet_check_transmit(ifp, m0);
658 	if (error) {
659 		m_freem(m0);
660 		return (error);
661 	}
662 #endif
663 
664 	/* Could be unlocked read? */
665 	mtx_lock(&tp->tun_mtx);
666 	cached_tun_flags = tp->tun_flags;
667 	mtx_unlock(&tp->tun_mtx);
668 	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
669 		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
670 		m_freem (m0);
671 		return (EHOSTDOWN);
672 	}
673 
674 	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
675 		m_freem (m0);
676 		return (EHOSTDOWN);
677 	}
678 
679 	/* BPF writes need to be handled specially. */
680 	if (dst->sa_family == AF_UNSPEC)
681 		bcopy(dst->sa_data, &af, sizeof(af));
682 	else
683 		af = dst->sa_family;
684 
685 	if (bpf_peers_present(ifp->if_bpf))
686 		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
687 
688 	/* prepend sockaddr? this may abort if the mbuf allocation fails */
689 	if (cached_tun_flags & TUN_LMODE) {
690 		/* allocate space for sockaddr */
691 		M_PREPEND(m0, dst->sa_len, M_NOWAIT);
692 
693 		/* if allocation failed drop packet */
694 		if (m0 == NULL) {
695 			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
696 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
697 			return (ENOBUFS);
698 		} else {
699 			bcopy(dst, m0->m_data, dst->sa_len);
700 		}
701 	}
702 
703 	if (cached_tun_flags & TUN_IFHEAD) {
704 		/* Prepend the address family */
705 		M_PREPEND(m0, 4, M_NOWAIT);
706 
707 		/* if allocation failed drop packet */
708 		if (m0 == NULL) {
709 			if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
710 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
711 			return (ENOBUFS);
712 		} else
713 			*(u_int32_t *)m0->m_data = htonl(af);
714 	} else {
715 #ifdef INET
716 		if (af != AF_INET)
717 #endif
718 		{
719 			m_freem(m0);
720 			return (EAFNOSUPPORT);
721 		}
722 	}
723 
724 	error = (ifp->if_transmit)(ifp, m0);
725 	if (error)
726 		return (ENOBUFS);
727 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
728 	return (0);
729 }
730 
731 /*
732  * the cdevsw interface is now pretty minimal.
733  */
734 static	int
735 tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
736     struct thread *td)
737 {
738 	struct ifreq ifr, *ifrp;
739 	struct tun_softc *tp = dev->si_drv1;
740 	struct tuninfo *tunp;
741 	int error;
742 
743 	switch (cmd) {
744 	case TUNGIFNAME:
745 		ifrp = (struct ifreq *)data;
746 		strlcpy(ifrp->ifr_name, TUN2IFP(tp)->if_xname, IFNAMSIZ);
747 		break;
748 	case TUNSIFINFO:
749 		tunp = (struct tuninfo *)data;
750 		if (TUN2IFP(tp)->if_type != tunp->type)
751 			return (EPROTOTYPE);
752 		mtx_lock(&tp->tun_mtx);
753 		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
754 			strlcpy(ifr.ifr_name, if_name(TUN2IFP(tp)), IFNAMSIZ);
755 			ifr.ifr_mtu = tunp->mtu;
756 			CURVNET_SET(TUN2IFP(tp)->if_vnet);
757 			error = ifhwioctl(SIOCSIFMTU, TUN2IFP(tp),
758 			    (caddr_t)&ifr, td);
759 			CURVNET_RESTORE();
760 			if (error) {
761 				mtx_unlock(&tp->tun_mtx);
762 				return (error);
763 			}
764 		}
765 		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
766 		mtx_unlock(&tp->tun_mtx);
767 		break;
768 	case TUNGIFINFO:
769 		tunp = (struct tuninfo *)data;
770 		mtx_lock(&tp->tun_mtx);
771 		tunp->mtu = TUN2IFP(tp)->if_mtu;
772 		tunp->type = TUN2IFP(tp)->if_type;
773 		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
774 		mtx_unlock(&tp->tun_mtx);
775 		break;
776 	case TUNSDEBUG:
777 		tundebug = *(int *)data;
778 		break;
779 	case TUNGDEBUG:
780 		*(int *)data = tundebug;
781 		break;
782 	case TUNSLMODE:
783 		mtx_lock(&tp->tun_mtx);
784 		if (*(int *)data) {
785 			tp->tun_flags |= TUN_LMODE;
786 			tp->tun_flags &= ~TUN_IFHEAD;
787 		} else
788 			tp->tun_flags &= ~TUN_LMODE;
789 		mtx_unlock(&tp->tun_mtx);
790 		break;
791 	case TUNSIFHEAD:
792 		mtx_lock(&tp->tun_mtx);
793 		if (*(int *)data) {
794 			tp->tun_flags |= TUN_IFHEAD;
795 			tp->tun_flags &= ~TUN_LMODE;
796 		} else
797 			tp->tun_flags &= ~TUN_IFHEAD;
798 		mtx_unlock(&tp->tun_mtx);
799 		break;
800 	case TUNGIFHEAD:
801 		mtx_lock(&tp->tun_mtx);
802 		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
803 		mtx_unlock(&tp->tun_mtx);
804 		break;
805 	case TUNSIFMODE:
806 		/* deny this if UP */
807 		if (TUN2IFP(tp)->if_flags & IFF_UP)
808 			return(EBUSY);
809 
810 		switch (*(int *)data & ~IFF_MULTICAST) {
811 		case IFF_POINTOPOINT:
812 		case IFF_BROADCAST:
813 			mtx_lock(&tp->tun_mtx);
814 			TUN2IFP(tp)->if_flags &=
815 			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
816 			TUN2IFP(tp)->if_flags |= *(int *)data;
817 			mtx_unlock(&tp->tun_mtx);
818 			break;
819 		default:
820 			return(EINVAL);
821 		}
822 		break;
823 	case TUNSIFPID:
824 		mtx_lock(&tp->tun_mtx);
825 		tp->tun_pid = curthread->td_proc->p_pid;
826 		mtx_unlock(&tp->tun_mtx);
827 		break;
828 	case FIONBIO:
829 		break;
830 	case FIOASYNC:
831 		mtx_lock(&tp->tun_mtx);
832 		if (*(int *)data)
833 			tp->tun_flags |= TUN_ASYNC;
834 		else
835 			tp->tun_flags &= ~TUN_ASYNC;
836 		mtx_unlock(&tp->tun_mtx);
837 		break;
838 	case FIONREAD:
839 		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
840 			struct mbuf *mb;
841 			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
842 			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
843 			for (*(int *)data = 0; mb != NULL; mb = mb->m_next)
844 				*(int *)data += mb->m_len;
845 			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
846 		} else
847 			*(int *)data = 0;
848 		break;
849 	case FIOSETOWN:
850 		return (fsetown(*(int *)data, &tp->tun_sigio));
851 
852 	case FIOGETOWN:
853 		*(int *)data = fgetown(&tp->tun_sigio);
854 		return (0);
855 
856 	/* This is deprecated, FIOSETOWN should be used instead. */
857 	case TIOCSPGRP:
858 		return (fsetown(-(*(int *)data), &tp->tun_sigio));
859 
860 	/* This is deprecated, FIOGETOWN should be used instead. */
861 	case TIOCGPGRP:
862 		*(int *)data = -fgetown(&tp->tun_sigio);
863 		return (0);
864 
865 	default:
866 		return (ENOTTY);
867 	}
868 	return (0);
869 }
870 
871 /*
872  * The cdevsw read interface - reads a packet at a time, or at
873  * least as much of a packet as can be read.
874  */
875 static	int
876 tunread(struct cdev *dev, struct uio *uio, int flag)
877 {
878 	struct tun_softc *tp = dev->si_drv1;
879 	struct ifnet	*ifp = TUN2IFP(tp);
880 	struct mbuf	*m;
881 	int		error=0, len;
882 
883 	TUNDEBUG (ifp, "read\n");
884 	mtx_lock(&tp->tun_mtx);
885 	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
886 		mtx_unlock(&tp->tun_mtx);
887 		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
888 		return (EHOSTDOWN);
889 	}
890 
891 	tp->tun_flags &= ~TUN_RWAIT;
892 
893 	do {
894 		IFQ_DEQUEUE(&ifp->if_snd, m);
895 		if (m == NULL) {
896 			if (flag & O_NONBLOCK) {
897 				mtx_unlock(&tp->tun_mtx);
898 				return (EWOULDBLOCK);
899 			}
900 			tp->tun_flags |= TUN_RWAIT;
901 			error = mtx_sleep(tp, &tp->tun_mtx, PCATCH | (PZERO + 1),
902 			    "tunread", 0);
903 			if (error != 0) {
904 				mtx_unlock(&tp->tun_mtx);
905 				return (error);
906 			}
907 		}
908 	} while (m == NULL);
909 	mtx_unlock(&tp->tun_mtx);
910 
911 	while (m && uio->uio_resid > 0 && error == 0) {
912 		len = min(uio->uio_resid, m->m_len);
913 		if (len != 0)
914 			error = uiomove(mtod(m, void *), len, uio);
915 		m = m_free(m);
916 	}
917 
918 	if (m) {
919 		TUNDEBUG(ifp, "Dropping mbuf\n");
920 		m_freem(m);
921 	}
922 	return (error);
923 }
924 
925 /*
926  * the cdevsw write interface - an atomic write is a packet - or else!
927  */
928 static	int
929 tunwrite(struct cdev *dev, struct uio *uio, int flag)
930 {
931 	struct tun_softc *tp = dev->si_drv1;
932 	struct ifnet	*ifp = TUN2IFP(tp);
933 	struct mbuf	*m;
934 	uint32_t	family, mru;
935 	int 		isr;
936 
937 	TUNDEBUG(ifp, "tunwrite\n");
938 
939 	if ((ifp->if_flags & IFF_UP) != IFF_UP)
940 		/* ignore silently */
941 		return (0);
942 
943 	if (uio->uio_resid == 0)
944 		return (0);
945 
946 	mru = TUNMRU;
947 	if (tp->tun_flags & TUN_IFHEAD)
948 		mru += sizeof(family);
949 	if (uio->uio_resid < 0 || uio->uio_resid > mru) {
950 		TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
951 		return (EIO);
952 	}
953 
954 	if ((m = m_uiotombuf(uio, M_NOWAIT, 0, 0, M_PKTHDR)) == NULL) {
955 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
956 		return (ENOBUFS);
957 	}
958 
959 	m->m_pkthdr.rcvif = ifp;
960 #ifdef MAC
961 	mac_ifnet_create_mbuf(ifp, m);
962 #endif
963 
964 	/* Could be unlocked read? */
965 	mtx_lock(&tp->tun_mtx);
966 	if (tp->tun_flags & TUN_IFHEAD) {
967 		mtx_unlock(&tp->tun_mtx);
968 		if (m->m_len < sizeof(family) &&
969 		    (m = m_pullup(m, sizeof(family))) == NULL)
970 			return (ENOBUFS);
971 		family = ntohl(*mtod(m, u_int32_t *));
972 		m_adj(m, sizeof(family));
973 	} else {
974 		mtx_unlock(&tp->tun_mtx);
975 		family = AF_INET;
976 	}
977 
978 	BPF_MTAP2(ifp, &family, sizeof(family), m);
979 
980 	switch (family) {
981 #ifdef INET
982 	case AF_INET:
983 		isr = NETISR_IP;
984 		break;
985 #endif
986 #ifdef INET6
987 	case AF_INET6:
988 		isr = NETISR_IPV6;
989 		break;
990 #endif
991 	default:
992 		m_freem(m);
993 		return (EAFNOSUPPORT);
994 	}
995 	random_harvest_queue(m, sizeof(*m), RANDOM_NET_TUN);
996 	if_inc_counter(ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
997 	if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
998 	CURVNET_SET(ifp->if_vnet);
999 	M_SETFIB(m, ifp->if_fib);
1000 	netisr_dispatch(isr, m);
1001 	CURVNET_RESTORE();
1002 	return (0);
1003 }
1004 
1005 /*
1006  * tunpoll - the poll interface, this is only useful on reads
1007  * really. The write detect always returns true, write never blocks
1008  * anyway, it either accepts the packet or drops it.
1009  */
1010 static	int
1011 tunpoll(struct cdev *dev, int events, struct thread *td)
1012 {
1013 	struct tun_softc *tp = dev->si_drv1;
1014 	struct ifnet	*ifp = TUN2IFP(tp);
1015 	int		revents = 0;
1016 	struct mbuf	*m;
1017 
1018 	TUNDEBUG(ifp, "tunpoll\n");
1019 
1020 	if (events & (POLLIN | POLLRDNORM)) {
1021 		IFQ_LOCK(&ifp->if_snd);
1022 		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
1023 		if (m != NULL) {
1024 			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
1025 			revents |= events & (POLLIN | POLLRDNORM);
1026 		} else {
1027 			TUNDEBUG(ifp, "tunpoll waiting\n");
1028 			selrecord(td, &tp->tun_rsel);
1029 		}
1030 		IFQ_UNLOCK(&ifp->if_snd);
1031 	}
1032 	if (events & (POLLOUT | POLLWRNORM))
1033 		revents |= events & (POLLOUT | POLLWRNORM);
1034 
1035 	return (revents);
1036 }
1037 
1038 /*
1039  * tunkqfilter - support for the kevent() system call.
1040  */
1041 static int
1042 tunkqfilter(struct cdev *dev, struct knote *kn)
1043 {
1044 	struct tun_softc	*tp = dev->si_drv1;
1045 	struct ifnet	*ifp = TUN2IFP(tp);
1046 
1047 	switch(kn->kn_filter) {
1048 	case EVFILT_READ:
1049 		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
1050 		    ifp->if_xname, dev2unit(dev));
1051 		kn->kn_fop = &tun_read_filterops;
1052 		break;
1053 
1054 	case EVFILT_WRITE:
1055 		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
1056 		    ifp->if_xname, dev2unit(dev));
1057 		kn->kn_fop = &tun_write_filterops;
1058 		break;
1059 
1060 	default:
1061 		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1062 		    ifp->if_xname, dev2unit(dev));
1063 		return(EINVAL);
1064 	}
1065 
1066 	kn->kn_hook = tp;
1067 	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1068 
1069 	return (0);
1070 }
1071 
1072 /*
1073  * Return true of there is data in the interface queue.
1074  */
1075 static int
1076 tunkqread(struct knote *kn, long hint)
1077 {
1078 	int			ret;
1079 	struct tun_softc	*tp = kn->kn_hook;
1080 	struct cdev		*dev = tp->tun_dev;
1081 	struct ifnet	*ifp = TUN2IFP(tp);
1082 
1083 	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1084 		TUNDEBUG(ifp,
1085 		    "%s have data in the queue.  Len = %d, minor = %#x\n",
1086 		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1087 		ret = 1;
1088 	} else {
1089 		TUNDEBUG(ifp,
1090 		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
1091 		    dev2unit(dev));
1092 		ret = 0;
1093 	}
1094 
1095 	return (ret);
1096 }
1097 
1098 /*
1099  * Always can write, always return MTU in kn->data.
1100  */
1101 static int
1102 tunkqwrite(struct knote *kn, long hint)
1103 {
1104 	struct tun_softc	*tp = kn->kn_hook;
1105 	struct ifnet	*ifp = TUN2IFP(tp);
1106 
1107 	kn->kn_data = ifp->if_mtu;
1108 
1109 	return (1);
1110 }
1111 
1112 static void
1113 tunkqdetach(struct knote *kn)
1114 {
1115 	struct tun_softc	*tp = kn->kn_hook;
1116 
1117 	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1118 }
1119