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