xref: /netbsd-src/sys/net/if_tun.c (revision e39ef1d61eee3ccba837ee281f1e098c864487aa)
1 /*	$NetBSD: if_tun.c,v 1.114 2011/10/28 22:08:14 dyoung 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 its
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 
17 #include <sys/cdefs.h>
18 __KERNEL_RCSID(0, "$NetBSD: if_tun.c,v 1.114 2011/10/28 22:08:14 dyoung Exp $");
19 
20 #include "opt_inet.h"
21 
22 #include <sys/param.h>
23 #include <sys/proc.h>
24 #include <sys/systm.h>
25 #include <sys/mbuf.h>
26 #include <sys/buf.h>
27 #include <sys/protosw.h>
28 #include <sys/socket.h>
29 #include <sys/ioctl.h>
30 #include <sys/errno.h>
31 #include <sys/syslog.h>
32 #include <sys/select.h>
33 #include <sys/poll.h>
34 #include <sys/file.h>
35 #include <sys/signalvar.h>
36 #include <sys/conf.h>
37 #include <sys/kauth.h>
38 #include <sys/simplelock.h>
39 #include <sys/cpu.h>
40 
41 #include <net/if.h>
42 #include <net/if_types.h>
43 #include <net/netisr.h>
44 #include <net/route.h>
45 
46 
47 #ifdef INET
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/in_var.h>
51 #include <netinet/ip.h>
52 #include <netinet/if_inarp.h>
53 #endif
54 
55 
56 #include <sys/time.h>
57 #include <net/bpf.h>
58 
59 #include <net/if_tun.h>
60 
61 #define TUNDEBUG	if (tundebug) printf
62 int	tundebug = 0;
63 
64 extern int ifqmaxlen;
65 void	tunattach(int);
66 
67 static LIST_HEAD(, tun_softc) tun_softc_list;
68 static LIST_HEAD(, tun_softc) tunz_softc_list;
69 static struct simplelock tun_softc_lock;
70 
71 static int	tun_ioctl(struct ifnet *, u_long, void *);
72 static int	tun_output(struct ifnet *, struct mbuf *,
73 			const struct sockaddr *, struct rtentry *rt);
74 static int	tun_clone_create(struct if_clone *, int);
75 static int	tun_clone_destroy(struct ifnet *);
76 
77 static struct if_clone tun_cloner =
78     IF_CLONE_INITIALIZER("tun", tun_clone_create, tun_clone_destroy);
79 
80 static void tunattach0(struct tun_softc *);
81 static void tuninit(struct tun_softc *);
82 static void tun_i_softintr(void *);
83 static void tun_o_softintr(void *);
84 #ifdef ALTQ
85 static void tunstart(struct ifnet *);
86 #endif
87 static struct tun_softc *tun_find_unit(dev_t);
88 static struct tun_softc *tun_find_zunit(int);
89 
90 static dev_type_open(tunopen);
91 static dev_type_close(tunclose);
92 static dev_type_read(tunread);
93 static dev_type_write(tunwrite);
94 static dev_type_ioctl(tunioctl);
95 static dev_type_poll(tunpoll);
96 static dev_type_kqfilter(tunkqfilter);
97 
98 const struct cdevsw tun_cdevsw = {
99 	tunopen, tunclose, tunread, tunwrite, tunioctl,
100 	nostop, notty, tunpoll, nommap, tunkqfilter, D_OTHER,
101 };
102 
103 void
104 tunattach(int unused)
105 {
106 
107 	simple_lock_init(&tun_softc_lock);
108 	LIST_INIT(&tun_softc_list);
109 	LIST_INIT(&tunz_softc_list);
110 	if_clone_attach(&tun_cloner);
111 }
112 
113 /*
114  * Find driver instance from dev_t.
115  * Call at splnet().
116  * Returns with tp locked (if found).
117  */
118 static struct tun_softc *
119 tun_find_unit(dev_t dev)
120 {
121 	struct tun_softc *tp;
122 	int unit = minor(dev);
123 
124 	simple_lock(&tun_softc_lock);
125 	LIST_FOREACH(tp, &tun_softc_list, tun_list)
126 		if (unit == tp->tun_unit)
127 			break;
128 	if (tp)
129 		simple_lock(&tp->tun_lock);
130 	simple_unlock(&tun_softc_lock);
131 
132 	return (tp);
133 }
134 
135 /*
136  * Find zombie driver instance by unit number.
137  * Call at splnet().
138  * Remove tp from list and return it unlocked (if found).
139  */
140 static struct tun_softc *
141 tun_find_zunit(int unit)
142 {
143 	struct tun_softc *tp;
144 
145 	simple_lock(&tun_softc_lock);
146 	LIST_FOREACH(tp, &tunz_softc_list, tun_list)
147 		if (unit == tp->tun_unit)
148 			break;
149 	if (tp)
150 		LIST_REMOVE(tp, tun_list);
151 	simple_unlock(&tun_softc_lock);
152 #ifdef DIAGNOSTIC
153 	if (tp != NULL && (tp->tun_flags & (TUN_INITED|TUN_OPEN)) != TUN_OPEN)
154 		printf("tun%d: inconsistent flags: %x\n", unit, tp->tun_flags);
155 #endif
156 
157 	return (tp);
158 }
159 
160 static int
161 tun_clone_create(struct if_clone *ifc, int unit)
162 {
163 	struct tun_softc *tp;
164 
165 	if ((tp = tun_find_zunit(unit)) == NULL) {
166 		/* Allocate a new instance */
167 		tp = malloc(sizeof(*tp), M_DEVBUF, M_WAITOK|M_ZERO);
168 
169 		tp->tun_unit = unit;
170 		simple_lock_init(&tp->tun_lock);
171 		selinit(&tp->tun_rsel);
172 		selinit(&tp->tun_wsel);
173 	} else {
174 		/* Revive tunnel instance; clear ifp part */
175 		(void)memset(&tp->tun_if, 0, sizeof(struct ifnet));
176 	}
177 
178 	if_initname(&tp->tun_if, ifc->ifc_name, unit);
179 	tunattach0(tp);
180 	tp->tun_flags |= TUN_INITED;
181 	tp->tun_osih = softint_establish(SOFTINT_CLOCK, tun_o_softintr, tp);
182 	tp->tun_isih = softint_establish(SOFTINT_CLOCK, tun_i_softintr, tp);
183 
184 	simple_lock(&tun_softc_lock);
185 	LIST_INSERT_HEAD(&tun_softc_list, tp, tun_list);
186 	simple_unlock(&tun_softc_lock);
187 
188 	return (0);
189 }
190 
191 static void
192 tunattach0(struct tun_softc *tp)
193 {
194 	struct ifnet *ifp;
195 
196 	ifp = &tp->tun_if;
197 	ifp->if_softc = tp;
198 	ifp->if_mtu = TUNMTU;
199 	ifp->if_ioctl = tun_ioctl;
200 	ifp->if_output = tun_output;
201 #ifdef ALTQ
202 	ifp->if_start = tunstart;
203 #endif
204 	ifp->if_flags = IFF_POINTOPOINT;
205 	ifp->if_type = IFT_TUNNEL;
206 	ifp->if_snd.ifq_maxlen = ifqmaxlen;
207 	ifp->if_collisions = 0;
208 	ifp->if_ierrors = 0;
209 	ifp->if_oerrors = 0;
210 	ifp->if_ipackets = 0;
211 	ifp->if_opackets = 0;
212 	ifp->if_ibytes   = 0;
213 	ifp->if_obytes   = 0;
214 	ifp->if_dlt = DLT_NULL;
215 	IFQ_SET_READY(&ifp->if_snd);
216 	if_attach(ifp);
217 	if_alloc_sadl(ifp);
218 	bpf_attach(ifp, DLT_NULL, sizeof(uint32_t));
219 }
220 
221 static int
222 tun_clone_destroy(struct ifnet *ifp)
223 {
224 	struct tun_softc *tp = (void *)ifp;
225 	int s, zombie = 0;
226 
227 	s = splnet();
228 	simple_lock(&tun_softc_lock);
229 	simple_lock(&tp->tun_lock);
230 	LIST_REMOVE(tp, tun_list);
231 	if (tp->tun_flags & TUN_OPEN) {
232 		/* Hang on to storage until last close */
233 		zombie = 1;
234 		tp->tun_flags &= ~TUN_INITED;
235 		LIST_INSERT_HEAD(&tunz_softc_list, tp, tun_list);
236 	}
237 	simple_unlock(&tun_softc_lock);
238 
239 	IF_PURGE(&ifp->if_snd);
240 	ifp->if_flags &= ~IFF_RUNNING;
241 
242 	if (tp->tun_flags & TUN_RWAIT) {
243 		tp->tun_flags &= ~TUN_RWAIT;
244 		wakeup((void *)tp);
245 	}
246 	selnotify(&tp->tun_rsel, 0, 0);
247 
248 	simple_unlock(&tp->tun_lock);
249 	splx(s);
250 
251 	if (tp->tun_flags & TUN_ASYNC && tp->tun_pgid)
252 		fownsignal(tp->tun_pgid, SIGIO, POLL_HUP, 0, NULL);
253 
254 	bpf_detach(ifp);
255 	if_detach(ifp);
256 
257 	if (!zombie) {
258 		seldestroy(&tp->tun_rsel);
259 		seldestroy(&tp->tun_wsel);
260 		softint_disestablish(tp->tun_osih);
261 		softint_disestablish(tp->tun_isih);
262 		free(tp, M_DEVBUF);
263 	}
264 
265 	return (0);
266 }
267 
268 /*
269  * tunnel open - must be superuser & the device must be
270  * configured in
271  */
272 static int
273 tunopen(dev_t dev, int flag, int mode, struct lwp *l)
274 {
275 	struct ifnet	*ifp;
276 	struct tun_softc *tp;
277 	int	s, error;
278 
279 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE_TUN,
280 	    KAUTH_REQ_NETWORK_INTERFACE_TUN_ADD, NULL, NULL, NULL);
281 	if (error)
282 		return (error);
283 
284 	s = splnet();
285 	tp = tun_find_unit(dev);
286 
287 	if (tp == NULL) {
288 		(void)tun_clone_create(&tun_cloner, minor(dev));
289 		tp = tun_find_unit(dev);
290 		if (tp == NULL) {
291 			error = ENXIO;
292 			goto out_nolock;
293 		}
294 	}
295 
296 	if (tp->tun_flags & TUN_OPEN) {
297 		error = EBUSY;
298 		goto out;
299 	}
300 
301 	ifp = &tp->tun_if;
302 	tp->tun_flags |= TUN_OPEN;
303 	TUNDEBUG("%s: open\n", ifp->if_xname);
304 out:
305 	simple_unlock(&tp->tun_lock);
306 out_nolock:
307 	splx(s);
308 	return (error);
309 }
310 
311 /*
312  * tunclose - close the device - mark i/f down & delete
313  * routing info
314  */
315 int
316 tunclose(dev_t dev, int flag, int mode,
317     struct lwp *l)
318 {
319 	int	s;
320 	struct tun_softc *tp;
321 	struct ifnet	*ifp;
322 
323 	s = splnet();
324 	if ((tp = tun_find_zunit(minor(dev))) != NULL) {
325 		/* interface was "destroyed" before the close */
326 		seldestroy(&tp->tun_rsel);
327 		seldestroy(&tp->tun_wsel);
328 		softint_disestablish(tp->tun_osih);
329 		softint_disestablish(tp->tun_isih);
330 		free(tp, M_DEVBUF);
331 		goto out_nolock;
332 	}
333 
334 	if ((tp = tun_find_unit(dev)) == NULL)
335 		goto out_nolock;
336 
337 	ifp = &tp->tun_if;
338 
339 	tp->tun_flags &= ~TUN_OPEN;
340 
341 	/*
342 	 * junk all pending output
343 	 */
344 	IFQ_PURGE(&ifp->if_snd);
345 
346 	if (ifp->if_flags & IFF_UP) {
347 		if_down(ifp);
348 		if (ifp->if_flags & IFF_RUNNING) {
349 			/* find internet addresses and delete routes */
350 			struct ifaddr *ifa;
351 			IFADDR_FOREACH(ifa, ifp) {
352 #if defined(INET) || defined(INET6)
353 				if (ifa->ifa_addr->sa_family == AF_INET ||
354 				    ifa->ifa_addr->sa_family == AF_INET6) {
355 					rtinit(ifa, (int)RTM_DELETE,
356 					       tp->tun_flags & TUN_DSTADDR
357 							? RTF_HOST
358 							: 0);
359 				}
360 #endif
361 			}
362 		}
363 	}
364 	tp->tun_pgid = 0;
365 	selnotify(&tp->tun_rsel, 0, 0);
366 
367 	TUNDEBUG ("%s: closed\n", ifp->if_xname);
368 	simple_unlock(&tp->tun_lock);
369 out_nolock:
370 	splx(s);
371 	return (0);
372 }
373 
374 /*
375  * Call at splnet().
376  */
377 static void
378 tuninit(struct tun_softc *tp)
379 {
380 	struct ifnet	*ifp = &tp->tun_if;
381 	struct ifaddr	*ifa;
382 
383 	TUNDEBUG("%s: tuninit\n", ifp->if_xname);
384 
385 	simple_lock(&tp->tun_lock);
386 	ifp->if_flags |= IFF_UP | IFF_RUNNING;
387 
388 	tp->tun_flags &= ~(TUN_IASET|TUN_DSTADDR);
389 	IFADDR_FOREACH(ifa, ifp) {
390 #ifdef INET
391 		if (ifa->ifa_addr->sa_family == AF_INET) {
392 			struct sockaddr_in *sin;
393 
394 			sin = satosin(ifa->ifa_addr);
395 			if (sin && sin->sin_addr.s_addr)
396 				tp->tun_flags |= TUN_IASET;
397 
398 			if (ifp->if_flags & IFF_POINTOPOINT) {
399 				sin = satosin(ifa->ifa_dstaddr);
400 				if (sin && sin->sin_addr.s_addr)
401 					tp->tun_flags |= TUN_DSTADDR;
402 			}
403 		}
404 #endif
405 #ifdef INET6
406 		if (ifa->ifa_addr->sa_family == AF_INET6) {
407 			struct sockaddr_in6 *sin;
408 
409 			sin = (struct sockaddr_in6 *)ifa->ifa_addr;
410 			if (!IN6_IS_ADDR_UNSPECIFIED(&sin->sin6_addr))
411 				tp->tun_flags |= TUN_IASET;
412 
413 			if (ifp->if_flags & IFF_POINTOPOINT) {
414 				sin = (struct sockaddr_in6 *)ifa->ifa_dstaddr;
415 				if (sin &&
416 				    !IN6_IS_ADDR_UNSPECIFIED(&sin->sin6_addr))
417 					tp->tun_flags |= TUN_DSTADDR;
418 			} else
419 				tp->tun_flags &= ~TUN_DSTADDR;
420 		}
421 #endif /* INET6 */
422 	}
423 
424 	simple_unlock(&tp->tun_lock);
425 	return;
426 }
427 
428 /*
429  * Process an ioctl request.
430  */
431 static int
432 tun_ioctl(struct ifnet *ifp, u_long cmd, void *data)
433 {
434 	int		error = 0, s;
435 	struct tun_softc *tp = (struct tun_softc *)(ifp->if_softc);
436 	struct ifreq *ifr = data;
437 
438 	s = splnet();
439 
440 	switch (cmd) {
441 	case SIOCINITIFADDR:
442 		tuninit(tp);
443 		TUNDEBUG("%s: address set\n", ifp->if_xname);
444 		break;
445 	case SIOCSIFBRDADDR:
446 		TUNDEBUG("%s: broadcast address set\n", ifp->if_xname);
447 		break;
448 	case SIOCSIFMTU:
449 		if (ifr->ifr_mtu > TUNMTU || ifr->ifr_mtu < 576) {
450 			error = EINVAL;
451 			break;
452 		}
453 		TUNDEBUG("%s: interface mtu set\n", ifp->if_xname);
454 		if ((error = ifioctl_common(ifp, cmd, data)) == ENETRESET)
455 			error = 0;
456 		break;
457 	case SIOCADDMULTI:
458 	case SIOCDELMULTI:
459 		if (ifr == NULL) {
460 	        	error = EAFNOSUPPORT;           /* XXX */
461 			break;
462 		}
463 		switch (ifreq_getaddr(cmd, ifr)->sa_family) {
464 #ifdef INET
465 		case AF_INET:
466 			break;
467 #endif
468 #ifdef INET6
469 		case AF_INET6:
470 			break;
471 #endif
472 		default:
473 			error = EAFNOSUPPORT;
474 			break;
475 		}
476 		break;
477 	default:
478 		error = ifioctl_common(ifp, cmd, data);
479 	}
480 
481 	splx(s);
482 	return (error);
483 }
484 
485 /*
486  * tun_output - queue packets from higher level ready to put out.
487  */
488 static int
489 tun_output(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst,
490     struct rtentry *rt)
491 {
492 	struct tun_softc *tp = ifp->if_softc;
493 	int		s;
494 	int		error;
495 #if defined(INET) || defined(INET6)
496 	int		mlen;
497 	uint32_t	*af;
498 #endif
499 	ALTQ_DECL(struct altq_pktattr pktattr;)
500 
501 	s = splnet();
502 	simple_lock(&tp->tun_lock);
503 	TUNDEBUG ("%s: tun_output\n", ifp->if_xname);
504 
505 	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
506 		TUNDEBUG ("%s: not ready 0%o\n", ifp->if_xname,
507 			  tp->tun_flags);
508 		m_freem (m0);
509 		error = EHOSTDOWN;
510 		goto out;
511 	}
512 
513 	/*
514 	 * if the queueing discipline needs packet classification,
515 	 * do it before prepending link headers.
516 	 */
517 	IFQ_CLASSIFY(&ifp->if_snd, m0, dst->sa_family, &pktattr);
518 
519 	bpf_mtap_af(ifp, dst->sa_family, m0);
520 
521 	switch(dst->sa_family) {
522 #ifdef INET6
523 	case AF_INET6:
524 #endif
525 #ifdef INET
526 	case AF_INET:
527 #endif
528 #if defined(INET) || defined(INET6)
529 		if (tp->tun_flags & TUN_PREPADDR) {
530 			/* Simple link-layer header */
531 			M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
532 			if (m0 == NULL) {
533 				IF_DROP(&ifp->if_snd);
534 				error = ENOBUFS;
535 				goto out;
536 			}
537 			bcopy(dst, mtod(m0, char *), dst->sa_len);
538 		}
539 
540 		if (tp->tun_flags & TUN_IFHEAD) {
541 			/* Prepend the address family */
542 			M_PREPEND(m0, sizeof(*af), M_DONTWAIT);
543 			if (m0 == NULL) {
544 				IF_DROP(&ifp->if_snd);
545 				error = ENOBUFS;
546 				goto out;
547 			}
548 			af = mtod(m0,uint32_t *);
549 			*af = htonl(dst->sa_family);
550 		} else {
551 #ifdef INET
552 			if (dst->sa_family != AF_INET)
553 #endif
554 			{
555 				m_freem(m0);
556 				error = EAFNOSUPPORT;
557 				goto out;
558 			}
559 		}
560 		/* FALLTHROUGH */
561 	case AF_UNSPEC:
562 		IFQ_ENQUEUE(&ifp->if_snd, m0, &pktattr, error);
563 		if (error) {
564 			ifp->if_collisions++;
565 			error = EAFNOSUPPORT;
566 			goto out;
567 		}
568 		mlen = m0->m_pkthdr.len;
569 		ifp->if_opackets++;
570 		ifp->if_obytes += mlen;
571 		break;
572 #endif
573 	default:
574 		m_freem(m0);
575 		error = EAFNOSUPPORT;
576 		goto out;
577 	}
578 
579 	if (tp->tun_flags & TUN_RWAIT) {
580 		tp->tun_flags &= ~TUN_RWAIT;
581 		wakeup((void *)tp);
582 	}
583 	if (tp->tun_flags & TUN_ASYNC && tp->tun_pgid)
584 		softint_schedule(tp->tun_isih);
585 
586 	selnotify(&tp->tun_rsel, 0, 0);
587 out:
588 	simple_unlock(&tp->tun_lock);
589 	splx(s);
590 	return (0);
591 }
592 
593 static void
594 tun_i_softintr(void *cookie)
595 {
596 	struct tun_softc *tp = cookie;
597 
598 	if (tp->tun_flags & TUN_ASYNC && tp->tun_pgid)
599 		fownsignal(tp->tun_pgid, SIGIO, POLL_IN, POLLIN|POLLRDNORM,
600 		    NULL);
601 }
602 
603 static void
604 tun_o_softintr(void *cookie)
605 {
606 	struct tun_softc *tp = cookie;
607 
608 	if (tp->tun_flags & TUN_ASYNC && tp->tun_pgid)
609 		fownsignal(tp->tun_pgid, SIGIO, POLL_OUT, POLLOUT|POLLWRNORM,
610 		    NULL);
611 }
612 
613 /*
614  * the cdevsw interface is now pretty minimal.
615  */
616 int
617 tunioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
618 {
619 	struct tun_softc *tp;
620 	int s, error = 0;
621 
622 	s = splnet();
623 	tp = tun_find_unit(dev);
624 
625 	/* interface was "destroyed" already */
626 	if (tp == NULL) {
627 		error = ENXIO;
628 		goto out_nolock;
629 	}
630 
631 	switch (cmd) {
632 	case TUNSDEBUG:
633 		tundebug = *(int *)data;
634 		break;
635 
636 	case TUNGDEBUG:
637 		*(int *)data = tundebug;
638 		break;
639 
640 	case TUNSIFMODE:
641 		switch (*(int *)data & (IFF_POINTOPOINT|IFF_BROADCAST)) {
642 		case IFF_POINTOPOINT:
643 		case IFF_BROADCAST:
644 			if (tp->tun_if.if_flags & IFF_UP) {
645 				error = EBUSY;
646 				goto out;
647 			}
648 			tp->tun_if.if_flags &=
649 				~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
650 			tp->tun_if.if_flags |= *(int *)data;
651 			break;
652 		default:
653 			error = EINVAL;
654 			goto out;
655 		}
656 		break;
657 
658 	case TUNSLMODE:
659 		if (*(int *)data) {
660 			tp->tun_flags |= TUN_PREPADDR;
661 			tp->tun_flags &= ~TUN_IFHEAD;
662 		} else
663 			tp->tun_flags &= ~TUN_PREPADDR;
664 		break;
665 
666 	case TUNSIFHEAD:
667 		if (*(int *)data) {
668 			tp->tun_flags |= TUN_IFHEAD;
669 			tp->tun_flags &= ~TUN_PREPADDR;
670 		} else
671 			tp->tun_flags &= ~TUN_IFHEAD;
672 		break;
673 
674 	case TUNGIFHEAD:
675 		*(int *)data = (tp->tun_flags & TUN_IFHEAD);
676 		break;
677 
678 	case FIONBIO:
679 		if (*(int *)data)
680 			tp->tun_flags |= TUN_NBIO;
681 		else
682 			tp->tun_flags &= ~TUN_NBIO;
683 		break;
684 
685 	case FIOASYNC:
686 		if (*(int *)data)
687 			tp->tun_flags |= TUN_ASYNC;
688 		else
689 			tp->tun_flags &= ~TUN_ASYNC;
690 		break;
691 
692 	case FIONREAD:
693 		if (tp->tun_if.if_snd.ifq_head)
694 			*(int *)data = tp->tun_if.if_snd.ifq_head->m_pkthdr.len;
695 		else
696 			*(int *)data = 0;
697 		break;
698 
699 	case TIOCSPGRP:
700 	case FIOSETOWN:
701 		error = fsetown(&tp->tun_pgid, cmd, data);
702 		break;
703 
704 	case TIOCGPGRP:
705 	case FIOGETOWN:
706 		error = fgetown(tp->tun_pgid, cmd, data);
707 		break;
708 
709 	default:
710 		error = ENOTTY;
711 	}
712 
713 out:
714 	simple_unlock(&tp->tun_lock);
715 out_nolock:
716 	splx(s);
717 	return (error);
718 }
719 
720 /*
721  * The cdevsw read interface - reads a packet at a time, or at
722  * least as much of a packet as can be read.
723  */
724 int
725 tunread(dev_t dev, struct uio *uio, int ioflag)
726 {
727 	struct tun_softc *tp;
728 	struct ifnet	*ifp;
729 	struct mbuf	*m, *m0;
730 	int		error = 0, len, s, index;
731 
732 	s = splnet();
733 	tp = tun_find_unit(dev);
734 
735 	/* interface was "destroyed" already */
736 	if (tp == NULL) {
737 		error = ENXIO;
738 		goto out_nolock;
739 	}
740 
741 	index = tp->tun_if.if_index;
742 	ifp = &tp->tun_if;
743 
744 	TUNDEBUG ("%s: read\n", ifp->if_xname);
745 	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
746 		TUNDEBUG ("%s: not ready 0%o\n", ifp->if_xname, tp->tun_flags);
747 		error = EHOSTDOWN;
748 		goto out;
749 	}
750 
751 	tp->tun_flags &= ~TUN_RWAIT;
752 
753 	do {
754 		IFQ_DEQUEUE(&ifp->if_snd, m0);
755 		if (m0 == 0) {
756 			if (tp->tun_flags & TUN_NBIO) {
757 				error = EWOULDBLOCK;
758 				goto out;
759 			}
760 			tp->tun_flags |= TUN_RWAIT;
761 			if (ltsleep((void *)tp, PZERO|PCATCH|PNORELOCK,
762 					"tunread", 0, &tp->tun_lock) != 0) {
763 				error = EINTR;
764 				goto out_nolock;
765 			} else {
766 				/*
767 				 * Maybe the interface was destroyed while
768 				 * we were sleeping, so let's ensure that
769 				 * we're looking at the same (valid) tun
770 				 * interface before looping.
771 				 */
772 				tp = tun_find_unit(dev);
773 				if (tp == NULL) {
774 					error = ENXIO;
775 					goto out_nolock;
776 				}
777 				if (tp->tun_if.if_index != index) {
778 					error = ENXIO;
779 					goto out;
780 				}
781 			}
782 		}
783 	} while (m0 == 0);
784 
785 	simple_unlock(&tp->tun_lock);
786 	splx(s);
787 
788 	/* Copy the mbuf chain */
789 	while (m0 && uio->uio_resid > 0 && error == 0) {
790 		len = min(uio->uio_resid, m0->m_len);
791 		if (len != 0)
792 			error = uiomove(mtod(m0, void *), len, uio);
793 		MFREE(m0, m);
794 		m0 = m;
795 	}
796 
797 	if (m0) {
798 		TUNDEBUG("Dropping mbuf\n");
799 		m_freem(m0);
800 	}
801 	if (error)
802 		ifp->if_ierrors++;
803 
804 	return (error);
805 
806 out:
807 	simple_unlock(&tp->tun_lock);
808 out_nolock:
809 	splx(s);
810 	return (error);
811 }
812 
813 /*
814  * the cdevsw write interface - an atomic write is a packet - or else!
815  */
816 int
817 tunwrite(dev_t dev, struct uio *uio, int ioflag)
818 {
819 	struct tun_softc *tp;
820 	struct ifnet	*ifp;
821 	struct mbuf	*top, **mp, *m;
822 	struct ifqueue	*ifq;
823 	struct sockaddr	dst;
824 	int		isr, error = 0, s, tlen, mlen;
825 	uint32_t	family;
826 
827 	s = splnet();
828 	tp = tun_find_unit(dev);
829 
830 	/* interface was "destroyed" already */
831 	if (tp == NULL) {
832 		error = ENXIO;
833 		goto out_nolock;
834 	}
835 
836 	/* Unlock until we've got the data */
837 	simple_unlock(&tp->tun_lock);
838 	splx(s);
839 
840 	ifp = &tp->tun_if;
841 
842 	TUNDEBUG("%s: tunwrite\n", ifp->if_xname);
843 
844 	if (tp->tun_flags & TUN_PREPADDR) {
845 		if (uio->uio_resid < sizeof(dst)) {
846 			error = EIO;
847 			goto out0;
848 		}
849 		error = uiomove((void *)&dst, sizeof(dst), uio);
850 		if (dst.sa_len > sizeof(dst)) {
851 			/* Duh.. */
852 			char discard;
853 			int n = dst.sa_len - sizeof(dst);
854 			while (n--)
855 				if ((error = uiomove(&discard, 1, uio)) != 0) {
856 					goto out0;
857 				}
858 		}
859 	} else if (tp->tun_flags & TUN_IFHEAD) {
860 		if (uio->uio_resid < sizeof(family)){
861 			error = EIO;
862 			goto out0;
863 		}
864 		error = uiomove((void *)&family, sizeof(family), uio);
865 		dst.sa_family = ntohl(family);
866 	} else {
867 #ifdef INET
868 		dst.sa_family = AF_INET;
869 #endif
870 	}
871 
872 	if (uio->uio_resid > TUNMTU) {
873 		TUNDEBUG("%s: len=%lu!\n", ifp->if_xname,
874 		    (unsigned long)uio->uio_resid);
875 		error = EIO;
876 		goto out0;
877 	}
878 
879 	switch (dst.sa_family) {
880 #ifdef INET
881 	case AF_INET:
882 		ifq = &ipintrq;
883 		isr = NETISR_IP;
884 		break;
885 #endif
886 #ifdef INET6
887 	case AF_INET6:
888 		ifq = &ip6intrq;
889 		isr = NETISR_IPV6;
890 		break;
891 #endif
892 	default:
893 		error = EAFNOSUPPORT;
894 		goto out0;
895 	}
896 
897 	tlen = uio->uio_resid;
898 
899 	/* get a header mbuf */
900 	MGETHDR(m, M_DONTWAIT, MT_DATA);
901 	if (m == NULL) {
902 		error = ENOBUFS;
903 		goto out0;
904 	}
905 	mlen = MHLEN;
906 
907 	top = NULL;
908 	mp = &top;
909 	while (error == 0 && uio->uio_resid > 0) {
910 		m->m_len = min(mlen, uio->uio_resid);
911 		error = uiomove(mtod(m, void *), m->m_len, uio);
912 		*mp = m;
913 		mp = &m->m_next;
914 		if (error == 0 && uio->uio_resid > 0) {
915 			MGET(m, M_DONTWAIT, MT_DATA);
916 			if (m == NULL) {
917 				error = ENOBUFS;
918 				break;
919 			}
920 			mlen = MLEN;
921 		}
922 	}
923 	if (error) {
924 		if (top != NULL)
925 			m_freem (top);
926 		ifp->if_ierrors++;
927 		goto out0;
928 	}
929 
930 	top->m_pkthdr.len = tlen;
931 	top->m_pkthdr.rcvif = ifp;
932 
933 	bpf_mtap_af(ifp, dst.sa_family, top);
934 
935 	s = splnet();
936 	simple_lock(&tp->tun_lock);
937 	if ((tp->tun_flags & TUN_INITED) == 0) {
938 		/* Interface was destroyed */
939 		error = ENXIO;
940 		goto out;
941 	}
942 	if (IF_QFULL(ifq)) {
943 		IF_DROP(ifq);
944 		ifp->if_collisions++;
945 		m_freem(top);
946 		error = ENOBUFS;
947 		goto out;
948 	}
949 
950 	IF_ENQUEUE(ifq, top);
951 	ifp->if_ipackets++;
952 	ifp->if_ibytes += tlen;
953 	schednetisr(isr);
954 out:
955 	simple_unlock(&tp->tun_lock);
956 out_nolock:
957 	splx(s);
958 out0:
959 	return (error);
960 }
961 
962 #ifdef ALTQ
963 /*
964  * Start packet transmission on the interface.
965  * when the interface queue is rate-limited by ALTQ or TBR,
966  * if_start is needed to drain packets from the queue in order
967  * to notify readers when outgoing packets become ready.
968  *
969  * Should be called at splnet.
970  */
971 static void
972 tunstart(struct ifnet *ifp)
973 {
974 	struct tun_softc *tp = ifp->if_softc;
975 
976 	if (!ALTQ_IS_ENABLED(&ifp->if_snd) && !TBR_IS_ENABLED(&ifp->if_snd))
977 		return;
978 
979 	simple_lock(&tp->tun_lock);
980 	if (!IF_IS_EMPTY(&ifp->if_snd)) {
981 		if (tp->tun_flags & TUN_RWAIT) {
982 			tp->tun_flags &= ~TUN_RWAIT;
983 			wakeup((void *)tp);
984 		}
985 		if (tp->tun_flags & TUN_ASYNC && tp->tun_pgid)
986 			softint_schedule(tp->tun_osih);
987 
988 		selnotify(&tp->tun_rsel, 0, 0);
989 	}
990 	simple_unlock(&tp->tun_lock);
991 }
992 #endif /* ALTQ */
993 /*
994  * tunpoll - the poll interface, this is only useful on reads
995  * really. The write detect always returns true, write never blocks
996  * anyway, it either accepts the packet or drops it.
997  */
998 int
999 tunpoll(dev_t dev, int events, struct lwp *l)
1000 {
1001 	struct tun_softc *tp;
1002 	struct ifnet	*ifp;
1003 	int		s, revents = 0;
1004 
1005 	s = splnet();
1006 	tp = tun_find_unit(dev);
1007 
1008 	/* interface was "destroyed" already */
1009 	if (tp == NULL)
1010 		goto out_nolock;
1011 
1012 	ifp = &tp->tun_if;
1013 
1014 	TUNDEBUG("%s: tunpoll\n", ifp->if_xname);
1015 
1016 	if (events & (POLLIN | POLLRDNORM)) {
1017 		if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
1018 			TUNDEBUG("%s: tunpoll q=%d\n", ifp->if_xname,
1019 			    ifp->if_snd.ifq_len);
1020 			revents |= events & (POLLIN | POLLRDNORM);
1021 		} else {
1022 			TUNDEBUG("%s: tunpoll waiting\n", ifp->if_xname);
1023 			selrecord(l, &tp->tun_rsel);
1024 		}
1025 	}
1026 
1027 	if (events & (POLLOUT | POLLWRNORM))
1028 		revents |= events & (POLLOUT | POLLWRNORM);
1029 
1030 	simple_unlock(&tp->tun_lock);
1031 out_nolock:
1032 	splx(s);
1033 	return (revents);
1034 }
1035 
1036 static void
1037 filt_tunrdetach(struct knote *kn)
1038 {
1039 	struct tun_softc *tp = kn->kn_hook;
1040 	int s;
1041 
1042 	s = splnet();
1043 	SLIST_REMOVE(&tp->tun_rsel.sel_klist, kn, knote, kn_selnext);
1044 	splx(s);
1045 }
1046 
1047 static int
1048 filt_tunread(struct knote *kn, long hint)
1049 {
1050 	struct tun_softc *tp = kn->kn_hook;
1051 	struct ifnet *ifp = &tp->tun_if;
1052 	struct mbuf *m;
1053 	int s;
1054 
1055 	s = splnet();
1056 	IF_POLL(&ifp->if_snd, m);
1057 	if (m == NULL) {
1058 		splx(s);
1059 		return (0);
1060 	}
1061 
1062 	for (kn->kn_data = 0; m != NULL; m = m->m_next)
1063 		kn->kn_data += m->m_len;
1064 
1065 	splx(s);
1066 	return (1);
1067 }
1068 
1069 static const struct filterops tunread_filtops =
1070 	{ 1, NULL, filt_tunrdetach, filt_tunread };
1071 
1072 static const struct filterops tun_seltrue_filtops =
1073 	{ 1, NULL, filt_tunrdetach, filt_seltrue };
1074 
1075 int
1076 tunkqfilter(dev_t dev, struct knote *kn)
1077 {
1078 	struct tun_softc *tp;
1079 	struct klist *klist;
1080 	int rv = 0, s;
1081 
1082 	s = splnet();
1083 	tp = tun_find_unit(dev);
1084 	if (tp == NULL)
1085 		goto out_nolock;
1086 
1087 	switch (kn->kn_filter) {
1088 	case EVFILT_READ:
1089 		klist = &tp->tun_rsel.sel_klist;
1090 		kn->kn_fop = &tunread_filtops;
1091 		break;
1092 
1093 	case EVFILT_WRITE:
1094 		klist = &tp->tun_rsel.sel_klist;
1095 		kn->kn_fop = &tun_seltrue_filtops;
1096 		break;
1097 
1098 	default:
1099 		rv = EINVAL;
1100 		goto out;
1101 	}
1102 
1103 	kn->kn_hook = tp;
1104 
1105 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1106 
1107 out:
1108 	simple_unlock(&tp->tun_lock);
1109 out_nolock:
1110 	splx(s);
1111 	return (rv);
1112 }
1113