if_tun.c revision 184679
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 184679 2008-11-05 11:39:46Z bz $
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#ifdef INET
498	struct tun_softc *tp = ifp->if_softc;
499	struct ifaddr *ifa;
500#endif
501	int error = 0;
502
503	TUNDEBUG(ifp, "tuninit\n");
504
505	ifp->if_flags |= IFF_UP;
506	ifp->if_drv_flags |= IFF_DRV_RUNNING;
507	getmicrotime(&ifp->if_lastchange);
508
509#ifdef INET
510	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
511		if (ifa->ifa_addr->sa_family == AF_INET) {
512			struct sockaddr_in *si;
513
514			si = (struct sockaddr_in *)ifa->ifa_addr;
515			mtx_lock(&tp->tun_mtx);
516			if (si->sin_addr.s_addr)
517				tp->tun_flags |= TUN_IASET;
518
519			si = (struct sockaddr_in *)ifa->ifa_dstaddr;
520			if (si && si->sin_addr.s_addr)
521				tp->tun_flags |= TUN_DSTADDR;
522			mtx_unlock(&tp->tun_mtx);
523		}
524	}
525#endif
526	return (error);
527}
528
529/*
530 * Process an ioctl request.
531 */
532static int
533tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
534{
535	struct ifreq *ifr = (struct ifreq *)data;
536	struct tun_softc *tp = ifp->if_softc;
537	struct ifstat *ifs;
538	int		error = 0, s;
539
540	s = splimp();
541	switch(cmd) {
542	case SIOCGIFSTATUS:
543		ifs = (struct ifstat *)data;
544		mtx_lock(&tp->tun_mtx);
545		if (tp->tun_pid)
546			sprintf(ifs->ascii + strlen(ifs->ascii),
547			    "\tOpened by PID %d\n", tp->tun_pid);
548		mtx_unlock(&tp->tun_mtx);
549		break;
550	case SIOCSIFADDR:
551		error = tuninit(ifp);
552		TUNDEBUG(ifp, "address set, error=%d\n", error);
553		break;
554	case SIOCSIFDSTADDR:
555		error = tuninit(ifp);
556		TUNDEBUG(ifp, "destination address set, error=%d\n", error);
557		break;
558	case SIOCSIFMTU:
559		ifp->if_mtu = ifr->ifr_mtu;
560		TUNDEBUG(ifp, "mtu set\n");
561		break;
562	case SIOCSIFFLAGS:
563	case SIOCADDMULTI:
564	case SIOCDELMULTI:
565		break;
566	default:
567		error = EINVAL;
568	}
569	splx(s);
570	return (error);
571}
572
573/*
574 * tunoutput - queue packets from higher level ready to put out.
575 */
576static int
577tunoutput(
578	struct ifnet *ifp,
579	struct mbuf *m0,
580	struct sockaddr *dst,
581	struct rtentry *rt)
582{
583	struct tun_softc *tp = ifp->if_softc;
584	u_short cached_tun_flags;
585	int error;
586	u_int32_t af;
587
588	TUNDEBUG (ifp, "tunoutput\n");
589
590#ifdef MAC
591	error = mac_ifnet_check_transmit(ifp, m0);
592	if (error) {
593		m_freem(m0);
594		return (error);
595	}
596#endif
597
598	/* Could be unlocked read? */
599	mtx_lock(&tp->tun_mtx);
600	cached_tun_flags = tp->tun_flags;
601	mtx_unlock(&tp->tun_mtx);
602	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
603		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
604		m_freem (m0);
605		return (EHOSTDOWN);
606	}
607
608	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
609		m_freem (m0);
610		return (EHOSTDOWN);
611	}
612
613	/* BPF writes need to be handled specially. */
614	if (dst->sa_family == AF_UNSPEC) {
615		bcopy(dst->sa_data, &af, sizeof(af));
616		dst->sa_family = af;
617	}
618
619	if (bpf_peers_present(ifp->if_bpf)) {
620		af = dst->sa_family;
621		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
622	}
623
624	/* prepend sockaddr? this may abort if the mbuf allocation fails */
625	if (cached_tun_flags & TUN_LMODE) {
626		/* allocate space for sockaddr */
627		M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
628
629		/* if allocation failed drop packet */
630		if (m0 == NULL) {
631			ifp->if_iqdrops++;
632			ifp->if_oerrors++;
633			return (ENOBUFS);
634		} else {
635			bcopy(dst, m0->m_data, dst->sa_len);
636		}
637	}
638
639	if (cached_tun_flags & TUN_IFHEAD) {
640		/* Prepend the address family */
641		M_PREPEND(m0, 4, M_DONTWAIT);
642
643		/* if allocation failed drop packet */
644		if (m0 == NULL) {
645			ifp->if_iqdrops++;
646			ifp->if_oerrors++;
647			return (ENOBUFS);
648		} else
649			*(u_int32_t *)m0->m_data = htonl(dst->sa_family);
650	} else {
651#ifdef INET
652		if (dst->sa_family != AF_INET)
653#endif
654		{
655			m_freem(m0);
656			return (EAFNOSUPPORT);
657		}
658	}
659
660	IFQ_HANDOFF(ifp, m0, error);
661	if (error) {
662		ifp->if_collisions++;
663		return (ENOBUFS);
664	}
665	ifp->if_opackets++;
666	return (0);
667}
668
669/*
670 * the cdevsw interface is now pretty minimal.
671 */
672static	int
673tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
674{
675	int		s;
676	int		error;
677	struct tun_softc *tp = dev->si_drv1;
678	struct tuninfo *tunp;
679
680	switch (cmd) {
681	case TUNSIFINFO:
682		tunp = (struct tuninfo *)data;
683		if (tunp->mtu < IF_MINMTU)
684			return (EINVAL);
685		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
686			error = priv_check(td, PRIV_NET_SETIFMTU);
687			if (error)
688				return (error);
689		}
690		TUN2IFP(tp)->if_mtu = tunp->mtu;
691		TUN2IFP(tp)->if_type = tunp->type;
692		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
693		break;
694	case TUNGIFINFO:
695		tunp = (struct tuninfo *)data;
696		tunp->mtu = TUN2IFP(tp)->if_mtu;
697		tunp->type = TUN2IFP(tp)->if_type;
698		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
699		break;
700	case TUNSDEBUG:
701		tundebug = *(int *)data;
702		break;
703	case TUNGDEBUG:
704		*(int *)data = tundebug;
705		break;
706	case TUNSLMODE:
707		mtx_lock(&tp->tun_mtx);
708		if (*(int *)data) {
709			tp->tun_flags |= TUN_LMODE;
710			tp->tun_flags &= ~TUN_IFHEAD;
711		} else
712			tp->tun_flags &= ~TUN_LMODE;
713		mtx_unlock(&tp->tun_mtx);
714		break;
715	case TUNSIFHEAD:
716		mtx_lock(&tp->tun_mtx);
717		if (*(int *)data) {
718			tp->tun_flags |= TUN_IFHEAD;
719			tp->tun_flags &= ~TUN_LMODE;
720		} else
721			tp->tun_flags &= ~TUN_IFHEAD;
722		mtx_unlock(&tp->tun_mtx);
723		break;
724	case TUNGIFHEAD:
725		/* Could be unlocked read? */
726		mtx_lock(&tp->tun_mtx);
727		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
728		mtx_unlock(&tp->tun_mtx);
729		break;
730	case TUNSIFMODE:
731		/* deny this if UP */
732		if (TUN2IFP(tp)->if_flags & IFF_UP)
733			return(EBUSY);
734
735		switch (*(int *)data & ~IFF_MULTICAST) {
736		case IFF_POINTOPOINT:
737		case IFF_BROADCAST:
738			TUN2IFP(tp)->if_flags &=
739			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
740			TUN2IFP(tp)->if_flags |= *(int *)data;
741			break;
742		default:
743			return(EINVAL);
744		}
745		break;
746	case TUNSIFPID:
747		mtx_lock(&tp->tun_mtx);
748		tp->tun_pid = curthread->td_proc->p_pid;
749		mtx_unlock(&tp->tun_mtx);
750		break;
751	case FIONBIO:
752		break;
753	case FIOASYNC:
754		mtx_lock(&tp->tun_mtx);
755		if (*(int *)data)
756			tp->tun_flags |= TUN_ASYNC;
757		else
758			tp->tun_flags &= ~TUN_ASYNC;
759		mtx_unlock(&tp->tun_mtx);
760		break;
761	case FIONREAD:
762		s = splimp();
763		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
764			struct mbuf *mb;
765			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
766			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
767			for( *(int *)data = 0; mb != 0; mb = mb->m_next)
768				*(int *)data += mb->m_len;
769			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
770		} else
771			*(int *)data = 0;
772		splx(s);
773		break;
774	case FIOSETOWN:
775		return (fsetown(*(int *)data, &tp->tun_sigio));
776
777	case FIOGETOWN:
778		*(int *)data = fgetown(&tp->tun_sigio);
779		return (0);
780
781	/* This is deprecated, FIOSETOWN should be used instead. */
782	case TIOCSPGRP:
783		return (fsetown(-(*(int *)data), &tp->tun_sigio));
784
785	/* This is deprecated, FIOGETOWN should be used instead. */
786	case TIOCGPGRP:
787		*(int *)data = -fgetown(&tp->tun_sigio);
788		return (0);
789
790	default:
791		return (ENOTTY);
792	}
793	return (0);
794}
795
796/*
797 * The cdevsw read interface - reads a packet at a time, or at
798 * least as much of a packet as can be read.
799 */
800static	int
801tunread(struct cdev *dev, struct uio *uio, int flag)
802{
803	struct tun_softc *tp = dev->si_drv1;
804	struct ifnet	*ifp = TUN2IFP(tp);
805	struct mbuf	*m;
806	int		error=0, len, s;
807
808	TUNDEBUG (ifp, "read\n");
809	mtx_lock(&tp->tun_mtx);
810	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
811		mtx_unlock(&tp->tun_mtx);
812		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
813		return (EHOSTDOWN);
814	}
815
816	tp->tun_flags &= ~TUN_RWAIT;
817	mtx_unlock(&tp->tun_mtx);
818
819	s = splimp();
820	do {
821		IFQ_DEQUEUE(&ifp->if_snd, m);
822		if (m == NULL) {
823			if (flag & O_NONBLOCK) {
824				splx(s);
825				return (EWOULDBLOCK);
826			}
827			mtx_lock(&tp->tun_mtx);
828			tp->tun_flags |= TUN_RWAIT;
829			mtx_unlock(&tp->tun_mtx);
830			if ((error = tsleep(tp, PCATCH | (PZERO + 1),
831					"tunread", 0)) != 0) {
832				splx(s);
833				return (error);
834			}
835		}
836	} while (m == NULL);
837	splx(s);
838
839	while (m && uio->uio_resid > 0 && error == 0) {
840		len = min(uio->uio_resid, m->m_len);
841		if (len != 0)
842			error = uiomove(mtod(m, void *), len, uio);
843		m = m_free(m);
844	}
845
846	if (m) {
847		TUNDEBUG(ifp, "Dropping mbuf\n");
848		m_freem(m);
849	}
850	return (error);
851}
852
853/*
854 * the cdevsw write interface - an atomic write is a packet - or else!
855 */
856static	int
857tunwrite(struct cdev *dev, struct uio *uio, int flag)
858{
859	struct tun_softc *tp = dev->si_drv1;
860	struct ifnet	*ifp = TUN2IFP(tp);
861	struct mbuf	*m;
862	int		error = 0;
863	uint32_t	family;
864	int 		isr;
865
866	TUNDEBUG(ifp, "tunwrite\n");
867
868	if ((ifp->if_flags & IFF_UP) != IFF_UP)
869		/* ignore silently */
870		return (0);
871
872	if (uio->uio_resid == 0)
873		return (0);
874
875	if (uio->uio_resid < 0 || uio->uio_resid > TUNMRU) {
876		TUNDEBUG(ifp, "len=%d!\n", uio->uio_resid);
877		return (EIO);
878	}
879
880	if ((m = m_uiotombuf(uio, M_DONTWAIT, 0, 0, M_PKTHDR)) == NULL) {
881		ifp->if_ierrors++;
882		return (error);
883	}
884
885	m->m_pkthdr.rcvif = ifp;
886#ifdef MAC
887	mac_ifnet_create_mbuf(ifp, m);
888#endif
889
890	/* Could be unlocked read? */
891	mtx_lock(&tp->tun_mtx);
892	if (tp->tun_flags & TUN_IFHEAD) {
893		mtx_unlock(&tp->tun_mtx);
894		if (m->m_len < sizeof(family) &&
895		    (m = m_pullup(m, sizeof(family))) == NULL)
896			return (ENOBUFS);
897		family = ntohl(*mtod(m, u_int32_t *));
898		m_adj(m, sizeof(family));
899	} else {
900		mtx_unlock(&tp->tun_mtx);
901		family = AF_INET;
902	}
903
904	BPF_MTAP2(ifp, &family, sizeof(family), m);
905
906	switch (family) {
907#ifdef INET
908	case AF_INET:
909		isr = NETISR_IP;
910		break;
911#endif
912#ifdef INET6
913	case AF_INET6:
914		isr = NETISR_IPV6;
915		break;
916#endif
917#ifdef IPX
918	case AF_IPX:
919		isr = NETISR_IPX;
920		break;
921#endif
922#ifdef NETATALK
923	case AF_APPLETALK:
924		isr = NETISR_ATALK2;
925		break;
926#endif
927	default:
928		m_freem(m);
929		return (EAFNOSUPPORT);
930	}
931	/* First chunk of an mbuf contains good junk */
932	if (harvest.point_to_point)
933		random_harvest(m, 16, 3, 0, RANDOM_NET);
934	ifp->if_ibytes += m->m_pkthdr.len;
935	ifp->if_ipackets++;
936	CURVNET_SET(ifp->if_vnet);
937	netisr_dispatch(isr, m);
938	CURVNET_RESTORE();
939	return (0);
940}
941
942/*
943 * tunpoll - the poll interface, this is only useful on reads
944 * really. The write detect always returns true, write never blocks
945 * anyway, it either accepts the packet or drops it.
946 */
947static	int
948tunpoll(struct cdev *dev, int events, struct thread *td)
949{
950	int		s;
951	struct tun_softc *tp = dev->si_drv1;
952	struct ifnet	*ifp = TUN2IFP(tp);
953	int		revents = 0;
954	struct mbuf	*m;
955
956	s = splimp();
957	TUNDEBUG(ifp, "tunpoll\n");
958
959	if (events & (POLLIN | POLLRDNORM)) {
960		IFQ_LOCK(&ifp->if_snd);
961		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
962		if (m != NULL) {
963			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
964			revents |= events & (POLLIN | POLLRDNORM);
965		} else {
966			TUNDEBUG(ifp, "tunpoll waiting\n");
967			selrecord(td, &tp->tun_rsel);
968		}
969		IFQ_UNLOCK(&ifp->if_snd);
970	}
971	if (events & (POLLOUT | POLLWRNORM))
972		revents |= events & (POLLOUT | POLLWRNORM);
973
974	splx(s);
975	return (revents);
976}
977
978/*
979 * tunkqfilter - support for the kevent() system call.
980 */
981static int
982tunkqfilter(struct cdev *dev, struct knote *kn)
983{
984	int			s;
985	struct tun_softc	*tp = dev->si_drv1;
986	struct ifnet	*ifp = TUN2IFP(tp);
987
988	s = splimp();
989	switch(kn->kn_filter) {
990	case EVFILT_READ:
991		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
992		    ifp->if_xname, dev2unit(dev));
993		kn->kn_fop = &tun_read_filterops;
994		break;
995
996	case EVFILT_WRITE:
997		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
998		    ifp->if_xname, dev2unit(dev));
999		kn->kn_fop = &tun_write_filterops;
1000		break;
1001
1002	default:
1003		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1004		    ifp->if_xname, dev2unit(dev));
1005		splx(s);
1006		return(EINVAL);
1007	}
1008	splx(s);
1009
1010	kn->kn_hook = (caddr_t) dev;
1011	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1012
1013	return (0);
1014}
1015
1016/*
1017 * Return true of there is data in the interface queue.
1018 */
1019static int
1020tunkqread(struct knote *kn, long hint)
1021{
1022	int			ret, s;
1023	struct cdev		*dev = (struct cdev *)(kn->kn_hook);
1024	struct tun_softc	*tp = dev->si_drv1;
1025	struct ifnet	*ifp = TUN2IFP(tp);
1026
1027	s = splimp();
1028	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1029		TUNDEBUG(ifp,
1030		    "%s have data in the queue.  Len = %d, minor = %#x\n",
1031		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1032		ret = 1;
1033	} else {
1034		TUNDEBUG(ifp,
1035		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
1036		    dev2unit(dev));
1037		ret = 0;
1038	}
1039	splx(s);
1040
1041	return (ret);
1042}
1043
1044/*
1045 * Always can write, always return MTU in kn->data.
1046 */
1047static int
1048tunkqwrite(struct knote *kn, long hint)
1049{
1050	int			s;
1051	struct tun_softc	*tp = ((struct cdev *)kn->kn_hook)->si_drv1;
1052	struct ifnet	*ifp = TUN2IFP(tp);
1053
1054	s = splimp();
1055	kn->kn_data = ifp->if_mtu;
1056	splx(s);
1057
1058	return (1);
1059}
1060
1061static void
1062tunkqdetach(struct knote *kn)
1063{
1064	struct tun_softc	*tp = ((struct cdev *)kn->kn_hook)->si_drv1;
1065
1066	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1067}
1068