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