]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if_tun.c
MFC r346602, r346670-r346671, r347183: tun/tap race fixes
[FreeBSD/FreeBSD.git] / sys / net / if_tun.c
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$
17  */
18
19 #include "opt_inet.h"
20 #include "opt_inet6.h"
21
22 #include <sys/param.h>
23 #include <sys/lock.h>
24 #include <sys/priv.h>
25 #include <sys/proc.h>
26 #include <sys/systm.h>
27 #include <sys/jail.h>
28 #include <sys/mbuf.h>
29 #include <sys/module.h>
30 #include <sys/socket.h>
31 #include <sys/fcntl.h>
32 #include <sys/filio.h>
33 #include <sys/sockio.h>
34 #include <sys/sx.h>
35 #include <sys/ttycom.h>
36 #include <sys/poll.h>
37 #include <sys/selinfo.h>
38 #include <sys/signalvar.h>
39 #include <sys/filedesc.h>
40 #include <sys/kernel.h>
41 #include <sys/sysctl.h>
42 #include <sys/conf.h>
43 #include <sys/uio.h>
44 #include <sys/malloc.h>
45 #include <sys/random.h>
46 #include <sys/ctype.h>
47
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_clone.h>
51 #include <net/if_types.h>
52 #include <net/netisr.h>
53 #include <net/route.h>
54 #include <net/vnet.h>
55 #ifdef INET
56 #include <netinet/in.h>
57 #endif
58 #include <net/bpf.h>
59 #include <net/if_tun.h>
60
61 #include <sys/queue.h>
62 #include <sys/condvar.h>
63
64 #include <security/mac/mac_framework.h>
65
66 /*
67  * tun_list is protected by global tunmtx.  Other mutable fields are
68  * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
69  * static for the duration of a tunnel interface.
70  */
71 struct tun_softc {
72         TAILQ_ENTRY(tun_softc)  tun_list;
73         struct cdev *tun_dev;
74         u_short tun_flags;              /* misc flags */
75 #define TUN_OPEN        0x0001
76 #define TUN_INITED      0x0002
77 #define TUN_RCOLL       0x0004
78 #define TUN_IASET       0x0008
79 #define TUN_DSTADDR     0x0010
80 #define TUN_LMODE       0x0020
81 #define TUN_RWAIT       0x0040
82 #define TUN_ASYNC       0x0080
83 #define TUN_IFHEAD      0x0100
84 #define TUN_DYING       0x0200
85
86 #define TUN_READY       (TUN_OPEN | TUN_INITED)
87
88         pid_t   tun_pid;                /* owning pid */
89         struct  ifnet *tun_ifp;         /* the interface */
90         struct  sigio *tun_sigio;       /* information for async I/O */
91         struct  selinfo tun_rsel;       /* read select */
92         struct mtx      tun_mtx;        /* protect mutable softc fields */
93         struct cv       tun_cv;         /* protect against ref'd dev destroy */
94 };
95 #define TUN2IFP(sc)     ((sc)->tun_ifp)
96
97 #define TUNDEBUG        if (tundebug) if_printf
98
99 /*
100  * All mutable global variables in if_tun are locked using tunmtx, with
101  * the exception of tundebug, which is used unlocked, and tunclones,
102  * which is static after setup.
103  */
104 static struct mtx tunmtx;
105 static eventhandler_tag tag;
106 static const char tunname[] = "tun";
107 static MALLOC_DEFINE(M_TUN, tunname, "Tunnel Interface");
108 static int tundebug = 0;
109 static int tundclone = 1;
110 static struct clonedevs *tunclones;
111 static TAILQ_HEAD(,tun_softc)   tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
112 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
113
114 static struct sx tun_ioctl_sx;
115 SX_SYSINIT(tun_ioctl_sx, &tun_ioctl_sx, "tun_ioctl");
116
117 SYSCTL_DECL(_net_link);
118 static SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
119     "IP tunnel software network interface.");
120 SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tundclone, 0,
121     "Enable legacy devfs interface creation.");
122
123 static void     tunclone(void *arg, struct ucred *cred, char *name,
124                     int namelen, struct cdev **dev);
125 static void     tuncreate(const char *name, struct cdev *dev);
126 static int      tunifioctl(struct ifnet *, u_long, caddr_t);
127 static void     tuninit(struct ifnet *);
128 static int      tunmodevent(module_t, int, void *);
129 static int      tunoutput(struct ifnet *, struct mbuf *,
130                     const struct sockaddr *, struct route *ro);
131 static void     tunstart(struct ifnet *);
132
133 static int      tun_clone_match(struct if_clone *ifc, const char *name);
134 static int      tun_clone_create(struct if_clone *, char *, size_t, caddr_t);
135 static int      tun_clone_destroy(struct if_clone *, struct ifnet *);
136 static struct unrhdr    *tun_unrhdr;
137 VNET_DEFINE_STATIC(struct if_clone *, tun_cloner);
138 #define V_tun_cloner VNET(tun_cloner)
139
140 static d_open_t         tunopen;
141 static d_close_t        tunclose;
142 static d_read_t         tunread;
143 static d_write_t        tunwrite;
144 static d_ioctl_t        tunioctl;
145 static d_poll_t         tunpoll;
146 static d_kqfilter_t     tunkqfilter;
147
148 static int              tunkqread(struct knote *, long);
149 static int              tunkqwrite(struct knote *, long);
150 static void             tunkqdetach(struct knote *);
151
152 static struct filterops tun_read_filterops = {
153         .f_isfd =       1,
154         .f_attach =     NULL,
155         .f_detach =     tunkqdetach,
156         .f_event =      tunkqread,
157 };
158
159 static struct filterops tun_write_filterops = {
160         .f_isfd =       1,
161         .f_attach =     NULL,
162         .f_detach =     tunkqdetach,
163         .f_event =      tunkqwrite,
164 };
165
166 static struct cdevsw tun_cdevsw = {
167         .d_version =    D_VERSION,
168         .d_flags =      D_NEEDMINOR,
169         .d_open =       tunopen,
170         .d_close =      tunclose,
171         .d_read =       tunread,
172         .d_write =      tunwrite,
173         .d_ioctl =      tunioctl,
174         .d_poll =       tunpoll,
175         .d_kqfilter =   tunkqfilter,
176         .d_name =       tunname,
177 };
178
179 static int
180 tun_clone_match(struct if_clone *ifc, const char *name)
181 {
182         if (strncmp(tunname, name, 3) == 0 &&
183             (name[3] == '\0' || isdigit(name[3])))
184                 return (1);
185
186         return (0);
187 }
188
189 static int
190 tun_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
191 {
192         struct cdev *dev;
193         int err, unit, i;
194
195         err = ifc_name2unit(name, &unit);
196         if (err != 0)
197                 return (err);
198
199         if (unit != -1) {
200                 /* If this unit number is still available that/s okay. */
201                 if (alloc_unr_specific(tun_unrhdr, unit) == -1)
202                         return (EEXIST);
203         } else {
204                 unit = alloc_unr(tun_unrhdr);
205         }
206
207         snprintf(name, IFNAMSIZ, "%s%d", tunname, unit);
208
209         /* find any existing device, or allocate new unit number */
210         i = clone_create(&tunclones, &tun_cdevsw, &unit, &dev, 0);
211         if (i) {
212                 /* No preexisting struct cdev *, create one */
213                 dev = make_dev(&tun_cdevsw, unit,
214                     UID_UUCP, GID_DIALER, 0600, "%s%d", tunname, unit);
215         }
216         tuncreate(tunname, dev);
217
218         return (0);
219 }
220
221 static void
222 tunclone(void *arg, struct ucred *cred, char *name, int namelen,
223     struct cdev **dev)
224 {
225         char devname[SPECNAMELEN + 1];
226         int u, i, append_unit;
227
228         if (*dev != NULL)
229                 return;
230
231         /*
232          * If tun cloning is enabled, only the superuser can create an
233          * interface.
234          */
235         if (!tundclone || priv_check_cred(cred, PRIV_NET_IFCREATE, 0) != 0)
236                 return;
237
238         if (strcmp(name, tunname) == 0) {
239                 u = -1;
240         } else if (dev_stdclone(name, NULL, tunname, &u) != 1)
241                 return; /* Don't recognise the name */
242         if (u != -1 && u > IF_MAXUNIT)
243                 return; /* Unit number too high */
244
245         if (u == -1)
246                 append_unit = 1;
247         else
248                 append_unit = 0;
249
250         CURVNET_SET(CRED_TO_VNET(cred));
251         /* find any existing device, or allocate new unit number */
252         i = clone_create(&tunclones, &tun_cdevsw, &u, dev, 0);
253         if (i) {
254                 if (append_unit) {
255                         namelen = snprintf(devname, sizeof(devname), "%s%d",
256                             name, u);
257                         name = devname;
258                 }
259                 /* No preexisting struct cdev *, create one */
260                 *dev = make_dev_credf(MAKEDEV_REF, &tun_cdevsw, u, cred,
261                     UID_UUCP, GID_DIALER, 0600, "%s", name);
262         }
263
264         if_clone_create(name, namelen, NULL);
265         CURVNET_RESTORE();
266 }
267
268 static void
269 tun_destroy(struct tun_softc *tp)
270 {
271         struct cdev *dev;
272
273         mtx_lock(&tp->tun_mtx);
274         tp->tun_flags |= TUN_DYING;
275         if ((tp->tun_flags & TUN_OPEN) != 0)
276                 cv_wait_unlock(&tp->tun_cv, &tp->tun_mtx);
277         else
278                 mtx_unlock(&tp->tun_mtx);
279
280         CURVNET_SET(TUN2IFP(tp)->if_vnet);
281         sx_xlock(&tun_ioctl_sx);
282         TUN2IFP(tp)->if_softc = NULL;
283         sx_xunlock(&tun_ioctl_sx);
284
285         dev = tp->tun_dev;
286         bpfdetach(TUN2IFP(tp));
287         if_detach(TUN2IFP(tp));
288         free_unr(tun_unrhdr, TUN2IFP(tp)->if_dunit);
289         if_free(TUN2IFP(tp));
290         destroy_dev(dev);
291         seldrain(&tp->tun_rsel);
292         knlist_clear(&tp->tun_rsel.si_note, 0);
293         knlist_destroy(&tp->tun_rsel.si_note);
294         mtx_destroy(&tp->tun_mtx);
295         cv_destroy(&tp->tun_cv);
296         free(tp, M_TUN);
297         CURVNET_RESTORE();
298 }
299
300 static int
301 tun_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
302 {
303         struct tun_softc *tp = ifp->if_softc;
304
305         mtx_lock(&tunmtx);
306         TAILQ_REMOVE(&tunhead, tp, tun_list);
307         mtx_unlock(&tunmtx);
308         tun_destroy(tp);
309
310         return (0);
311 }
312
313 static void
314 vnet_tun_init(const void *unused __unused)
315 {
316         V_tun_cloner = if_clone_advanced(tunname, 0, tun_clone_match,
317                         tun_clone_create, tun_clone_destroy);
318 }
319 VNET_SYSINIT(vnet_tun_init, SI_SUB_PROTO_IF, SI_ORDER_ANY,
320                 vnet_tun_init, NULL);
321
322 static void
323 vnet_tun_uninit(const void *unused __unused)
324 {
325         if_clone_detach(V_tun_cloner);
326 }
327 VNET_SYSUNINIT(vnet_tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY,
328     vnet_tun_uninit, NULL);
329
330 static void
331 tun_uninit(const void *unused __unused)
332 {
333         struct tun_softc *tp;
334
335         EVENTHANDLER_DEREGISTER(dev_clone, tag);
336         drain_dev_clone_events();
337
338         mtx_lock(&tunmtx);
339         while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
340                 TAILQ_REMOVE(&tunhead, tp, tun_list);
341                 mtx_unlock(&tunmtx);
342                 tun_destroy(tp);
343                 mtx_lock(&tunmtx);
344         }
345         mtx_unlock(&tunmtx);
346         delete_unrhdr(tun_unrhdr);
347         clone_cleanup(&tunclones);
348         mtx_destroy(&tunmtx);
349 }
350 SYSUNINIT(tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY, tun_uninit, NULL);
351
352 static int
353 tunmodevent(module_t mod, int type, void *data)
354 {
355
356         switch (type) {
357         case MOD_LOAD:
358                 mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
359                 clone_setup(&tunclones);
360                 tun_unrhdr = new_unrhdr(0, IF_MAXUNIT, &tunmtx);
361                 tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
362                 if (tag == NULL)
363                         return (ENOMEM);
364                 break;
365         case MOD_UNLOAD:
366                 /* See tun_uninit, so it's done after the vnet_sysuninit() */
367                 break;
368         default:
369                 return EOPNOTSUPP;
370         }
371         return 0;
372 }
373
374 static moduledata_t tun_mod = {
375         "if_tun",
376         tunmodevent,
377         0
378 };
379
380 DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
381 MODULE_VERSION(if_tun, 1);
382
383 static void
384 tunstart(struct ifnet *ifp)
385 {
386         struct tun_softc *tp = ifp->if_softc;
387         struct mbuf *m;
388
389         TUNDEBUG(ifp,"%s starting\n", ifp->if_xname);
390         if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
391                 IFQ_LOCK(&ifp->if_snd);
392                 IFQ_POLL_NOLOCK(&ifp->if_snd, m);
393                 if (m == NULL) {
394                         IFQ_UNLOCK(&ifp->if_snd);
395                         return;
396                 }
397                 IFQ_UNLOCK(&ifp->if_snd);
398         }
399
400         mtx_lock(&tp->tun_mtx);
401         if (tp->tun_flags & TUN_RWAIT) {
402                 tp->tun_flags &= ~TUN_RWAIT;
403                 wakeup(tp);
404         }
405         selwakeuppri(&tp->tun_rsel, PZERO + 1);
406         KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
407         if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
408                 mtx_unlock(&tp->tun_mtx);
409                 pgsigio(&tp->tun_sigio, SIGIO, 0);
410         } else
411                 mtx_unlock(&tp->tun_mtx);
412 }
413
414 /* XXX: should return an error code so it can fail. */
415 static void
416 tuncreate(const char *name, struct cdev *dev)
417 {
418         struct tun_softc *sc;
419         struct ifnet *ifp;
420
421         sc = malloc(sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
422         mtx_init(&sc->tun_mtx, "tun_mtx", NULL, MTX_DEF);
423         cv_init(&sc->tun_cv, "tun_condvar");
424         sc->tun_flags = TUN_INITED;
425         sc->tun_dev = dev;
426         mtx_lock(&tunmtx);
427         TAILQ_INSERT_TAIL(&tunhead, sc, tun_list);
428         mtx_unlock(&tunmtx);
429
430         ifp = sc->tun_ifp = if_alloc(IFT_PPP);
431         if (ifp == NULL)
432                 panic("%s%d: failed to if_alloc() interface.\n",
433                     name, dev2unit(dev));
434         if_initname(ifp, name, dev2unit(dev));
435         ifp->if_mtu = TUNMTU;
436         ifp->if_ioctl = tunifioctl;
437         ifp->if_output = tunoutput;
438         ifp->if_start = tunstart;
439         ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
440         ifp->if_softc = sc;
441         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
442         ifp->if_snd.ifq_drv_maxlen = 0;
443         IFQ_SET_READY(&ifp->if_snd);
444         knlist_init_mtx(&sc->tun_rsel.si_note, &sc->tun_mtx);
445         ifp->if_capabilities |= IFCAP_LINKSTATE;
446         ifp->if_capenable |= IFCAP_LINKSTATE;
447
448         if_attach(ifp);
449         bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
450         dev->si_drv1 = sc;
451         TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
452             ifp->if_xname, dev2unit(dev));
453 }
454
455 static int
456 tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
457 {
458         struct ifnet    *ifp;
459         struct tun_softc *tp;
460
461         /*
462          * XXXRW: Non-atomic test and set of dev->si_drv1 requires
463          * synchronization.
464          */
465         tp = dev->si_drv1;
466         if (!tp) {
467                 tuncreate(tunname, dev);
468                 tp = dev->si_drv1;
469         }
470
471         mtx_lock(&tp->tun_mtx);
472         if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) {
473                 mtx_unlock(&tp->tun_mtx);
474                 return (EBUSY);
475         }
476
477         tp->tun_pid = td->td_proc->p_pid;
478         tp->tun_flags |= TUN_OPEN;
479         ifp = TUN2IFP(tp);
480         if_link_state_change(ifp, LINK_STATE_UP);
481         TUNDEBUG(ifp, "open\n");
482         mtx_unlock(&tp->tun_mtx);
483
484         return (0);
485 }
486
487 /*
488  * tunclose - close the device - mark i/f down & delete
489  * routing info
490  */
491 static  int
492 tunclose(struct cdev *dev, int foo, int bar, struct thread *td)
493 {
494         struct tun_softc *tp;
495         struct ifnet *ifp;
496
497         tp = dev->si_drv1;
498         ifp = TUN2IFP(tp);
499
500         mtx_lock(&tp->tun_mtx);
501         /*
502          * Simply close the device if this isn't the controlling process.  This
503          * may happen if, for instance, the tunnel has been handed off to
504          * another process.  The original controller should be able to close it
505          * without putting us into an inconsistent state.
506          */
507         if (td->td_proc->p_pid != tp->tun_pid) {
508                 mtx_unlock(&tp->tun_mtx);
509                 return (0);
510         }
511
512         /*
513          * junk all pending output
514          */
515         CURVNET_SET(ifp->if_vnet);
516         IFQ_PURGE(&ifp->if_snd);
517
518         if (ifp->if_flags & IFF_UP) {
519                 mtx_unlock(&tp->tun_mtx);
520                 if_down(ifp);
521                 mtx_lock(&tp->tun_mtx);
522         }
523
524         /* Delete all addresses and routes which reference this interface. */
525         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
526                 struct ifaddr *ifa;
527
528                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
529                 mtx_unlock(&tp->tun_mtx);
530                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
531                         /* deal w/IPv4 PtP destination; unlocked read */
532                         if (ifa->ifa_addr->sa_family == AF_INET) {
533                                 rtinit(ifa, (int)RTM_DELETE,
534                                     tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
535                         } else {
536                                 rtinit(ifa, (int)RTM_DELETE, 0);
537                         }
538                 }
539                 if_purgeaddrs(ifp);
540                 mtx_lock(&tp->tun_mtx);
541         }
542         if_link_state_change(ifp, LINK_STATE_DOWN);
543         CURVNET_RESTORE();
544
545         funsetown(&tp->tun_sigio);
546         selwakeuppri(&tp->tun_rsel, PZERO + 1);
547         KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
548         TUNDEBUG (ifp, "closed\n");
549         tp->tun_flags &= ~TUN_OPEN;
550         tp->tun_pid = 0;
551
552         cv_broadcast(&tp->tun_cv);
553         mtx_unlock(&tp->tun_mtx);
554         return (0);
555 }
556
557 static void
558 tuninit(struct ifnet *ifp)
559 {
560         struct tun_softc *tp = ifp->if_softc;
561 #ifdef INET
562         struct ifaddr *ifa;
563 #endif
564
565         TUNDEBUG(ifp, "tuninit\n");
566
567         mtx_lock(&tp->tun_mtx);
568         ifp->if_flags |= IFF_UP;
569         ifp->if_drv_flags |= IFF_DRV_RUNNING;
570         getmicrotime(&ifp->if_lastchange);
571
572 #ifdef INET
573         if_addr_rlock(ifp);
574         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
575                 if (ifa->ifa_addr->sa_family == AF_INET) {
576                         struct sockaddr_in *si;
577
578                         si = (struct sockaddr_in *)ifa->ifa_addr;
579                         if (si->sin_addr.s_addr)
580                                 tp->tun_flags |= TUN_IASET;
581
582                         si = (struct sockaddr_in *)ifa->ifa_dstaddr;
583                         if (si && si->sin_addr.s_addr)
584                                 tp->tun_flags |= TUN_DSTADDR;
585                 }
586         }
587         if_addr_runlock(ifp);
588 #endif
589         mtx_unlock(&tp->tun_mtx);
590 }
591
592 /*
593  * Process an ioctl request.
594  */
595 static int
596 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
597 {
598         struct ifreq *ifr = (struct ifreq *)data;
599         struct tun_softc *tp;
600         struct ifstat *ifs;
601         int             error = 0;
602
603         sx_xlock(&tun_ioctl_sx);
604         tp = ifp->if_softc;
605         if (tp == NULL) {
606                 error = ENXIO;
607                 goto bad;
608         }
609         switch(cmd) {
610         case SIOCGIFSTATUS:
611                 ifs = (struct ifstat *)data;
612                 mtx_lock(&tp->tun_mtx);
613                 if (tp->tun_pid)
614                         snprintf(ifs->ascii, sizeof(ifs->ascii),
615                             "\tOpened by PID %d\n", tp->tun_pid);
616                 else
617                         ifs->ascii[0] = '\0';
618                 mtx_unlock(&tp->tun_mtx);
619                 break;
620         case SIOCSIFADDR:
621                 tuninit(ifp);
622                 TUNDEBUG(ifp, "address set\n");
623                 break;
624         case SIOCSIFMTU:
625                 ifp->if_mtu = ifr->ifr_mtu;
626                 TUNDEBUG(ifp, "mtu set\n");
627                 break;
628         case SIOCSIFFLAGS:
629         case SIOCADDMULTI:
630         case SIOCDELMULTI:
631                 break;
632         default:
633                 error = EINVAL;
634         }
635 bad:
636         sx_xunlock(&tun_ioctl_sx);
637         return (error);
638 }
639
640 /*
641  * tunoutput - queue packets from higher level ready to put out.
642  */
643 static int
644 tunoutput(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst,
645     struct route *ro)
646 {
647         struct tun_softc *tp = ifp->if_softc;
648         u_short cached_tun_flags;
649         int error;
650         u_int32_t af;
651
652         TUNDEBUG (ifp, "tunoutput\n");
653
654 #ifdef MAC
655         error = mac_ifnet_check_transmit(ifp, m0);
656         if (error) {
657                 m_freem(m0);
658                 return (error);
659         }
660 #endif
661
662         /* Could be unlocked read? */
663         mtx_lock(&tp->tun_mtx);
664         cached_tun_flags = tp->tun_flags;
665         mtx_unlock(&tp->tun_mtx);
666         if ((cached_tun_flags & TUN_READY) != TUN_READY) {
667                 TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
668                 m_freem (m0);
669                 return (EHOSTDOWN);
670         }
671
672         if ((ifp->if_flags & IFF_UP) != IFF_UP) {
673                 m_freem (m0);
674                 return (EHOSTDOWN);
675         }
676
677         /* BPF writes need to be handled specially. */
678         if (dst->sa_family == AF_UNSPEC)
679                 bcopy(dst->sa_data, &af, sizeof(af));
680         else
681                 af = dst->sa_family;
682
683         if (bpf_peers_present(ifp->if_bpf))
684                 bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
685
686         /* prepend sockaddr? this may abort if the mbuf allocation fails */
687         if (cached_tun_flags & TUN_LMODE) {
688                 /* allocate space for sockaddr */
689                 M_PREPEND(m0, dst->sa_len, M_NOWAIT);
690
691                 /* if allocation failed drop packet */
692                 if (m0 == NULL) {
693                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
694                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
695                         return (ENOBUFS);
696                 } else {
697                         bcopy(dst, m0->m_data, dst->sa_len);
698                 }
699         }
700
701         if (cached_tun_flags & TUN_IFHEAD) {
702                 /* Prepend the address family */
703                 M_PREPEND(m0, 4, M_NOWAIT);
704
705                 /* if allocation failed drop packet */
706                 if (m0 == NULL) {
707                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
708                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
709                         return (ENOBUFS);
710                 } else
711                         *(u_int32_t *)m0->m_data = htonl(af);
712         } else {
713 #ifdef INET
714                 if (af != AF_INET)
715 #endif
716                 {
717                         m_freem(m0);
718                         return (EAFNOSUPPORT);
719                 }
720         }
721
722         error = (ifp->if_transmit)(ifp, m0);
723         if (error)
724                 return (ENOBUFS);
725         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
726         return (0);
727 }
728
729 /*
730  * the cdevsw interface is now pretty minimal.
731  */
732 static  int
733 tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
734     struct thread *td)
735 {
736         struct ifreq ifr;
737         struct tun_softc *tp = dev->si_drv1;
738         struct tuninfo *tunp;
739         int error;
740
741         switch (cmd) {
742         case TUNSIFINFO:
743                 tunp = (struct tuninfo *)data;
744                 if (TUN2IFP(tp)->if_type != tunp->type)
745                         return (EPROTOTYPE);
746                 mtx_lock(&tp->tun_mtx);
747                 if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
748                         strlcpy(ifr.ifr_name, if_name(TUN2IFP(tp)), IFNAMSIZ);
749                         ifr.ifr_mtu = tunp->mtu;
750                         CURVNET_SET(TUN2IFP(tp)->if_vnet);
751                         error = ifhwioctl(SIOCSIFMTU, TUN2IFP(tp),
752                             (caddr_t)&ifr, td);
753                         CURVNET_RESTORE();
754                         if (error) {
755                                 mtx_unlock(&tp->tun_mtx);
756                                 return (error);
757                         }
758                 }
759                 TUN2IFP(tp)->if_baudrate = tunp->baudrate;
760                 mtx_unlock(&tp->tun_mtx);
761                 break;
762         case TUNGIFINFO:
763                 tunp = (struct tuninfo *)data;
764                 mtx_lock(&tp->tun_mtx);
765                 tunp->mtu = TUN2IFP(tp)->if_mtu;
766                 tunp->type = TUN2IFP(tp)->if_type;
767                 tunp->baudrate = TUN2IFP(tp)->if_baudrate;
768                 mtx_unlock(&tp->tun_mtx);
769                 break;
770         case TUNSDEBUG:
771                 tundebug = *(int *)data;
772                 break;
773         case TUNGDEBUG:
774                 *(int *)data = tundebug;
775                 break;
776         case TUNSLMODE:
777                 mtx_lock(&tp->tun_mtx);
778                 if (*(int *)data) {
779                         tp->tun_flags |= TUN_LMODE;
780                         tp->tun_flags &= ~TUN_IFHEAD;
781                 } else
782                         tp->tun_flags &= ~TUN_LMODE;
783                 mtx_unlock(&tp->tun_mtx);
784                 break;
785         case TUNSIFHEAD:
786                 mtx_lock(&tp->tun_mtx);
787                 if (*(int *)data) {
788                         tp->tun_flags |= TUN_IFHEAD;
789                         tp->tun_flags &= ~TUN_LMODE;
790                 } else
791                         tp->tun_flags &= ~TUN_IFHEAD;
792                 mtx_unlock(&tp->tun_mtx);
793                 break;
794         case TUNGIFHEAD:
795                 mtx_lock(&tp->tun_mtx);
796                 *(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
797                 mtx_unlock(&tp->tun_mtx);
798                 break;
799         case TUNSIFMODE:
800                 /* deny this if UP */
801                 if (TUN2IFP(tp)->if_flags & IFF_UP)
802                         return(EBUSY);
803
804                 switch (*(int *)data & ~IFF_MULTICAST) {
805                 case IFF_POINTOPOINT:
806                 case IFF_BROADCAST:
807                         mtx_lock(&tp->tun_mtx);
808                         TUN2IFP(tp)->if_flags &=
809                             ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
810                         TUN2IFP(tp)->if_flags |= *(int *)data;
811                         mtx_unlock(&tp->tun_mtx);
812                         break;
813                 default:
814                         return(EINVAL);
815                 }
816                 break;
817         case TUNSIFPID:
818                 mtx_lock(&tp->tun_mtx);
819                 tp->tun_pid = curthread->td_proc->p_pid;
820                 mtx_unlock(&tp->tun_mtx);
821                 break;
822         case FIONBIO:
823                 break;
824         case FIOASYNC:
825                 mtx_lock(&tp->tun_mtx);
826                 if (*(int *)data)
827                         tp->tun_flags |= TUN_ASYNC;
828                 else
829                         tp->tun_flags &= ~TUN_ASYNC;
830                 mtx_unlock(&tp->tun_mtx);
831                 break;
832         case FIONREAD:
833                 if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
834                         struct mbuf *mb;
835                         IFQ_LOCK(&TUN2IFP(tp)->if_snd);
836                         IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
837                         for (*(int *)data = 0; mb != NULL; mb = mb->m_next)
838                                 *(int *)data += mb->m_len;
839                         IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
840                 } else
841                         *(int *)data = 0;
842                 break;
843         case FIOSETOWN:
844                 return (fsetown(*(int *)data, &tp->tun_sigio));
845
846         case FIOGETOWN:
847                 *(int *)data = fgetown(&tp->tun_sigio);
848                 return (0);
849
850         /* This is deprecated, FIOSETOWN should be used instead. */
851         case TIOCSPGRP:
852                 return (fsetown(-(*(int *)data), &tp->tun_sigio));
853
854         /* This is deprecated, FIOGETOWN should be used instead. */
855         case TIOCGPGRP:
856                 *(int *)data = -fgetown(&tp->tun_sigio);
857                 return (0);
858
859         default:
860                 return (ENOTTY);
861         }
862         return (0);
863 }
864
865 /*
866  * The cdevsw read interface - reads a packet at a time, or at
867  * least as much of a packet as can be read.
868  */
869 static  int
870 tunread(struct cdev *dev, struct uio *uio, int flag)
871 {
872         struct tun_softc *tp = dev->si_drv1;
873         struct ifnet    *ifp = TUN2IFP(tp);
874         struct mbuf     *m;
875         int             error=0, len;
876
877         TUNDEBUG (ifp, "read\n");
878         mtx_lock(&tp->tun_mtx);
879         if ((tp->tun_flags & TUN_READY) != TUN_READY) {
880                 mtx_unlock(&tp->tun_mtx);
881                 TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
882                 return (EHOSTDOWN);
883         }
884
885         tp->tun_flags &= ~TUN_RWAIT;
886
887         do {
888                 IFQ_DEQUEUE(&ifp->if_snd, m);
889                 if (m == NULL) {
890                         if (flag & O_NONBLOCK) {
891                                 mtx_unlock(&tp->tun_mtx);
892                                 return (EWOULDBLOCK);
893                         }
894                         tp->tun_flags |= TUN_RWAIT;
895                         error = mtx_sleep(tp, &tp->tun_mtx, PCATCH | (PZERO + 1),
896                             "tunread", 0);
897                         if (error != 0) {
898                                 mtx_unlock(&tp->tun_mtx);
899                                 return (error);
900                         }
901                 }
902         } while (m == NULL);
903         mtx_unlock(&tp->tun_mtx);
904
905         while (m && uio->uio_resid > 0 && error == 0) {
906                 len = min(uio->uio_resid, m->m_len);
907                 if (len != 0)
908                         error = uiomove(mtod(m, void *), len, uio);
909                 m = m_free(m);
910         }
911
912         if (m) {
913                 TUNDEBUG(ifp, "Dropping mbuf\n");
914                 m_freem(m);
915         }
916         return (error);
917 }
918
919 /*
920  * the cdevsw write interface - an atomic write is a packet - or else!
921  */
922 static  int
923 tunwrite(struct cdev *dev, struct uio *uio, int flag)
924 {
925         struct tun_softc *tp = dev->si_drv1;
926         struct ifnet    *ifp = TUN2IFP(tp);
927         struct mbuf     *m;
928         uint32_t        family, mru;
929         int             isr;
930
931         TUNDEBUG(ifp, "tunwrite\n");
932
933         if ((ifp->if_flags & IFF_UP) != IFF_UP)
934                 /* ignore silently */
935                 return (0);
936
937         if (uio->uio_resid == 0)
938                 return (0);
939
940         mru = TUNMRU;
941         if (tp->tun_flags & TUN_IFHEAD)
942                 mru += sizeof(family);
943         if (uio->uio_resid < 0 || uio->uio_resid > mru) {
944                 TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
945                 return (EIO);
946         }
947
948         if ((m = m_uiotombuf(uio, M_NOWAIT, 0, 0, M_PKTHDR)) == NULL) {
949                 if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
950                 return (ENOBUFS);
951         }
952
953         m->m_pkthdr.rcvif = ifp;
954 #ifdef MAC
955         mac_ifnet_create_mbuf(ifp, m);
956 #endif
957
958         /* Could be unlocked read? */
959         mtx_lock(&tp->tun_mtx);
960         if (tp->tun_flags & TUN_IFHEAD) {
961                 mtx_unlock(&tp->tun_mtx);
962                 if (m->m_len < sizeof(family) &&
963                     (m = m_pullup(m, sizeof(family))) == NULL)
964                         return (ENOBUFS);
965                 family = ntohl(*mtod(m, u_int32_t *));
966                 m_adj(m, sizeof(family));
967         } else {
968                 mtx_unlock(&tp->tun_mtx);
969                 family = AF_INET;
970         }
971
972         BPF_MTAP2(ifp, &family, sizeof(family), m);
973
974         switch (family) {
975 #ifdef INET
976         case AF_INET:
977                 isr = NETISR_IP;
978                 break;
979 #endif
980 #ifdef INET6
981         case AF_INET6:
982                 isr = NETISR_IPV6;
983                 break;
984 #endif
985         default:
986                 m_freem(m);
987                 return (EAFNOSUPPORT);
988         }
989         random_harvest_queue(m, sizeof(*m), RANDOM_NET_TUN);
990         if_inc_counter(ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
991         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
992         CURVNET_SET(ifp->if_vnet);
993         M_SETFIB(m, ifp->if_fib);
994         netisr_dispatch(isr, m);
995         CURVNET_RESTORE();
996         return (0);
997 }
998
999 /*
1000  * tunpoll - the poll interface, this is only useful on reads
1001  * really. The write detect always returns true, write never blocks
1002  * anyway, it either accepts the packet or drops it.
1003  */
1004 static  int
1005 tunpoll(struct cdev *dev, int events, struct thread *td)
1006 {
1007         struct tun_softc *tp = dev->si_drv1;
1008         struct ifnet    *ifp = TUN2IFP(tp);
1009         int             revents = 0;
1010         struct mbuf     *m;
1011
1012         TUNDEBUG(ifp, "tunpoll\n");
1013
1014         if (events & (POLLIN | POLLRDNORM)) {
1015                 IFQ_LOCK(&ifp->if_snd);
1016                 IFQ_POLL_NOLOCK(&ifp->if_snd, m);
1017                 if (m != NULL) {
1018                         TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
1019                         revents |= events & (POLLIN | POLLRDNORM);
1020                 } else {
1021                         TUNDEBUG(ifp, "tunpoll waiting\n");
1022                         selrecord(td, &tp->tun_rsel);
1023                 }
1024                 IFQ_UNLOCK(&ifp->if_snd);
1025         }
1026         if (events & (POLLOUT | POLLWRNORM))
1027                 revents |= events & (POLLOUT | POLLWRNORM);
1028
1029         return (revents);
1030 }
1031
1032 /*
1033  * tunkqfilter - support for the kevent() system call.
1034  */
1035 static int
1036 tunkqfilter(struct cdev *dev, struct knote *kn)
1037 {
1038         struct tun_softc        *tp = dev->si_drv1;
1039         struct ifnet    *ifp = TUN2IFP(tp);
1040
1041         switch(kn->kn_filter) {
1042         case EVFILT_READ:
1043                 TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
1044                     ifp->if_xname, dev2unit(dev));
1045                 kn->kn_fop = &tun_read_filterops;
1046                 break;
1047
1048         case EVFILT_WRITE:
1049                 TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
1050                     ifp->if_xname, dev2unit(dev));
1051                 kn->kn_fop = &tun_write_filterops;
1052                 break;
1053
1054         default:
1055                 TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1056                     ifp->if_xname, dev2unit(dev));
1057                 return(EINVAL);
1058         }
1059
1060         kn->kn_hook = tp;
1061         knlist_add(&tp->tun_rsel.si_note, kn, 0);
1062
1063         return (0);
1064 }
1065
1066 /*
1067  * Return true of there is data in the interface queue.
1068  */
1069 static int
1070 tunkqread(struct knote *kn, long hint)
1071 {
1072         int                     ret;
1073         struct tun_softc        *tp = kn->kn_hook;
1074         struct cdev             *dev = tp->tun_dev;
1075         struct ifnet    *ifp = TUN2IFP(tp);
1076
1077         if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1078                 TUNDEBUG(ifp,
1079                     "%s have data in the queue.  Len = %d, minor = %#x\n",
1080                     ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1081                 ret = 1;
1082         } else {
1083                 TUNDEBUG(ifp,
1084                     "%s waiting for data, minor = %#x\n", ifp->if_xname,
1085                     dev2unit(dev));
1086                 ret = 0;
1087         }
1088
1089         return (ret);
1090 }
1091
1092 /*
1093  * Always can write, always return MTU in kn->data.
1094  */
1095 static int
1096 tunkqwrite(struct knote *kn, long hint)
1097 {
1098         struct tun_softc        *tp = kn->kn_hook;
1099         struct ifnet    *ifp = TUN2IFP(tp);
1100
1101         kn->kn_data = ifp->if_mtu;
1102
1103         return (1);
1104 }
1105
1106 static void
1107 tunkqdetach(struct knote *kn)
1108 {
1109         struct tun_softc        *tp = kn->kn_hook;
1110
1111         knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1112 }