if_tun.c revision 111998
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 111998 2003-03-08 16:26:34Z jlemon $
17 */
18
19#include "opt_inet.h"
20#include "opt_mac.h"
21
22#include <sys/param.h>
23#include <sys/proc.h>
24#include <sys/systm.h>
25#include <sys/mac.h>
26#include <sys/mbuf.h>
27#include <sys/module.h>
28#include <sys/socket.h>
29#include <sys/filio.h>
30#include <sys/sockio.h>
31#include <sys/ttycom.h>
32#include <sys/poll.h>
33#include <sys/signalvar.h>
34#include <sys/filedesc.h>
35#include <sys/kernel.h>
36#include <sys/sysctl.h>
37#include <sys/conf.h>
38#include <sys/uio.h>
39#include <sys/vnode.h>
40#include <sys/malloc.h>
41#include <machine/bus.h>	/* XXX Shouldn't really be required ! */
42#include <sys/random.h>
43#include <sys/rman.h>
44
45#include <net/if.h>
46#include <net/if_types.h>
47#include <net/netisr.h>
48#include <net/route.h>
49#ifdef INET
50#include <netinet/in.h>
51#endif
52#include <net/bpf.h>
53#include <net/if_tunvar.h>
54#include <net/if_tun.h>
55
56#define TUNDEBUG	if (tundebug) printf
57#define	TUNNAME		"tun"
58#define	TUN_MAXUNIT	0x7fff	/* ifp->if_unit is only 15 bits */
59
60static MALLOC_DEFINE(M_TUN, TUNNAME, "Tunnel Interface");
61static int tundebug = 0;
62static struct tun_softc *tunhead = NULL;
63static struct rman tununits;
64static udev_t tunbasedev = NOUDEV;
65SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
66
67static void	tunclone(void *arg, char *name, int namelen, dev_t *dev);
68static void	tuncreate(dev_t dev);
69static int	tunifioctl(struct ifnet *, u_long, caddr_t);
70static int	tuninit(struct ifnet *);
71static int	tunmodevent(module_t, int, void *);
72static int	tunoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
73		    struct rtentry *rt);
74static void	tunstart(struct ifnet *);
75
76static d_open_t		tunopen;
77static d_close_t	tunclose;
78static d_read_t		tunread;
79static d_write_t	tunwrite;
80static d_ioctl_t	tunioctl;
81static d_poll_t		tunpoll;
82
83#define CDEV_MAJOR 52
84static struct cdevsw tun_cdevsw = {
85	.d_open =	tunopen,
86	.d_close =	tunclose,
87	.d_read =	tunread,
88	.d_write =	tunwrite,
89	.d_ioctl =	tunioctl,
90	.d_poll =	tunpoll,
91	.d_name =	TUNNAME,
92	.d_maj =	CDEV_MAJOR,
93};
94
95static void
96tunclone(void *arg, char *name, int namelen, dev_t *dev)
97{
98	struct resource *r;
99	int err;
100	int u;
101
102	if (*dev != NODEV)
103		return;
104
105	if (strcmp(name, TUNNAME) == 0) {
106		r = rman_reserve_resource(&tununits, 0, TUN_MAXUNIT, 1,
107		    RF_ALLOCATED | RF_ACTIVE, NULL);
108		u = rman_get_start(r);
109		err = rman_release_resource(r);
110		KASSERT(err == 0, ("Unexpected failure releasing resource"));
111		*dev = makedev(CDEV_MAJOR, unit2minor(u));
112		if ((*dev)->si_flags & SI_NAMED)
113			return;	/* Already make_dev()d */
114	} else if (dev_stdclone(name, NULL, TUNNAME, &u) != 1)
115		return;	/* Don't recognise the name */
116
117	*dev = make_dev(&tun_cdevsw, unit2minor(u),
118	    UID_ROOT, GID_WHEEL, 0600, "tun%d", u);
119
120	/*
121	 * All devices depend on tunbasedev so that we can simply
122	 * destroy_dev() this device at module unload time to get
123	 * rid of all our make_dev()d resources.
124	 */
125	if (tunbasedev == NOUDEV)
126		tunbasedev = (*dev)->si_udev;
127	else {
128		(*dev)->si_flags |= SI_CHEAPCLONE;
129		dev_depends(udev2dev(tunbasedev, 0), *dev);
130	}
131}
132
133static int
134tunmodevent(module_t mod, int type, void *data)
135{
136	static eventhandler_tag tag;
137	struct tun_softc *tp;
138	dev_t dev;
139	int err;
140
141	switch (type) {
142	case MOD_LOAD:
143		tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
144		if (tag == NULL)
145			return (ENOMEM);
146		tununits.rm_type = RMAN_ARRAY;
147		tununits.rm_descr = "open if_tun units";
148		err = rman_init(&tununits);
149		if (err != 0) {
150			EVENTHANDLER_DEREGISTER(dev_clone, tag);
151			return (err);
152		}
153		err = rman_manage_region(&tununits, 0, TUN_MAXUNIT);
154		if (err != 0) {
155			printf("%s: tununits: rman_manage_region: Failed %d\n",
156			    TUNNAME, err);
157			rman_fini(&tununits);
158			EVENTHANDLER_DEREGISTER(dev_clone, tag);
159			return (err);
160		}
161		break;
162	case MOD_UNLOAD:
163		err = rman_fini(&tununits);
164		if (err != 0)
165			return (err);
166		EVENTHANDLER_DEREGISTER(dev_clone, tag);
167
168		while (tunhead != NULL) {
169			KASSERT((tunhead->tun_flags & TUN_OPEN) == 0,
170			    ("tununits is out of sync - unit %d",
171			    tunhead->tun_if.if_unit));
172			tp = tunhead;
173			dev = makedev(tun_cdevsw.d_maj,
174			    unit2minor(tp->tun_if.if_unit));
175			KASSERT(dev->si_drv1 == tp, ("Bad makedev result"));
176			tunhead = tp->next;
177			bpfdetach(&tp->tun_if);
178			if_detach(&tp->tun_if);
179			KASSERT(dev->si_flags & SI_NAMED, ("Missing make_dev"));
180			free(tp, M_TUN);
181		}
182
183		/*
184		 * Destroying tunbasedev results in all of our make_dev()s
185		 * conveniently going away.
186		 */
187		if (tunbasedev != NOUDEV)
188			destroy_dev(udev2dev(tunbasedev, 0));
189
190		break;
191	}
192	return 0;
193}
194
195static moduledata_t tun_mod = {
196	"if_tun",
197	tunmodevent,
198	0
199};
200
201DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
202
203static void
204tunstart(struct ifnet *ifp)
205{
206	struct tun_softc *tp = ifp->if_softc;
207
208	if (tp->tun_flags & TUN_RWAIT) {
209		tp->tun_flags &= ~TUN_RWAIT;
210		wakeup(tp);
211	}
212	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio)
213		pgsigio(&tp->tun_sigio, SIGIO, 0);
214	selwakeup(&tp->tun_rsel);
215}
216
217static void
218tuncreate(dev_t dev)
219{
220	struct tun_softc *sc;
221	struct ifnet *ifp;
222
223	if (!(dev->si_flags & SI_NAMED))
224		dev = make_dev(&tun_cdevsw, minor(dev),
225		    UID_UUCP, GID_DIALER, 0600, "tun%d", dev2unit(dev));
226
227	MALLOC(sc, struct tun_softc *, sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
228	sc->tun_flags = TUN_INITED;
229	sc->next = tunhead;
230	tunhead = sc;
231
232	ifp = &sc->tun_if;
233	ifp->if_unit = dev2unit(dev);
234	ifp->if_name = TUNNAME;
235	ifp->if_mtu = TUNMTU;
236	ifp->if_ioctl = tunifioctl;
237	ifp->if_output = tunoutput;
238	ifp->if_start = tunstart;
239	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
240	ifp->if_type = IFT_PPP;
241	ifp->if_snd.ifq_maxlen = ifqmaxlen;
242	ifp->if_softc = sc;
243	if_attach(ifp);
244	bpfattach(ifp, DLT_NULL, sizeof(u_int));
245	dev->si_drv1 = sc;
246}
247
248static int
249tunopen(dev_t dev, int flag, int mode, struct thread *td)
250{
251	struct resource *r;
252	struct ifnet	*ifp;
253	struct tun_softc *tp;
254	int unit;
255
256	unit = dev2unit(dev);
257	if (unit > TUN_MAXUNIT)
258		return (ENXIO);
259
260	r = rman_reserve_resource(&tununits, unit, unit, 1,
261	    RF_ALLOCATED | RF_ACTIVE, NULL);
262	if (r == NULL)
263		return (EBUSY);
264
265	dev->si_flags &= ~SI_CHEAPCLONE;
266
267	tp = dev->si_drv1;
268	if (!tp) {
269		tuncreate(dev);
270		tp = dev->si_drv1;
271	}
272	KASSERT(!(tp->tun_flags & TUN_OPEN), ("Resource & flags out-of-sync"));
273	tp->r_unit = r;
274	tp->tun_pid = td->td_proc->p_pid;
275	ifp = &tp->tun_if;
276	tp->tun_flags |= TUN_OPEN;
277	TUNDEBUG("%s%d: open\n", ifp->if_name, ifp->if_unit);
278
279	return (0);
280}
281
282/*
283 * tunclose - close the device - mark i/f down & delete
284 * routing info
285 */
286static	int
287tunclose(dev_t dev, int foo, int bar, struct thread *td)
288{
289	struct tun_softc *tp;
290	struct ifnet *ifp;
291	int s;
292	int err;
293
294	tp = dev->si_drv1;
295	ifp = &tp->tun_if;
296
297	KASSERT(tp->r_unit, ("Unit %d not marked open", ifp->if_unit));
298	tp->tun_flags &= ~TUN_OPEN;
299	tp->tun_pid = 0;
300
301	/*
302	 * junk all pending output
303	 */
304	IF_DRAIN(&ifp->if_snd);
305
306	if (ifp->if_flags & IFF_UP) {
307		s = splimp();
308		if_down(ifp);
309		splx(s);
310	}
311
312	if (ifp->if_flags & IFF_RUNNING) {
313		struct ifaddr *ifa;
314
315		s = splimp();
316		/* find internet addresses and delete routes */
317		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
318			if (ifa->ifa_addr->sa_family == AF_INET)
319				rtinit(ifa, (int)RTM_DELETE,
320				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
321		ifp->if_flags &= ~IFF_RUNNING;
322		splx(s);
323	}
324
325	funsetown(&tp->tun_sigio);
326	selwakeup(&tp->tun_rsel);
327
328	TUNDEBUG ("%s%d: closed\n", ifp->if_name, ifp->if_unit);
329	err = rman_release_resource(tp->r_unit);
330	KASSERT(err == 0, ("Unit %d failed to release", ifp->if_unit));
331
332	return (0);
333}
334
335static int
336tuninit(struct ifnet *ifp)
337{
338	struct tun_softc *tp = ifp->if_softc;
339	struct ifaddr *ifa;
340	int error = 0;
341
342	TUNDEBUG("%s%d: tuninit\n", ifp->if_name, ifp->if_unit);
343
344	ifp->if_flags |= IFF_UP | IFF_RUNNING;
345	getmicrotime(&ifp->if_lastchange);
346
347	for (ifa = TAILQ_FIRST(&ifp->if_addrhead); ifa;
348	     ifa = TAILQ_NEXT(ifa, ifa_link)) {
349		if (ifa->ifa_addr == NULL)
350			error = EFAULT;
351			/* XXX: Should maybe return straight off? */
352		else {
353#ifdef INET
354			if (ifa->ifa_addr->sa_family == AF_INET) {
355			    struct sockaddr_in *si;
356
357			    si = (struct sockaddr_in *)ifa->ifa_addr;
358			    if (si->sin_addr.s_addr)
359				    tp->tun_flags |= TUN_IASET;
360
361			    si = (struct sockaddr_in *)ifa->ifa_dstaddr;
362			    if (si && si->sin_addr.s_addr)
363				    tp->tun_flags |= TUN_DSTADDR;
364			}
365#endif
366		}
367	}
368	return (error);
369}
370
371/*
372 * Process an ioctl request.
373 */
374static int
375tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
376{
377	struct ifreq *ifr = (struct ifreq *)data;
378	struct tun_softc *tp = ifp->if_softc;
379	struct ifstat *ifs;
380	int		error = 0, s;
381
382	s = splimp();
383	switch(cmd) {
384	case SIOCGIFSTATUS:
385		ifs = (struct ifstat *)data;
386		if (tp->tun_pid)
387			sprintf(ifs->ascii + strlen(ifs->ascii),
388			    "\tOpened by PID %d\n", tp->tun_pid);
389		break;
390	case SIOCSIFADDR:
391		error = tuninit(ifp);
392		TUNDEBUG("%s%d: address set, error=%d\n",
393			 ifp->if_name, ifp->if_unit, error);
394		break;
395	case SIOCSIFDSTADDR:
396		error = tuninit(ifp);
397		TUNDEBUG("%s%d: destination address set, error=%d\n",
398			 ifp->if_name, ifp->if_unit, error);
399		break;
400	case SIOCSIFMTU:
401		ifp->if_mtu = ifr->ifr_mtu;
402		TUNDEBUG("%s%d: mtu set\n", ifp->if_name, ifp->if_unit);
403		break;
404	case SIOCSIFFLAGS:
405	case SIOCADDMULTI:
406	case SIOCDELMULTI:
407		break;
408	default:
409		error = EINVAL;
410	}
411	splx(s);
412	return (error);
413}
414
415/*
416 * tunoutput - queue packets from higher level ready to put out.
417 */
418static int
419tunoutput(
420	struct ifnet *ifp,
421	struct mbuf *m0,
422	struct sockaddr *dst,
423	struct rtentry *rt)
424{
425	struct tun_softc *tp = ifp->if_softc;
426#ifdef MAC
427	int error;
428#endif
429
430	TUNDEBUG ("%s%d: tunoutput\n", ifp->if_name, ifp->if_unit);
431
432#ifdef MAC
433	error = mac_check_ifnet_transmit(ifp, m0);
434	if (error) {
435		m_freem(m0);
436		return (error);
437	}
438#endif
439
440	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
441		TUNDEBUG ("%s%d: not ready 0%o\n", ifp->if_name,
442			  ifp->if_unit, tp->tun_flags);
443		m_freem (m0);
444		return (EHOSTDOWN);
445	}
446
447	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
448		m_freem (m0);
449		return (EHOSTDOWN);
450	}
451
452	/* BPF write needs to be handled specially */
453	if (dst->sa_family == AF_UNSPEC) {
454		dst->sa_family = *(mtod(m0, int *));
455		m0->m_len -= sizeof(int);
456		m0->m_pkthdr.len -= sizeof(int);
457		m0->m_data += sizeof(int);
458	}
459
460	if (ifp->if_bpf) {
461		/*
462		 * We need to prepend the address family as
463		 * a four byte field.  Cons up a dummy header
464		 * to pacify bpf.  This is safe because bpf
465		 * will only read from the mbuf (i.e., it won't
466		 * try to free it or keep a pointer to it).
467		 */
468		struct mbuf m;
469		uint32_t af = dst->sa_family;
470
471		m.m_next = m0;
472		m.m_len = 4;
473		m.m_data = (char *)&af;
474
475		BPF_MTAP(ifp, &m);
476	}
477
478	/* prepend sockaddr? this may abort if the mbuf allocation fails */
479	if (tp->tun_flags & TUN_LMODE) {
480		/* allocate space for sockaddr */
481		M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
482
483		/* if allocation failed drop packet */
484		if (m0 == NULL) {
485			ifp->if_iqdrops++;
486			ifp->if_oerrors++;
487			return (ENOBUFS);
488		} else {
489			bcopy(dst, m0->m_data, dst->sa_len);
490		}
491	}
492
493	if (tp->tun_flags & TUN_IFHEAD) {
494		/* Prepend the address family */
495		M_PREPEND(m0, 4, M_DONTWAIT);
496
497		/* if allocation failed drop packet */
498		if (m0 == NULL) {
499			ifp->if_iqdrops++;
500			ifp->if_oerrors++;
501			return (ENOBUFS);
502		} else
503			*(u_int32_t *)m0->m_data = htonl(dst->sa_family);
504	} else {
505#ifdef INET
506		if (dst->sa_family != AF_INET)
507#endif
508		{
509			m_freem(m0);
510			return (EAFNOSUPPORT);
511		}
512	}
513
514	if (! IF_HANDOFF(&ifp->if_snd, m0, ifp)) {
515		ifp->if_collisions++;
516		return (ENOBUFS);
517	}
518	ifp->if_opackets++;
519	return (0);
520}
521
522/*
523 * the cdevsw interface is now pretty minimal.
524 */
525static	int
526tunioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct thread *td)
527{
528	int		s;
529	int		error;
530	struct tun_softc *tp = dev->si_drv1;
531	struct tuninfo *tunp;
532
533	switch (cmd) {
534	case TUNSIFINFO:
535		tunp = (struct tuninfo *)data;
536		if (tunp->mtu < IF_MINMTU)
537			return (EINVAL);
538		if (tp->tun_if.if_mtu != tunp->mtu
539		&& (error = suser(td)) != 0)
540			return (error);
541		tp->tun_if.if_mtu = tunp->mtu;
542		tp->tun_if.if_type = tunp->type;
543		tp->tun_if.if_baudrate = tunp->baudrate;
544		break;
545	case TUNGIFINFO:
546		tunp = (struct tuninfo *)data;
547		tunp->mtu = tp->tun_if.if_mtu;
548		tunp->type = tp->tun_if.if_type;
549		tunp->baudrate = tp->tun_if.if_baudrate;
550		break;
551	case TUNSDEBUG:
552		tundebug = *(int *)data;
553		break;
554	case TUNGDEBUG:
555		*(int *)data = tundebug;
556		break;
557	case TUNSLMODE:
558		if (*(int *)data) {
559			tp->tun_flags |= TUN_LMODE;
560			tp->tun_flags &= ~TUN_IFHEAD;
561		} else
562			tp->tun_flags &= ~TUN_LMODE;
563		break;
564	case TUNSIFHEAD:
565		if (*(int *)data) {
566			tp->tun_flags |= TUN_IFHEAD;
567			tp->tun_flags &= ~TUN_LMODE;
568		} else
569			tp->tun_flags &= ~TUN_IFHEAD;
570		break;
571	case TUNGIFHEAD:
572		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
573		break;
574	case TUNSIFMODE:
575		/* deny this if UP */
576		if (tp->tun_if.if_flags & IFF_UP)
577			return(EBUSY);
578
579		switch (*(int *)data & ~IFF_MULTICAST) {
580		case IFF_POINTOPOINT:
581		case IFF_BROADCAST:
582			tp->tun_if.if_flags &=
583			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
584			tp->tun_if.if_flags |= *(int *)data;
585			break;
586		default:
587			return(EINVAL);
588		}
589		break;
590	case TUNSIFPID:
591		tp->tun_pid = curthread->td_proc->p_pid;
592		break;
593	case FIONBIO:
594		break;
595	case FIOASYNC:
596		if (*(int *)data)
597			tp->tun_flags |= TUN_ASYNC;
598		else
599			tp->tun_flags &= ~TUN_ASYNC;
600		break;
601	case FIONREAD:
602		s = splimp();
603		if (tp->tun_if.if_snd.ifq_head) {
604			struct mbuf *mb = tp->tun_if.if_snd.ifq_head;
605			for( *(int *)data = 0; mb != 0; mb = mb->m_next)
606				*(int *)data += mb->m_len;
607		} else
608			*(int *)data = 0;
609		splx(s);
610		break;
611	case FIOSETOWN:
612		return (fsetown(*(int *)data, &tp->tun_sigio));
613
614	case FIOGETOWN:
615		*(int *)data = fgetown(&tp->tun_sigio);
616		return (0);
617
618	/* This is deprecated, FIOSETOWN should be used instead. */
619	case TIOCSPGRP:
620		return (fsetown(-(*(int *)data), &tp->tun_sigio));
621
622	/* This is deprecated, FIOGETOWN should be used instead. */
623	case TIOCGPGRP:
624		*(int *)data = -fgetown(&tp->tun_sigio);
625		return (0);
626
627	default:
628		return (ENOTTY);
629	}
630	return (0);
631}
632
633/*
634 * The cdevsw read interface - reads a packet at a time, or at
635 * least as much of a packet as can be read.
636 */
637static	int
638tunread(dev_t dev, struct uio *uio, int flag)
639{
640	struct tun_softc *tp = dev->si_drv1;
641	struct ifnet	*ifp = &tp->tun_if;
642	struct mbuf	*m;
643	int		error=0, len, s;
644
645	TUNDEBUG ("%s%d: read\n", ifp->if_name, ifp->if_unit);
646	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
647		TUNDEBUG ("%s%d: not ready 0%o\n", ifp->if_name,
648			  ifp->if_unit, tp->tun_flags);
649		return (EHOSTDOWN);
650	}
651
652	tp->tun_flags &= ~TUN_RWAIT;
653
654	s = splimp();
655	do {
656		IF_DEQUEUE(&ifp->if_snd, m);
657		if (m == NULL) {
658			if (flag & IO_NDELAY) {
659				splx(s);
660				return (EWOULDBLOCK);
661			}
662			tp->tun_flags |= TUN_RWAIT;
663			if((error = tsleep(tp, PCATCH | (PZERO + 1),
664					"tunread", 0)) != 0) {
665				splx(s);
666				return (error);
667			}
668		}
669	} while (m == NULL);
670	splx(s);
671
672	while (m && uio->uio_resid > 0 && error == 0) {
673		len = min(uio->uio_resid, m->m_len);
674		if (len != 0)
675			error = uiomove(mtod(m, void *), len, uio);
676		m = m_free(m);
677	}
678
679	if (m) {
680		TUNDEBUG("%s%d: Dropping mbuf\n", ifp->if_name, ifp->if_unit);
681		m_freem(m);
682	}
683	return (error);
684}
685
686/*
687 * the cdevsw write interface - an atomic write is a packet - or else!
688 */
689static	int
690tunwrite(dev_t dev, struct uio *uio, int flag)
691{
692	struct tun_softc *tp = dev->si_drv1;
693	struct ifnet	*ifp = &tp->tun_if;
694	struct mbuf	*top, **mp, *m;
695	int		error=0, tlen, mlen;
696	uint32_t	family;
697	int 		isr;
698
699	TUNDEBUG("%s%d: tunwrite\n", ifp->if_name, ifp->if_unit);
700
701	if ((ifp->if_flags & IFF_UP) != IFF_UP)
702		/* ignore silently */
703		return (0);
704
705	if (uio->uio_resid == 0)
706		return (0);
707
708	if (uio->uio_resid < 0 || uio->uio_resid > TUNMRU) {
709		TUNDEBUG("%s%d: len=%d!\n", ifp->if_name, ifp->if_unit,
710		    uio->uio_resid);
711		return (EIO);
712	}
713	tlen = uio->uio_resid;
714
715	/* get a header mbuf */
716	MGETHDR(m, M_DONTWAIT, MT_DATA);
717	if (m == NULL)
718		return (ENOBUFS);
719	mlen = MHLEN;
720
721	top = 0;
722	mp = &top;
723	while (error == 0 && uio->uio_resid > 0) {
724		m->m_len = min(mlen, uio->uio_resid);
725		error = uiomove(mtod(m, void *), m->m_len, uio);
726		*mp = m;
727		mp = &m->m_next;
728		if (uio->uio_resid > 0) {
729			MGET (m, M_DONTWAIT, MT_DATA);
730			if (m == 0) {
731				error = ENOBUFS;
732				break;
733			}
734			mlen = MLEN;
735		}
736	}
737	if (error) {
738		if (top)
739			m_freem (top);
740		ifp->if_ierrors++;
741		return (error);
742	}
743
744	top->m_pkthdr.len = tlen;
745	top->m_pkthdr.rcvif = ifp;
746#ifdef MAC
747	mac_create_mbuf_from_ifnet(ifp, top);
748#endif
749
750	if (ifp->if_bpf) {
751		if (tp->tun_flags & TUN_IFHEAD) {
752			/*
753			 * Conveniently, we already have a 4-byte address
754			 * family prepended to our packet !
755			 * Inconveniently, it's in the wrong byte order !
756			 */
757			if ((top = m_pullup(top, sizeof(family))) == NULL)
758				return (ENOBUFS);
759			*mtod(top, u_int32_t *) =
760			    ntohl(*mtod(top, u_int32_t *));
761			BPF_MTAP(ifp, top);
762			*mtod(top, u_int32_t *) =
763			    htonl(*mtod(top, u_int32_t *));
764		} else {
765			/*
766			 * We need to prepend the address family as
767			 * a four byte field.  Cons up a dummy header
768			 * to pacify bpf.  This is safe because bpf
769			 * will only read from the mbuf (i.e., it won't
770			 * try to free it or keep a pointer to it).
771			 */
772			struct mbuf m;
773			uint32_t af = AF_INET;
774
775			m.m_next = top;
776			m.m_len = 4;
777			m.m_data = (char *)&af;
778
779			BPF_MTAP(ifp, &m);
780		}
781	}
782
783	if (tp->tun_flags & TUN_IFHEAD) {
784		if (top->m_len < sizeof(family) &&
785		    (top = m_pullup(top, sizeof(family))) == NULL)
786			return (ENOBUFS);
787		family = ntohl(*mtod(top, u_int32_t *));
788		m_adj(top, sizeof(family));
789	} else
790		family = AF_INET;
791
792	switch (family) {
793#ifdef INET
794	case AF_INET:
795		isr = NETISR_IP;
796		break;
797#endif
798	default:
799		m_freem(m);
800		return (EAFNOSUPPORT);
801	}
802	/* First chunk of an mbuf contains good junk */
803	if (harvest.point_to_point)
804		random_harvest(m, 16, 3, 0, RANDOM_NET);
805	ifp->if_ibytes += top->m_pkthdr.len;
806	ifp->if_ipackets++;
807	netisr_dispatch(isr, top);
808	return (0);
809}
810
811/*
812 * tunpoll - the poll interface, this is only useful on reads
813 * really. The write detect always returns true, write never blocks
814 * anyway, it either accepts the packet or drops it.
815 */
816static	int
817tunpoll(dev_t dev, int events, struct thread *td)
818{
819	int		s;
820	struct tun_softc *tp = dev->si_drv1;
821	struct ifnet	*ifp = &tp->tun_if;
822	int		revents = 0;
823
824	s = splimp();
825	TUNDEBUG("%s%d: tunpoll\n", ifp->if_name, ifp->if_unit);
826
827	if (events & (POLLIN | POLLRDNORM)) {
828		if (ifp->if_snd.ifq_len > 0) {
829			TUNDEBUG("%s%d: tunpoll q=%d\n", ifp->if_name,
830			    ifp->if_unit, ifp->if_snd.ifq_len);
831			revents |= events & (POLLIN | POLLRDNORM);
832		} else {
833			TUNDEBUG("%s%d: tunpoll waiting\n", ifp->if_name,
834			    ifp->if_unit);
835			selrecord(td, &tp->tun_rsel);
836		}
837	}
838	if (events & (POLLOUT | POLLWRNORM))
839		revents |= events & (POLLOUT | POLLWRNORM);
840
841	splx(s);
842	return (revents);
843}
844