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