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