if_tun.c revision 184205
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 184205 2008-10-23 15:53:51Z des $
17 */
18
19#include "opt_atalk.h"
20#include "opt_inet.h"
21#include "opt_inet6.h"
22#include "opt_ipx.h"
23#include "opt_mac.h"
24
25#include <sys/param.h>
26#include <sys/priv.h>
27#include <sys/proc.h>
28#include <sys/systm.h>
29#include <sys/mbuf.h>
30#include <sys/module.h>
31#include <sys/socket.h>
32#include <sys/fcntl.h>
33#include <sys/filio.h>
34#include <sys/sockio.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/vimage.h>
47
48#include <net/if.h>
49#include <net/if_clone.h>
50#include <net/if_types.h>
51#include <net/netisr.h>
52#include <net/route.h>
53#ifdef INET
54#include <netinet/in.h>
55#endif
56#include <net/bpf.h>
57#include <net/if_tun.h>
58
59#include <sys/queue.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};
97#define TUN2IFP(sc)	((sc)->tun_ifp)
98
99#define TUNDEBUG	if (tundebug) if_printf
100#define	TUNNAME		"tun"
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 MALLOC_DEFINE(M_TUN, TUNNAME, "Tunnel Interface");
109static int tundebug = 0;
110static int tundclone = 1;
111static struct clonedevs *tunclones;
112static TAILQ_HEAD(,tun_softc)	tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
113SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
114
115SYSCTL_DECL(_net_link);
116SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
117    "IP tunnel software network interface.");
118SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RW, &tundclone, 0,
119    "Enable legacy devfs interface creation.");
120
121TUNABLE_INT("net.link.tun.devfs_cloning", &tundclone);
122
123static void	tunclone(void *arg, struct ucred *cred, char *name,
124		    int namelen, struct cdev **dev);
125static void	tuncreate(const char *name, struct cdev *dev);
126static int	tunifioctl(struct ifnet *, u_long, caddr_t);
127static int	tuninit(struct ifnet *);
128static int	tunmodevent(module_t, int, void *);
129static int	tunoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
130		    struct rtentry *rt);
131static void	tunstart(struct ifnet *);
132
133static int	tun_clone_create(struct if_clone *, int, caddr_t);
134static void	tun_clone_destroy(struct ifnet *);
135
136IFC_SIMPLE_DECLARE(tun, 0);
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_PSEUDO | D_NEEDGIANT | 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", ifc->ifc_name, unit);
189		if (dev != NULL) {
190			dev_ref(dev);
191			dev->si_flags |= SI_CHEAPCLONE;
192		}
193	}
194	tuncreate(ifc->ifc_name, dev);
195
196	return (0);
197}
198
199static void
200tunclone(void *arg, struct ucred *cred, char *name, int namelen,
201    struct cdev **dev)
202{
203	char devname[SPECNAMELEN + 1];
204	int u, i, append_unit;
205
206	if (*dev != NULL)
207		return;
208
209	/*
210	 * If tun cloning is enabled, only the superuser can create an
211	 * interface.
212	 */
213	if (!tundclone || priv_check_cred(cred, PRIV_NET_IFCREATE, 0) != 0)
214		return;
215
216	if (strcmp(name, TUNNAME) == 0) {
217		u = -1;
218	} else if (dev_stdclone(name, NULL, TUNNAME, &u) != 1)
219		return;	/* Don't recognise the name */
220	if (u != -1 && u > IF_MAXUNIT)
221		return;	/* Unit number too high */
222
223	if (u == -1)
224		append_unit = 1;
225	else
226		append_unit = 0;
227
228	CURVNET_SET(TD_TO_VNET(curthread));
229	/* find any existing device, or allocate new unit number */
230	i = clone_create(&tunclones, &tun_cdevsw, &u, dev, 0);
231	if (i) {
232		if (append_unit) {
233			namelen = snprintf(devname, sizeof(devname), "%s%d", name,
234			    u);
235			name = devname;
236		}
237		/* No preexisting struct cdev *, create one */
238		*dev = make_dev(&tun_cdevsw, u,
239		    UID_UUCP, GID_DIALER, 0600, "%s", name);
240		if (*dev != NULL) {
241			dev_ref(*dev);
242			(*dev)->si_flags |= SI_CHEAPCLONE;
243		}
244	}
245
246	if_clone_create(name, namelen, NULL);
247	CURVNET_RESTORE();
248}
249
250static void
251tun_destroy(struct tun_softc *tp)
252{
253	struct cdev *dev;
254
255	/* Unlocked read. */
256	KASSERT((tp->tun_flags & TUN_OPEN) == 0,
257	    ("tununits is out of sync - unit %d", TUN2IFP(tp)->if_dunit));
258
259	CURVNET_SET(TUN2IFP(tp)->if_vnet);
260	dev = tp->tun_dev;
261	bpfdetach(TUN2IFP(tp));
262	if_detach(TUN2IFP(tp));
263	if_free(TUN2IFP(tp));
264	destroy_dev(dev);
265	knlist_destroy(&tp->tun_rsel.si_note);
266	mtx_destroy(&tp->tun_mtx);
267	free(tp, M_TUN);
268	CURVNET_RESTORE();
269}
270
271static void
272tun_clone_destroy(struct ifnet *ifp)
273{
274	struct tun_softc *tp = ifp->if_softc;
275
276	mtx_lock(&tunmtx);
277	TAILQ_REMOVE(&tunhead, tp, tun_list);
278	mtx_unlock(&tunmtx);
279	tun_destroy(tp);
280}
281
282static int
283tunmodevent(module_t mod, int type, void *data)
284{
285	static eventhandler_tag tag;
286	struct tun_softc *tp;
287
288	switch (type) {
289	case MOD_LOAD:
290		mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
291		clone_setup(&tunclones);
292		tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
293		if (tag == NULL)
294			return (ENOMEM);
295		if_clone_attach(&tun_cloner);
296		break;
297	case MOD_UNLOAD:
298		if_clone_detach(&tun_cloner);
299		EVENTHANDLER_DEREGISTER(dev_clone, tag);
300
301		mtx_lock(&tunmtx);
302		while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
303			TAILQ_REMOVE(&tunhead, tp, tun_list);
304			mtx_unlock(&tunmtx);
305			tun_destroy(tp);
306			mtx_lock(&tunmtx);
307		}
308		mtx_unlock(&tunmtx);
309		clone_cleanup(&tunclones);
310		mtx_destroy(&tunmtx);
311		break;
312	default:
313		return EOPNOTSUPP;
314	}
315	return 0;
316}
317
318static moduledata_t tun_mod = {
319	"if_tun",
320	tunmodevent,
321	0
322};
323
324DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
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	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
349		mtx_unlock(&tp->tun_mtx);
350		pgsigio(&tp->tun_sigio, SIGIO, 0);
351	} else
352		mtx_unlock(&tp->tun_mtx);
353	selwakeuppri(&tp->tun_rsel, PZERO + 1);
354	KNOTE_UNLOCKED(&tp->tun_rsel.si_note, 0);
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	dev->si_flags &= ~SI_CHEAPCLONE;
365
366	sc = malloc(sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
367	mtx_init(&sc->tun_mtx, "tun_mtx", NULL, MTX_DEF);
368	sc->tun_flags = TUN_INITED;
369	sc->tun_dev = dev;
370	mtx_lock(&tunmtx);
371	TAILQ_INSERT_TAIL(&tunhead, sc, tun_list);
372	mtx_unlock(&tunmtx);
373
374	ifp = sc->tun_ifp = if_alloc(IFT_PPP);
375	if (ifp == NULL)
376		panic("%s%d: failed to if_alloc() interface.\n",
377		    name, dev2unit(dev));
378	if_initname(ifp, name, dev2unit(dev));
379	ifp->if_mtu = TUNMTU;
380	ifp->if_ioctl = tunifioctl;
381	ifp->if_output = tunoutput;
382	ifp->if_start = tunstart;
383	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
384	ifp->if_softc = sc;
385	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
386	ifp->if_snd.ifq_drv_maxlen = 0;
387	IFQ_SET_READY(&ifp->if_snd);
388	knlist_init(&sc->tun_rsel.si_note, NULL, NULL, NULL, NULL);
389
390	if_attach(ifp);
391	bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
392	dev->si_drv1 = sc;
393	TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
394	    ifp->if_xname, dev2unit(dev));
395}
396
397static int
398tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
399{
400	struct ifnet	*ifp;
401	struct tun_softc *tp;
402
403	/*
404	 * XXXRW: Non-atomic test and set of dev->si_drv1 requires
405	 * synchronization.
406	 */
407	tp = dev->si_drv1;
408	if (!tp) {
409		tuncreate(TUNNAME, dev);
410		tp = dev->si_drv1;
411	}
412
413	/*
414	 * XXXRW: This use of tun_pid is subject to error due to the
415	 * fact that a reference to the tunnel can live beyond the
416	 * death of the process that created it.  Can we replace this
417	 * with a simple busy flag?
418	 */
419	mtx_lock(&tp->tun_mtx);
420	if (tp->tun_pid != 0 && tp->tun_pid != td->td_proc->p_pid) {
421		mtx_unlock(&tp->tun_mtx);
422		return (EBUSY);
423	}
424	tp->tun_pid = td->td_proc->p_pid;
425
426	tp->tun_flags |= TUN_OPEN;
427	mtx_unlock(&tp->tun_mtx);
428	ifp = TUN2IFP(tp);
429	TUNDEBUG(ifp, "open\n");
430
431	return (0);
432}
433
434/*
435 * tunclose - close the device - mark i/f down & delete
436 * routing info
437 */
438static	int
439tunclose(struct cdev *dev, int foo, int bar, struct thread *td)
440{
441	struct tun_softc *tp;
442	struct ifnet *ifp;
443	int s;
444
445	tp = dev->si_drv1;
446	ifp = TUN2IFP(tp);
447
448	mtx_lock(&tp->tun_mtx);
449	tp->tun_flags &= ~TUN_OPEN;
450	tp->tun_pid = 0;
451
452	/*
453	 * junk all pending output
454	 */
455	CURVNET_SET(ifp->if_vnet);
456	s = splimp();
457	IFQ_PURGE(&ifp->if_snd);
458	splx(s);
459	mtx_unlock(&tp->tun_mtx);
460
461	if (ifp->if_flags & IFF_UP) {
462		s = splimp();
463		if_down(ifp);
464		splx(s);
465	}
466
467	/* Delete all addresses and routes which reference this interface. */
468	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
469		struct ifaddr *ifa;
470
471		s = splimp();
472		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
473			/* deal w/IPv4 PtP destination; unlocked read */
474			if (ifa->ifa_addr->sa_family == AF_INET) {
475				rtinit(ifa, (int)RTM_DELETE,
476				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
477			} else {
478				rtinit(ifa, (int)RTM_DELETE, 0);
479			}
480		}
481		if_purgeaddrs(ifp);
482		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
483		splx(s);
484	}
485	CURVNET_RESTORE();
486
487	funsetown(&tp->tun_sigio);
488	selwakeuppri(&tp->tun_rsel, PZERO + 1);
489	KNOTE_UNLOCKED(&tp->tun_rsel.si_note, 0);
490	TUNDEBUG (ifp, "closed\n");
491	return (0);
492}
493
494static int
495tuninit(struct ifnet *ifp)
496{
497	struct tun_softc *tp = ifp->if_softc;
498	struct ifaddr *ifa;
499	int error = 0;
500
501	TUNDEBUG(ifp, "tuninit\n");
502
503	ifp->if_flags |= IFF_UP;
504	ifp->if_drv_flags |= IFF_DRV_RUNNING;
505	getmicrotime(&ifp->if_lastchange);
506
507#ifdef INET
508	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
509		if (ifa->ifa_addr->sa_family == AF_INET) {
510			struct sockaddr_in *si;
511
512			si = (struct sockaddr_in *)ifa->ifa_addr;
513			mtx_lock(&tp->tun_mtx);
514			if (si->sin_addr.s_addr)
515				tp->tun_flags |= TUN_IASET;
516
517			si = (struct sockaddr_in *)ifa->ifa_dstaddr;
518			if (si && si->sin_addr.s_addr)
519				tp->tun_flags |= TUN_DSTADDR;
520			mtx_unlock(&tp->tun_mtx);
521		}
522	}
523#endif
524	return (error);
525}
526
527/*
528 * Process an ioctl request.
529 */
530static int
531tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
532{
533	struct ifreq *ifr = (struct ifreq *)data;
534	struct tun_softc *tp = ifp->if_softc;
535	struct ifstat *ifs;
536	int		error = 0, s;
537
538	s = splimp();
539	switch(cmd) {
540	case SIOCGIFSTATUS:
541		ifs = (struct ifstat *)data;
542		mtx_lock(&tp->tun_mtx);
543		if (tp->tun_pid)
544			sprintf(ifs->ascii + strlen(ifs->ascii),
545			    "\tOpened by PID %d\n", tp->tun_pid);
546		mtx_unlock(&tp->tun_mtx);
547		break;
548	case SIOCSIFADDR:
549		error = tuninit(ifp);
550		TUNDEBUG(ifp, "address set, error=%d\n", error);
551		break;
552	case SIOCSIFDSTADDR:
553		error = tuninit(ifp);
554		TUNDEBUG(ifp, "destination address set, error=%d\n", error);
555		break;
556	case SIOCSIFMTU:
557		ifp->if_mtu = ifr->ifr_mtu;
558		TUNDEBUG(ifp, "mtu set\n");
559		break;
560	case SIOCSIFFLAGS:
561	case SIOCADDMULTI:
562	case SIOCDELMULTI:
563		break;
564	default:
565		error = EINVAL;
566	}
567	splx(s);
568	return (error);
569}
570
571/*
572 * tunoutput - queue packets from higher level ready to put out.
573 */
574static int
575tunoutput(
576	struct ifnet *ifp,
577	struct mbuf *m0,
578	struct sockaddr *dst,
579	struct rtentry *rt)
580{
581	struct tun_softc *tp = ifp->if_softc;
582	u_short cached_tun_flags;
583	int error;
584	u_int32_t af;
585
586	TUNDEBUG (ifp, "tunoutput\n");
587
588#ifdef MAC
589	error = mac_ifnet_check_transmit(ifp, m0);
590	if (error) {
591		m_freem(m0);
592		return (error);
593	}
594#endif
595
596	/* Could be unlocked read? */
597	mtx_lock(&tp->tun_mtx);
598	cached_tun_flags = tp->tun_flags;
599	mtx_unlock(&tp->tun_mtx);
600	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
601		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
602		m_freem (m0);
603		return (EHOSTDOWN);
604	}
605
606	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
607		m_freem (m0);
608		return (EHOSTDOWN);
609	}
610
611	/* BPF writes need to be handled specially. */
612	if (dst->sa_family == AF_UNSPEC) {
613		bcopy(dst->sa_data, &af, sizeof(af));
614		dst->sa_family = af;
615	}
616
617	if (bpf_peers_present(ifp->if_bpf)) {
618		af = dst->sa_family;
619		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
620	}
621
622	/* prepend sockaddr? this may abort if the mbuf allocation fails */
623	if (cached_tun_flags & TUN_LMODE) {
624		/* allocate space for sockaddr */
625		M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
626
627		/* if allocation failed drop packet */
628		if (m0 == NULL) {
629			ifp->if_iqdrops++;
630			ifp->if_oerrors++;
631			return (ENOBUFS);
632		} else {
633			bcopy(dst, m0->m_data, dst->sa_len);
634		}
635	}
636
637	if (cached_tun_flags & TUN_IFHEAD) {
638		/* Prepend the address family */
639		M_PREPEND(m0, 4, M_DONTWAIT);
640
641		/* if allocation failed drop packet */
642		if (m0 == NULL) {
643			ifp->if_iqdrops++;
644			ifp->if_oerrors++;
645			return (ENOBUFS);
646		} else
647			*(u_int32_t *)m0->m_data = htonl(dst->sa_family);
648	} else {
649#ifdef INET
650		if (dst->sa_family != AF_INET)
651#endif
652		{
653			m_freem(m0);
654			return (EAFNOSUPPORT);
655		}
656	}
657
658	IFQ_HANDOFF(ifp, m0, error);
659	if (error) {
660		ifp->if_collisions++;
661		return (ENOBUFS);
662	}
663	ifp->if_opackets++;
664	return (0);
665}
666
667/*
668 * the cdevsw interface is now pretty minimal.
669 */
670static	int
671tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
672{
673	int		s;
674	int		error;
675	struct tun_softc *tp = dev->si_drv1;
676	struct tuninfo *tunp;
677
678	switch (cmd) {
679	case TUNSIFINFO:
680		tunp = (struct tuninfo *)data;
681		if (tunp->mtu < IF_MINMTU)
682			return (EINVAL);
683		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
684			error = priv_check(td, PRIV_NET_SETIFMTU);
685			if (error)
686				return (error);
687		}
688		TUN2IFP(tp)->if_mtu = tunp->mtu;
689		TUN2IFP(tp)->if_type = tunp->type;
690		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
691		break;
692	case TUNGIFINFO:
693		tunp = (struct tuninfo *)data;
694		tunp->mtu = TUN2IFP(tp)->if_mtu;
695		tunp->type = TUN2IFP(tp)->if_type;
696		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
697		break;
698	case TUNSDEBUG:
699		tundebug = *(int *)data;
700		break;
701	case TUNGDEBUG:
702		*(int *)data = tundebug;
703		break;
704	case TUNSLMODE:
705		mtx_lock(&tp->tun_mtx);
706		if (*(int *)data) {
707			tp->tun_flags |= TUN_LMODE;
708			tp->tun_flags &= ~TUN_IFHEAD;
709		} else
710			tp->tun_flags &= ~TUN_LMODE;
711		mtx_unlock(&tp->tun_mtx);
712		break;
713	case TUNSIFHEAD:
714		mtx_lock(&tp->tun_mtx);
715		if (*(int *)data) {
716			tp->tun_flags |= TUN_IFHEAD;
717			tp->tun_flags &= ~TUN_LMODE;
718		} else
719			tp->tun_flags &= ~TUN_IFHEAD;
720		mtx_unlock(&tp->tun_mtx);
721		break;
722	case TUNGIFHEAD:
723		/* Could be unlocked read? */
724		mtx_lock(&tp->tun_mtx);
725		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
726		mtx_unlock(&tp->tun_mtx);
727		break;
728	case TUNSIFMODE:
729		/* deny this if UP */
730		if (TUN2IFP(tp)->if_flags & IFF_UP)
731			return(EBUSY);
732
733		switch (*(int *)data & ~IFF_MULTICAST) {
734		case IFF_POINTOPOINT:
735		case IFF_BROADCAST:
736			TUN2IFP(tp)->if_flags &=
737			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
738			TUN2IFP(tp)->if_flags |= *(int *)data;
739			break;
740		default:
741			return(EINVAL);
742		}
743		break;
744	case TUNSIFPID:
745		mtx_lock(&tp->tun_mtx);
746		tp->tun_pid = curthread->td_proc->p_pid;
747		mtx_unlock(&tp->tun_mtx);
748		break;
749	case FIONBIO:
750		break;
751	case FIOASYNC:
752		mtx_lock(&tp->tun_mtx);
753		if (*(int *)data)
754			tp->tun_flags |= TUN_ASYNC;
755		else
756			tp->tun_flags &= ~TUN_ASYNC;
757		mtx_unlock(&tp->tun_mtx);
758		break;
759	case FIONREAD:
760		s = splimp();
761		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
762			struct mbuf *mb;
763			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
764			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
765			for( *(int *)data = 0; mb != 0; mb = mb->m_next)
766				*(int *)data += mb->m_len;
767			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
768		} else
769			*(int *)data = 0;
770		splx(s);
771		break;
772	case FIOSETOWN:
773		return (fsetown(*(int *)data, &tp->tun_sigio));
774
775	case FIOGETOWN:
776		*(int *)data = fgetown(&tp->tun_sigio);
777		return (0);
778
779	/* This is deprecated, FIOSETOWN should be used instead. */
780	case TIOCSPGRP:
781		return (fsetown(-(*(int *)data), &tp->tun_sigio));
782
783	/* This is deprecated, FIOGETOWN should be used instead. */
784	case TIOCGPGRP:
785		*(int *)data = -fgetown(&tp->tun_sigio);
786		return (0);
787
788	default:
789		return (ENOTTY);
790	}
791	return (0);
792}
793
794/*
795 * The cdevsw read interface - reads a packet at a time, or at
796 * least as much of a packet as can be read.
797 */
798static	int
799tunread(struct cdev *dev, struct uio *uio, int flag)
800{
801	struct tun_softc *tp = dev->si_drv1;
802	struct ifnet	*ifp = TUN2IFP(tp);
803	struct mbuf	*m;
804	int		error=0, len, s;
805
806	TUNDEBUG (ifp, "read\n");
807	mtx_lock(&tp->tun_mtx);
808	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
809		mtx_unlock(&tp->tun_mtx);
810		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
811		return (EHOSTDOWN);
812	}
813
814	tp->tun_flags &= ~TUN_RWAIT;
815	mtx_unlock(&tp->tun_mtx);
816
817	s = splimp();
818	do {
819		IFQ_DEQUEUE(&ifp->if_snd, m);
820		if (m == NULL) {
821			if (flag & O_NONBLOCK) {
822				splx(s);
823				return (EWOULDBLOCK);
824			}
825			mtx_lock(&tp->tun_mtx);
826			tp->tun_flags |= TUN_RWAIT;
827			mtx_unlock(&tp->tun_mtx);
828			if ((error = tsleep(tp, PCATCH | (PZERO + 1),
829					"tunread", 0)) != 0) {
830				splx(s);
831				return (error);
832			}
833		}
834	} while (m == NULL);
835	splx(s);
836
837	while (m && uio->uio_resid > 0 && error == 0) {
838		len = min(uio->uio_resid, m->m_len);
839		if (len != 0)
840			error = uiomove(mtod(m, void *), len, uio);
841		m = m_free(m);
842	}
843
844	if (m) {
845		TUNDEBUG(ifp, "Dropping mbuf\n");
846		m_freem(m);
847	}
848	return (error);
849}
850
851/*
852 * the cdevsw write interface - an atomic write is a packet - or else!
853 */
854static	int
855tunwrite(struct cdev *dev, struct uio *uio, int flag)
856{
857	struct tun_softc *tp = dev->si_drv1;
858	struct ifnet	*ifp = TUN2IFP(tp);
859	struct mbuf	*m;
860	int		error = 0;
861	uint32_t	family;
862	int 		isr;
863
864	TUNDEBUG(ifp, "tunwrite\n");
865
866	if ((ifp->if_flags & IFF_UP) != IFF_UP)
867		/* ignore silently */
868		return (0);
869
870	if (uio->uio_resid == 0)
871		return (0);
872
873	if (uio->uio_resid < 0 || uio->uio_resid > TUNMRU) {
874		TUNDEBUG(ifp, "len=%d!\n", uio->uio_resid);
875		return (EIO);
876	}
877
878	if ((m = m_uiotombuf(uio, M_DONTWAIT, 0, 0, M_PKTHDR)) == NULL) {
879		ifp->if_ierrors++;
880		return (error);
881	}
882
883	m->m_pkthdr.rcvif = ifp;
884#ifdef MAC
885	mac_ifnet_create_mbuf(ifp, m);
886#endif
887
888	/* Could be unlocked read? */
889	mtx_lock(&tp->tun_mtx);
890	if (tp->tun_flags & TUN_IFHEAD) {
891		mtx_unlock(&tp->tun_mtx);
892		if (m->m_len < sizeof(family) &&
893		    (m = m_pullup(m, sizeof(family))) == NULL)
894			return (ENOBUFS);
895		family = ntohl(*mtod(m, u_int32_t *));
896		m_adj(m, sizeof(family));
897	} else {
898		mtx_unlock(&tp->tun_mtx);
899		family = AF_INET;
900	}
901
902	BPF_MTAP2(ifp, &family, sizeof(family), m);
903
904	switch (family) {
905#ifdef INET
906	case AF_INET:
907		isr = NETISR_IP;
908		break;
909#endif
910#ifdef INET6
911	case AF_INET6:
912		isr = NETISR_IPV6;
913		break;
914#endif
915#ifdef IPX
916	case AF_IPX:
917		isr = NETISR_IPX;
918		break;
919#endif
920#ifdef NETATALK
921	case AF_APPLETALK:
922		isr = NETISR_ATALK2;
923		break;
924#endif
925	default:
926		m_freem(m);
927		return (EAFNOSUPPORT);
928	}
929	/* First chunk of an mbuf contains good junk */
930	if (harvest.point_to_point)
931		random_harvest(m, 16, 3, 0, RANDOM_NET);
932	ifp->if_ibytes += m->m_pkthdr.len;
933	ifp->if_ipackets++;
934	CURVNET_SET(ifp->if_vnet);
935	netisr_dispatch(isr, m);
936	CURVNET_RESTORE();
937	return (0);
938}
939
940/*
941 * tunpoll - the poll interface, this is only useful on reads
942 * really. The write detect always returns true, write never blocks
943 * anyway, it either accepts the packet or drops it.
944 */
945static	int
946tunpoll(struct cdev *dev, int events, struct thread *td)
947{
948	int		s;
949	struct tun_softc *tp = dev->si_drv1;
950	struct ifnet	*ifp = TUN2IFP(tp);
951	int		revents = 0;
952	struct mbuf	*m;
953
954	s = splimp();
955	TUNDEBUG(ifp, "tunpoll\n");
956
957	if (events & (POLLIN | POLLRDNORM)) {
958		IFQ_LOCK(&ifp->if_snd);
959		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
960		if (m != NULL) {
961			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
962			revents |= events & (POLLIN | POLLRDNORM);
963		} else {
964			TUNDEBUG(ifp, "tunpoll waiting\n");
965			selrecord(td, &tp->tun_rsel);
966		}
967		IFQ_UNLOCK(&ifp->if_snd);
968	}
969	if (events & (POLLOUT | POLLWRNORM))
970		revents |= events & (POLLOUT | POLLWRNORM);
971
972	splx(s);
973	return (revents);
974}
975
976/*
977 * tunkqfilter - support for the kevent() system call.
978 */
979static int
980tunkqfilter(struct cdev *dev, struct knote *kn)
981{
982	int			s;
983	struct tun_softc	*tp = dev->si_drv1;
984	struct ifnet	*ifp = TUN2IFP(tp);
985
986	s = splimp();
987	switch(kn->kn_filter) {
988	case EVFILT_READ:
989		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
990		    ifp->if_xname, dev2unit(dev));
991		kn->kn_fop = &tun_read_filterops;
992		break;
993
994	case EVFILT_WRITE:
995		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
996		    ifp->if_xname, dev2unit(dev));
997		kn->kn_fop = &tun_write_filterops;
998		break;
999
1000	default:
1001		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1002		    ifp->if_xname, dev2unit(dev));
1003		splx(s);
1004		return(EINVAL);
1005	}
1006	splx(s);
1007
1008	kn->kn_hook = (caddr_t) dev;
1009	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1010
1011	return (0);
1012}
1013
1014/*
1015 * Return true of there is data in the interface queue.
1016 */
1017static int
1018tunkqread(struct knote *kn, long hint)
1019{
1020	int			ret, s;
1021	struct cdev		*dev = (struct cdev *)(kn->kn_hook);
1022	struct tun_softc	*tp = dev->si_drv1;
1023	struct ifnet	*ifp = TUN2IFP(tp);
1024
1025	s = splimp();
1026	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1027		TUNDEBUG(ifp,
1028		    "%s have data in the queue.  Len = %d, minor = %#x\n",
1029		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1030		ret = 1;
1031	} else {
1032		TUNDEBUG(ifp,
1033		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
1034		    dev2unit(dev));
1035		ret = 0;
1036	}
1037	splx(s);
1038
1039	return (ret);
1040}
1041
1042/*
1043 * Always can write, always return MTU in kn->data.
1044 */
1045static int
1046tunkqwrite(struct knote *kn, long hint)
1047{
1048	int			s;
1049	struct tun_softc	*tp = ((struct cdev *)kn->kn_hook)->si_drv1;
1050	struct ifnet	*ifp = TUN2IFP(tp);
1051
1052	s = splimp();
1053	kn->kn_data = ifp->if_mtu;
1054	splx(s);
1055
1056	return (1);
1057}
1058
1059static void
1060tunkqdetach(struct knote *kn)
1061{
1062	struct tun_softc	*tp = ((struct cdev *)kn->kn_hook)->si_drv1;
1063
1064	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1065}
1066