xref: /dragonfly/sys/net/tun/if_tun.c (revision 9317c2d0)
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: src/sys/net/if_tun.c,v 1.74.2.8 2002/02/13 00:43:11 dillon Exp $
17  */
18 
19 #include "opt_inet.h"
20 #include "opt_inet6.h"
21 
22 #include <sys/param.h>
23 #include <sys/proc.h>
24 #include <sys/priv.h>
25 #include <sys/systm.h>
26 #include <sys/mbuf.h>
27 #include <sys/socket.h>
28 #include <sys/conf.h>
29 #include <sys/device.h>
30 #include <sys/filio.h>
31 #include <sys/sockio.h>
32 #include <sys/ttycom.h>
33 #include <sys/signalvar.h>
34 #include <sys/filedesc.h>
35 #include <sys/kernel.h>
36 #include <sys/sysctl.h>
37 #include <sys/uio.h>
38 #include <sys/vnode.h>
39 #include <sys/malloc.h>
40 #include <sys/mplock2.h>
41 #include <sys/devfs.h>
42 #include <sys/queue.h>
43 
44 #include <net/bpf.h>
45 #include <net/if.h>
46 #include <net/if_types.h>
47 #include <net/if_clone.h>
48 #include <net/ifq_var.h>
49 #include <net/netisr.h>
50 #include <net/route.h>
51 
52 #ifdef INET
53 #include <netinet/in.h>
54 #endif
55 
56 #include "if_tunvar.h"
57 #include "if_tun.h"
58 
59 #define TUN		"tun"
60 #define TUNDEBUG	if (tundebug) if_printf
61 
62 /* module */
63 static int		tunmodevent(module_t, int, void *);
64 
65 /* device */
66 static struct tun_softc *tuncreate(cdev_t, int);
67 static void		tundestroy(struct tun_softc *sc);
68 
69 /* clone */
70 static int		tun_clone_create(struct if_clone *, int,
71 					 caddr_t, caddr_t);
72 static int		tun_clone_destroy(struct ifnet *);
73 
74 /* network interface */
75 static int		tunifinit(struct ifnet *);
76 static void		tunifstart(struct ifnet *, struct ifaltq_subque *);
77 static int		tunifoutput(struct ifnet *, struct mbuf *,
78 				    struct sockaddr *, struct rtentry *rt);
79 static int		tunifioctl(struct ifnet *, u_long,
80 				   caddr_t, struct ucred *);
81 
82 /* character device */
83 static d_open_t		tunopen;
84 static d_close_t	tunclose;
85 static d_read_t		tunread;
86 static d_write_t	tunwrite;
87 static d_ioctl_t	tunioctl;
88 static d_kqfilter_t	tunkqfilter;
89 static d_clone_t	tunclone;
90 
91 static struct dev_ops	tun_ops = {
92 	{ TUN, 0, 0 },
93 	.d_open =	tunopen,
94 	.d_close =	tunclose,
95 	.d_read =	tunread,
96 	.d_write =	tunwrite,
97 	.d_ioctl =	tunioctl,
98 	.d_kqfilter =	tunkqfilter
99 };
100 
101 /* kqueue support */
102 static void		tun_filter_detach(struct knote *);
103 static int		tun_filter_read(struct knote *, long);
104 static int		tun_filter_write(struct knote *, long);
105 
106 static struct filterops tun_read_filtops = {
107 	FILTEROP_ISFD,
108 	NULL,
109 	tun_filter_detach,
110 	tun_filter_read
111 };
112 static struct filterops tun_write_filtops = {
113 	FILTEROP_ISFD,
114 	NULL,
115 	tun_filter_detach,
116 	tun_filter_write
117 };
118 
119 static int		tundebug = 0;	/* debug flag */
120 static int		tunrefcnt = 0;	/* module reference counter */
121 
122 static MALLOC_DEFINE(M_TUN, TUN, "Tunnel Interface");
123 
124 static DEVFS_DEFINE_CLONE_BITMAP(tun);
125 
126 struct if_clone tun_cloner = IF_CLONE_INITIALIZER(
127 	TUN, tun_clone_create, tun_clone_destroy, 0, IF_MAXUNIT);
128 
129 static SLIST_HEAD(,tun_softc) tun_listhead =
130 	SLIST_HEAD_INITIALIZER(&tun_listhead);
131 
132 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0,
133 	   "Enable debug output");
134 SYSCTL_DECL(_net_link);
135 SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
136 	    "IP tunnel software network interface");
137 SYSCTL_INT(_net_link_tun, OID_AUTO, debug, CTLFLAG_RW, &tundebug, 0,
138 	   "Enable debug output");
139 SYSCTL_INT(_net_link_tun, OID_AUTO, refcnt, CTLFLAG_RD, &tunrefcnt, 0,
140 	   "Number of opened devices");
141 
142 DEV_MODULE(if_tun, tunmodevent, NULL);
143 
144 /*
145  * tunmodevent - module event handler
146  */
147 static int
148 tunmodevent(module_t mod, int type, void *data)
149 {
150 	static cdev_t dev = NULL;
151 	struct tun_softc *sc, *sc_tmp;
152 
153 	switch (type) {
154 	case MOD_LOAD:
155 		dev = make_autoclone_dev(&tun_ops, &DEVFS_CLONE_BITMAP(tun),
156 					 tunclone, UID_UUCP, GID_DIALER,
157 					 0600, TUN);
158 
159 		SLIST_INIT(&tun_listhead);
160 		if_clone_attach(&tun_cloner);
161 		break;
162 
163 	case MOD_UNLOAD:
164 		if (tunrefcnt > 0)
165 			return (EBUSY);
166 
167 		if_clone_detach(&tun_cloner);
168 
169 		SLIST_FOREACH_MUTABLE(sc, &tun_listhead, tun_link, sc_tmp)
170 			tundestroy(sc);
171 
172 		dev_ops_remove_all(&tun_ops);
173 		destroy_autoclone_dev(dev, &DEVFS_CLONE_BITMAP(tun));
174 		break;
175 
176 	default:
177 		return (EOPNOTSUPP);
178 	}
179 
180 	return (0);
181 }
182 
183 static int
184 tunclone(struct dev_clone_args *ap)
185 {
186 	char ifname[IFNAMSIZ];
187 	int unit;
188 
189 	unit = devfs_clone_bitmap_get(&DEVFS_CLONE_BITMAP(tun), 0);
190 	ksnprintf(ifname, IFNAMSIZ, "%s%d", TUN, unit);
191 	ap->a_dev = make_only_dev(&tun_ops, unit, UID_UUCP, GID_DIALER,
192 				  0600, "%s", ifname);
193 
194 	/*
195 	 * Use the if_clone framework to create cloned device/interface,
196 	 * so the two clone methods (autoclone device /dev/tun; ifconfig
197 	 * clone) are consistent and can be mix used.
198 	 *
199 	 * Need to pass the cdev_t because the device created by
200 	 * 'make_only_dev()' doesn't appear in '/dev' yet so that it can't
201 	 * be found by 'devfs_find_device_by_name()' in 'tun_clone_create()'.
202 	 */
203 	return (if_clone_create(ifname, IFNAMSIZ, NULL, (caddr_t)ap->a_dev));
204 }
205 
206 static struct tun_softc *
207 tuncreate(cdev_t dev, int flags)
208 {
209 	struct tun_softc *sc;
210 	struct ifnet *ifp;
211 	int unit = minor(dev);
212 
213 	sc = kmalloc(sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
214 	dev->si_drv1 = sc;
215 	sc->tun_dev = dev;
216 	sc->tun_flags = TUN_INITED;
217 	sc->tun_flags |= flags;
218 
219 	reference_dev(dev);  /* device association */
220 
221 	ifp = sc->tun_ifp = if_alloc(IFT_PPP);
222 	if (ifp == NULL) {
223 		kprintf("%s: failed to if_alloc() interface for %s%d",
224 			__func__, TUN, unit);
225 		return (NULL);
226 	}
227 
228 	if_initname(ifp, TUN, unit);
229 	ifp->if_mtu = TUNMTU;
230 	ifp->if_ioctl = tunifioctl;
231 	ifp->if_output = tunifoutput;
232 	ifp->if_start = tunifstart;
233 	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
234 	ifp->if_type = IFT_PPP;
235 	ifp->if_softc = sc;
236 	ifq_set_maxlen(&ifp->if_snd, ifqmaxlen);
237 	ifq_set_ready(&ifp->if_snd);
238 
239 	if_attach(ifp, NULL);
240 	bpfattach(ifp, DLT_NULL, sizeof(u_int));
241 
242 	SLIST_INSERT_HEAD(&tun_listhead, sc, tun_link);
243 	TUNDEBUG(ifp, "created, minor = %#x, flags = 0x%x\n",
244 		 unit, sc->tun_flags);
245 	return (sc);
246 }
247 
248 static void
249 tundestroy(struct tun_softc *sc)
250 {
251 	cdev_t dev = sc->tun_dev;
252 	struct ifnet *ifp = sc->tun_ifp;
253 	int unit = minor(dev);
254 
255 	TUNDEBUG(ifp, "destroyed, minor = %#x. Module refcnt = %d\n",
256 		 unit, tunrefcnt);
257 
258 	bpfdetach(ifp);
259 	if_detach(ifp);
260 	if_free(ifp);
261 
262 	sc->tun_dev = NULL;
263 	dev->si_drv1 = NULL;
264 	release_dev(dev);  /* device disassociation */
265 
266 	/* Also destroy the cloned device */
267 	destroy_dev(dev);
268 	devfs_clone_bitmap_put(&DEVFS_CLONE_BITMAP(tun), unit);
269 
270 	SLIST_REMOVE(&tun_listhead, sc, tun_softc, tun_link);
271 	kfree(sc, M_TUN);
272 }
273 
274 /*
275  * tunnel open - must be superuser & the device must be configured in
276  */
277 static int
278 tunopen(struct dev_open_args *ap)
279 {
280 	cdev_t dev = ap->a_head.a_dev;
281 	struct tun_softc *sc;
282 	int error;
283 
284 	if ((error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0)) != 0)
285 		return (error);
286 
287 	sc = dev->si_drv1;
288 	if (sc == NULL && (sc = tuncreate(dev, TUN_MANUALMAKE)) == NULL)
289 		return (ENOMEM);
290 	if (sc->tun_flags & TUN_OPEN)
291 		return (EBUSY);
292 
293 	sc->tun_pid = curproc->p_pid;
294 	sc->tun_flags |= TUN_OPEN;
295 	tunrefcnt++;
296 
297 	TUNDEBUG(sc->tun_ifp, "opened, minor = %#x. Module refcnt = %d\n",
298 		 minor(dev), tunrefcnt);
299 	return (0);
300 }
301 
302 /*
303  * close the device - mark interface down & delete routing info
304  */
305 static int
306 tunclose(struct dev_close_args *ap)
307 {
308 	cdev_t dev = ap->a_head.a_dev;
309 	struct tun_softc *sc = dev->si_drv1;
310 	struct ifnet *ifp;
311 	int unit = minor(dev);
312 
313 	KASSERT(sc != NULL,
314 		("try closing the already destroyed %s%d", TUN, unit));
315 	ifp = sc->tun_ifp;
316 
317 	sc->tun_flags &= ~TUN_OPEN;
318 	sc->tun_pid = 0;
319 
320 	/* Junk all pending output. */
321 	ifq_purge_all(&ifp->if_snd);
322 
323 	if (ifp->if_flags & IFF_UP)
324 		if_down(ifp);
325 	ifp->if_flags &= ~IFF_RUNNING;
326 
327 	if ((sc->tun_flags & TUN_CLONE) == 0) {
328 		if_purgeaddrs_nolink(ifp);
329 
330 		EVENTHANDLER_INVOKE(ifnet_detach_event, ifp);
331 
332 		/* Announce the departure of the interface. */
333 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
334 	}
335 
336 	funsetown(&sc->tun_sigio);
337 	KNOTE(&sc->tun_rkq.ki_note, 0);
338 
339 	tunrefcnt--;
340 	if (tunrefcnt < 0) {
341 		tunrefcnt = 0;
342 		if_printf(ifp, ". Module refcnt = %d is out of sync! "
343 			  "Force refcnt to be 0.\n", tunrefcnt);
344 	}
345 
346 	TUNDEBUG(ifp, "closed, minor = %#x. Module refcnt = %d\n",
347 		 unit, tunrefcnt);
348 
349 	/* Only auto-destroy if the interface was not manually created. */
350 	if ((sc->tun_flags & TUN_MANUALMAKE) == 0) {
351 		tundestroy(sc);
352 		dev->si_drv1 = NULL;
353 	}
354 
355 	return (0);
356 }
357 
358 
359 /*
360  * Interface clone support
361  *
362  * Create and destroy tun device/interface via ifconfig(8).
363  */
364 
365 static struct tun_softc *
366 tunfind(int unit)
367 {
368 	struct tun_softc *sc;
369 
370 	SLIST_FOREACH(sc, &tun_listhead, tun_link) {
371 		if (minor(sc->tun_dev) == unit)
372 			return (sc);
373 	}
374 	return (NULL);
375 }
376 
377 static int
378 tun_clone_create(struct if_clone *ifc __unused, int unit,
379 		 caddr_t params __unused, caddr_t data)
380 {
381 	struct tun_softc *sc;
382 	cdev_t dev = (cdev_t)data;
383 
384 	if (tunfind(unit) != NULL)
385 		return (EEXIST);
386 
387 	if (dev == NULL) {
388 		if (!devfs_clone_bitmap_chk(&DEVFS_CLONE_BITMAP(tun), unit)) {
389 			devfs_clone_bitmap_set(&DEVFS_CLONE_BITMAP(tun), unit);
390 			dev = make_dev(&tun_ops, unit, UID_UUCP, GID_DIALER,
391 				       0600, "%s%d", TUN, unit);
392 		} else {
393 			dev = devfs_find_device_by_name("%s%d", TUN, unit);
394 			if (dev == NULL)
395 				return (ENOENT);
396 		}
397 	}
398 
399 	if ((sc = tuncreate(dev, 0)) == NULL)
400 		return (ENOMEM);
401 
402 	sc->tun_flags |= TUN_CLONE;
403 	TUNDEBUG(sc->tun_ifp, "clone created, minor = %#x, flags = 0x%x\n",
404 		 minor(sc->tun_dev), sc->tun_flags);
405 
406 	return (0);
407 }
408 
409 static int
410 tun_clone_destroy(struct ifnet *ifp)
411 {
412 	struct tun_softc *sc = ifp->if_softc;
413 
414 	if (sc->tun_flags & TUN_OPEN)
415 		return (EBUSY);
416 	if ((sc->tun_flags & TUN_CLONE) == 0)
417 		return (EINVAL);
418 
419 	TUNDEBUG(ifp, "clone destroyed, minor = %#x, flags = 0x%x\n",
420 		 minor(sc->tun_dev), sc->tun_flags);
421 	tundestroy(sc);
422 
423 	return (0);
424 }
425 
426 
427 /*
428  * Network interface functions
429  */
430 
431 static int
432 tunifinit(struct ifnet *ifp)
433 {
434 #ifdef INET
435 	struct tun_softc *sc = ifp->if_softc;
436 #endif
437 	struct ifaddr_container *ifac;
438 	int error = 0;
439 
440 	TUNDEBUG(ifp, "initialize\n");
441 
442 	ifp->if_flags |= IFF_UP | IFF_RUNNING;
443 	getmicrotime(&ifp->if_lastchange);
444 
445 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
446 		struct ifaddr *ifa = ifac->ifa;
447 
448 		if (ifa->ifa_addr == NULL) {
449 			error = EFAULT;
450 			/* XXX: Should maybe return straight off? */
451 		} else {
452 #ifdef INET
453 			if (ifa->ifa_addr->sa_family == AF_INET) {
454 				struct sockaddr_in *si;
455 
456 				si = (struct sockaddr_in *)ifa->ifa_addr;
457 				if (si->sin_addr.s_addr)
458 					sc->tun_flags |= TUN_IASET;
459 			}
460 #endif
461 		}
462 	}
463 	return (error);
464 }
465 
466 /*
467  * Process an ioctl request.
468  *
469  * MPSAFE
470  */
471 static int
472 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
473 {
474 	struct ifreq *ifr = (struct ifreq *)data;
475 	struct tun_softc *sc = ifp->if_softc;
476 	struct ifstat *ifs;
477 	int error = 0;
478 
479 	switch (cmd) {
480 	case SIOCGIFSTATUS:
481 		ifs = (struct ifstat *)data;
482 		if (sc->tun_pid)
483 			ksprintf(ifs->ascii + strlen(ifs->ascii),
484 			    "\tOpened by PID %d\n", sc->tun_pid);
485 		break;
486 	case SIOCSIFADDR:
487 		error = tunifinit(ifp);
488 		TUNDEBUG(ifp, "address set, error=%d\n", error);
489 		break;
490 	case SIOCSIFDSTADDR:
491 		error = tunifinit(ifp);
492 		TUNDEBUG(ifp, "destination address set, error=%d\n", error);
493 		break;
494 	case SIOCSIFMTU:
495 		ifp->if_mtu = ifr->ifr_mtu;
496 		TUNDEBUG(ifp, "mtu set\n");
497 		break;
498 	case SIOCSIFFLAGS:
499 	case SIOCADDMULTI:
500 	case SIOCDELMULTI:
501 		break;
502 	default:
503 		error = EINVAL;
504 	}
505 	return (error);
506 }
507 
508 /*
509  * Start packet transmission on the interface.
510  * when the interface queue is rate-limited by ALTQ,
511  * if_start is needed to drain packets from the queue in order
512  * to notify readers when outgoing packets become ready.
513  */
514 static void
515 tunifstart(struct ifnet *ifp, struct ifaltq_subque *ifsq)
516 {
517 	struct tun_softc *sc = ifp->if_softc;
518 	struct mbuf *m;
519 
520 	ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
521 
522 	if (!ifq_is_enabled(&ifp->if_snd))
523 		return;
524 
525 	m = ifsq_poll(ifsq);
526 	if (m != NULL) {
527 		if (sc->tun_flags & TUN_RWAIT) {
528 			sc->tun_flags &= ~TUN_RWAIT;
529 			wakeup((caddr_t)sc);
530 		}
531 		if (sc->tun_flags & TUN_ASYNC && sc->tun_sigio)
532 			pgsigio(sc->tun_sigio, SIGIO, 0);
533 		ifsq_deserialize_hw(ifsq);
534 		KNOTE(&sc->tun_rkq.ki_note, 0);
535 		ifsq_serialize_hw(ifsq);
536 	}
537 }
538 
539 /*
540  * tunifoutput - queue packets from higher level ready to put out.
541  *
542  * MPSAFE
543  */
544 static int
545 tunifoutput_serialized(struct ifnet *ifp, struct mbuf *m0,
546 		       struct sockaddr *dst, struct rtentry *rt)
547 {
548 	struct tun_softc *sc = ifp->if_softc;
549 	int error;
550 	struct altq_pktattr pktattr;
551 
552 	TUNDEBUG(ifp, "output\n");
553 
554 	if ((sc->tun_flags & TUN_READY) != TUN_READY) {
555 		TUNDEBUG(ifp, "not ready, flags = 0x%x\n", sc->tun_flags);
556 		m_freem (m0);
557 		return (EHOSTDOWN);
558 	}
559 
560 	/*
561 	 * if the queueing discipline needs packet classification,
562 	 * do it before prepending link headers.
563 	 */
564 	ifq_classify(&ifp->if_snd, m0, dst->sa_family, &pktattr);
565 
566 	/* BPF write needs to be handled specially */
567 	if (dst->sa_family == AF_UNSPEC) {
568 		dst->sa_family = *(mtod(m0, int *));
569 		m0->m_len -= sizeof(int);
570 		m0->m_pkthdr.len -= sizeof(int);
571 		m0->m_data += sizeof(int);
572 	}
573 
574 	if (ifp->if_bpf) {
575 		bpf_gettoken();
576 		if (ifp->if_bpf) {
577 			/*
578 			 * We need to prepend the address family as
579 			 * a four byte field.
580 			 */
581 			uint32_t af = dst->sa_family;
582 
583 			bpf_ptap(ifp->if_bpf, m0, &af, sizeof(af));
584 		}
585 		bpf_reltoken();
586 	}
587 
588 	/* prepend sockaddr? this may abort if the mbuf allocation fails */
589 	if (sc->tun_flags & TUN_LMODE) {
590 		/* allocate space for sockaddr */
591 		M_PREPEND(m0, dst->sa_len, M_NOWAIT);
592 
593 		/* if allocation failed drop packet */
594 		if (m0 == NULL){
595 			IFNET_STAT_INC(ifp, oerrors, 1);
596 			return (ENOBUFS);
597 		} else {
598 			bcopy(dst, m0->m_data, dst->sa_len);
599 		}
600 	}
601 
602 	if (sc->tun_flags & TUN_IFHEAD) {
603 		/* Prepend the address family */
604 		M_PREPEND(m0, 4, M_NOWAIT);
605 
606 		/* if allocation failed drop packet */
607 		if (m0 == NULL){
608 			IFNET_STAT_INC(ifp, oerrors, 1);
609 			return (ENOBUFS);
610 		} else {
611 			*(u_int32_t *)m0->m_data = htonl(dst->sa_family);
612 		}
613 	} else {
614 #ifdef INET
615 		if (dst->sa_family != AF_INET)
616 #endif
617 		{
618 			m_freem(m0);
619 			return (EAFNOSUPPORT);
620 		}
621 	}
622 
623 	error = ifq_handoff(ifp, m0, &pktattr);
624 	if (error) {
625 		IFNET_STAT_INC(ifp, collisions, 1);
626 	} else {
627 		IFNET_STAT_INC(ifp, opackets, 1);
628 		if (sc->tun_flags & TUN_RWAIT) {
629 			sc->tun_flags &= ~TUN_RWAIT;
630 			wakeup((caddr_t)sc);
631 		}
632 		get_mplock();
633 		if (sc->tun_flags & TUN_ASYNC && sc->tun_sigio)
634 			pgsigio(sc->tun_sigio, SIGIO, 0);
635 		rel_mplock();
636 		ifnet_deserialize_all(ifp);
637 		KNOTE(&sc->tun_rkq.ki_note, 0);
638 		ifnet_serialize_all(ifp);
639 	}
640 	return (error);
641 }
642 
643 static int
644 tunifoutput(struct ifnet *ifp, struct mbuf *m0, struct sockaddr *dst,
645 	    struct rtentry *rt)
646 {
647 	int error;
648 
649 	ifnet_serialize_all(ifp);
650 	error = tunifoutput_serialized(ifp, m0, dst, rt);
651 	ifnet_deserialize_all(ifp);
652 
653 	return (error);
654 }
655 
656 
657 /*
658  * the ops interface is now pretty minimal.
659  */
660 static int
661 tunioctl(struct dev_ioctl_args *ap)
662 {
663 	cdev_t dev = ap->a_head.a_dev;
664 	caddr_t data = ap->a_data;
665 	struct tun_softc *sc = dev->si_drv1;
666 	struct ifnet *ifp = sc->tun_ifp;
667 	struct ifreq *ifr;
668 	struct tuninfo *tunp;
669 	int error = 0;
670 
671 	switch (ap->a_cmd) {
672 	case TUNSIFINFO:
673 		tunp = (struct tuninfo *)data;
674 		if (ifp->if_type != tunp->type)
675 			return (EPROTOTYPE);
676 		if (tunp->mtu < IF_MINMTU)
677 			return (EINVAL);
678 		ifp->if_mtu = tunp->mtu;
679 		ifp->if_baudrate = tunp->baudrate;
680 		break;
681 
682 	case TUNGIFINFO:
683 		tunp = (struct tuninfo *)data;
684 		tunp->mtu = ifp->if_mtu;
685 		tunp->type = ifp->if_type;
686 		tunp->baudrate = ifp->if_baudrate;
687 		break;
688 
689 	case TUNGIFNAME:
690 		ifr = (struct ifreq *)data;
691 		strlcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
692 		break;
693 
694 	case TUNSDEBUG:
695 		tundebug = *(int *)data;
696 		break;
697 
698 	case TUNGDEBUG:
699 		*(int *)data = tundebug;
700 		break;
701 
702 	case TUNSLMODE:
703 		if (*(int *)data) {
704 			sc->tun_flags |= TUN_LMODE;
705 			sc->tun_flags &= ~TUN_IFHEAD;
706 		} else {
707 			sc->tun_flags &= ~TUN_LMODE;
708 		}
709 		break;
710 
711 	case TUNSIFHEAD:
712 		if (*(int *)data) {
713 			sc->tun_flags |= TUN_IFHEAD;
714 			sc->tun_flags &= ~TUN_LMODE;
715 		} else {
716 			sc->tun_flags &= ~TUN_IFHEAD;
717 		}
718 		break;
719 
720 	case TUNGIFHEAD:
721 		*(int *)data = (sc->tun_flags & TUN_IFHEAD) ? 1 : 0;
722 		break;
723 
724 	case TUNSIFMODE:
725 		/* deny this if UP */
726 		if (ifp->if_flags & IFF_UP)
727 			return (EBUSY);
728 
729 		switch (*(int *)data & ~IFF_MULTICAST) {
730 		case IFF_POINTOPOINT:
731 		case IFF_BROADCAST:
732 			ifp->if_flags &= ~(IFF_BROADCAST | IFF_POINTOPOINT);
733 			ifp->if_flags |= *(int *)data;
734 			break;
735 		default:
736 			return (EINVAL);
737 		}
738 		break;
739 
740 	case TUNSIFPID:
741 		sc->tun_pid = curproc->p_pid;
742 		break;
743 
744 	case FIOASYNC:
745 		if (*(int *)data)
746 			sc->tun_flags |= TUN_ASYNC;
747 		else
748 			sc->tun_flags &= ~TUN_ASYNC;
749 		break;
750 
751 	case FIONREAD:
752 		*(int *)data = ifsq_poll_pktlen(
753 		    ifq_get_subq_default(&ifp->if_snd));
754 		break;
755 
756 	case FIOSETOWN:
757 		error = fsetown(*(int *)data, &sc->tun_sigio);
758 		break;
759 
760 	case FIOGETOWN:
761 		*(int *)data = fgetown(&sc->tun_sigio);
762 		break;
763 
764 	/* This is deprecated, FIOSETOWN should be used instead. */
765 	case TIOCSPGRP:
766 		error = fsetown(-(*(int *)data), &sc->tun_sigio);
767 		break;
768 
769 	/* This is deprecated, FIOGETOWN should be used instead. */
770 	case TIOCGPGRP:
771 		*(int *)data = -fgetown(&sc->tun_sigio);
772 		break;
773 
774 	default:
775 		error = ENOTTY;
776 		break;
777 	}
778 
779 	return (error);
780 }
781 
782 /*
783  * The ops read interface - reads a packet at a time, or at
784  * least as much of a packet as can be read.
785  */
786 static	int
787 tunread(struct dev_read_args *ap)
788 {
789 	cdev_t dev = ap->a_head.a_dev;
790 	struct uio *uio = ap->a_uio;
791 	struct tun_softc *sc = dev->si_drv1;
792 	struct ifnet *ifp = sc->tun_ifp;
793 	struct ifaltq_subque *ifsq = ifq_get_subq_default(&ifp->if_snd);
794 	struct mbuf *m0;
795 	int error=0, len;
796 
797 	TUNDEBUG(ifp, "read\n");
798 	if ((sc->tun_flags & TUN_READY) != TUN_READY) {
799 		TUNDEBUG(ifp, "not ready, flags = 0x%x\n", sc->tun_flags);
800 		return (EHOSTDOWN);
801 	}
802 
803 	sc->tun_flags &= ~TUN_RWAIT;
804 
805 	ifnet_serialize_all(ifp);
806 
807 	while ((m0 = ifsq_dequeue(ifsq)) == NULL) {
808 		if (ap->a_ioflag & IO_NDELAY) {
809 			ifnet_deserialize_all(ifp);
810 			return (EWOULDBLOCK);
811 		}
812 		sc->tun_flags |= TUN_RWAIT;
813 		ifnet_deserialize_all(ifp);
814 		if ((error = tsleep(sc, PCATCH, "tunread", 0)) != 0)
815 			return (error);
816 		ifnet_serialize_all(ifp);
817 	}
818 
819 	ifnet_deserialize_all(ifp);
820 
821 	while (m0 && uio->uio_resid > 0 && error == 0) {
822 		len = (int)szmin(uio->uio_resid, m0->m_len);
823 		if (len != 0)
824 			error = uiomove(mtod(m0, caddr_t), (size_t)len, uio);
825 		m0 = m_free(m0);
826 	}
827 
828 	if (m0) {
829 		TUNDEBUG(ifp, "dropping mbuf\n");
830 		m_freem(m0);
831 	}
832 	return (error);
833 }
834 
835 /*
836  * the ops write interface - an atomic write is a packet - or else!
837  */
838 static	int
839 tunwrite(struct dev_write_args *ap)
840 {
841 	cdev_t dev = ap->a_head.a_dev;
842 	struct uio *uio = ap->a_uio;
843 	struct tun_softc *sc = dev->si_drv1;
844 	struct ifnet *ifp = sc->tun_ifp;
845 	struct mbuf *top, **mp, *m;
846 	size_t tlen;
847 	uint32_t family, mru;
848 	int error = 0;
849 	int isr;
850 
851 	TUNDEBUG(ifp, "tunwrite\n");
852 
853 	if (uio->uio_resid == 0)
854 		return (0);
855 
856 	mru = TUNMRU;
857 	if (sc->tun_flags & TUN_IFHEAD)
858 		mru += sizeof(family);
859 	if (uio->uio_resid > mru) {
860 		TUNDEBUG(ifp, "len = %zd!\n", uio->uio_resid);
861 		return (EIO);
862 	}
863 
864 	/* get a header mbuf */
865 	MGETHDR(m, M_WAITOK, MT_DATA);
866 	if (m == NULL)
867 		return (ENOBUFS);
868 
869 	tlen = uio->uio_resid;
870 	top = NULL;
871 	mp = &top;
872 	while (error == 0 && uio->uio_resid > 0) {
873 		m->m_len = (int)szmin(MHLEN, uio->uio_resid);
874 		error = uiomove(mtod(m, caddr_t), (size_t)m->m_len, uio);
875 		*mp = m;
876 		mp = &m->m_next;
877 		if (uio->uio_resid > 0) {
878 			MGET(m, M_WAITOK, MT_DATA);
879 			if (m == NULL) {
880 				error = ENOBUFS;
881 				break;
882 			}
883 		}
884 	}
885 	if (error) {
886 		if (top)
887 			m_freem(top);
888 		IFNET_STAT_INC(ifp, ierrors, 1);
889 		return (error);
890 	}
891 
892 	top->m_pkthdr.len = (int)tlen;
893 	top->m_pkthdr.rcvif = ifp;
894 
895 	if (ifp->if_bpf) {
896 		bpf_gettoken();
897 
898 		if (ifp->if_bpf) {
899 			if (sc->tun_flags & TUN_IFHEAD) {
900 				/*
901 				 * Conveniently, we already have a 4-byte
902 				 * address family prepended to our packet !
903 				 * Inconveniently, it's in the wrong byte
904 				 * order !
905 				 */
906 				if ((top = m_pullup(top, sizeof(family)))
907 				    == NULL) {
908 					bpf_reltoken();
909 					return (ENOBUFS);
910 				}
911 				*mtod(top, u_int32_t *) =
912 				    ntohl(*mtod(top, u_int32_t *));
913 				bpf_mtap(ifp->if_bpf, top);
914 				*mtod(top, u_int32_t *) =
915 				    htonl(*mtod(top, u_int32_t *));
916 			} else {
917 				/*
918 				 * We need to prepend the address family as
919 				 * a four byte field.
920 				 */
921 				static const uint32_t af = AF_INET;
922 
923 				bpf_ptap(ifp->if_bpf, top, &af, sizeof(af));
924 			}
925 		}
926 
927 		bpf_reltoken();
928 	}
929 
930 	if (sc->tun_flags & TUN_IFHEAD) {
931 		if (top->m_len < sizeof(family) &&
932 		    (top = m_pullup(top, sizeof(family))) == NULL)
933 				return (ENOBUFS);
934 		family = ntohl(*mtod(top, u_int32_t *));
935 		m_adj(top, sizeof(family));
936 	} else {
937 		family = AF_INET;
938 	}
939 
940 	IFNET_STAT_INC(ifp, ibytes, top->m_pkthdr.len);
941 	IFNET_STAT_INC(ifp, ipackets, 1);
942 
943 	switch (family) {
944 #ifdef INET
945 	case AF_INET:
946 		isr = NETISR_IP;
947 		break;
948 #endif
949 #ifdef INET6
950 	case AF_INET6:
951 		isr = NETISR_IPV6;
952 		break;
953 #endif
954 	default:
955 		m_freem(m);
956 		return (EAFNOSUPPORT);
957 	}
958 
959 	netisr_queue(isr, top);
960 	return (0);
961 }
962 
963 
964 /*
965  * tunkqfilter - support for the kevent() system call.
966  */
967 static int
968 tunkqfilter(struct dev_kqfilter_args *ap)
969 {
970 	cdev_t dev = ap->a_head.a_dev;
971 	struct tun_softc *sc = dev->si_drv1;
972 	struct ifnet *ifp = sc->tun_ifp;
973 	struct knote *kn = ap->a_kn;
974 	struct klist *klist;
975 
976 	ap->a_result = 0;
977 	ifnet_serialize_all(ifp);
978 
979 	switch (kn->kn_filter) {
980 	case EVFILT_READ:
981 		kn->kn_fop = &tun_read_filtops;
982 		kn->kn_hook = (caddr_t)sc;
983 		break;
984 	case EVFILT_WRITE:
985 		kn->kn_fop = &tun_write_filtops;
986 		kn->kn_hook = (caddr_t)sc;
987 		break;
988 	default:
989 		ifnet_deserialize_all(ifp);
990 		ap->a_result = EOPNOTSUPP;
991 		return (0);
992 	}
993 
994 	klist = &sc->tun_rkq.ki_note;
995 	knote_insert(klist, kn);
996 	ifnet_deserialize_all(ifp);
997 
998 	return (0);
999 }
1000 
1001 static void
1002 tun_filter_detach(struct knote *kn)
1003 {
1004 	struct tun_softc *sc = (struct tun_softc *)kn->kn_hook;
1005 	struct klist *klist = &sc->tun_rkq.ki_note;
1006 
1007 	knote_remove(klist, kn);
1008 }
1009 
1010 static int
1011 tun_filter_write(struct knote *kn, long hint)
1012 {
1013 	/* Always ready for a write */
1014 	return (1);
1015 }
1016 
1017 static int
1018 tun_filter_read(struct knote *kn, long hint)
1019 {
1020 	struct tun_softc *sc = (struct tun_softc *)kn->kn_hook;
1021 	struct ifnet *ifp = sc->tun_ifp;
1022 	int ready = 0;
1023 
1024 	ifnet_serialize_all(ifp);
1025 	if (!ifsq_is_empty(ifq_get_subq_default(&ifp->if_snd)))
1026 		ready = 1;
1027 	ifnet_deserialize_all(ifp);
1028 
1029 	return (ready);
1030 }
1031