]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if_tun.c
Add function __mq_oshandle() to get file handle of a mqueue.
[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_atalk.h"
20 #include "opt_inet.h"
21 #include "opt_inet6.h"
22 #include "opt_ipx.h"
23 #include "opt_mac.h"
24
25 #include <sys/param.h>
26 #include <sys/priv.h>
27 #include <sys/proc.h>
28 #include <sys/systm.h>
29 #include <sys/mbuf.h>
30 #include <sys/module.h>
31 #include <sys/socket.h>
32 #include <sys/fcntl.h>
33 #include <sys/filio.h>
34 #include <sys/sockio.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
47 #include <net/if.h>
48 #include <net/if_types.h>
49 #include <net/netisr.h>
50 #include <net/route.h>
51 #ifdef INET
52 #include <netinet/in.h>
53 #endif
54 #include <net/bpf.h>
55 #include <net/if_tun.h>
56
57 #include <sys/queue.h>
58
59 #include <security/mac/mac_framework.h>
60
61 /*
62  * tun_list is protected by global tunmtx.  Other mutable fields are
63  * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
64  * static for the duration of a tunnel interface.
65  */
66 struct tun_softc {
67         TAILQ_ENTRY(tun_softc)  tun_list;
68         struct cdev *tun_dev;
69         u_short tun_flags;              /* misc flags */
70 #define TUN_OPEN        0x0001
71 #define TUN_INITED      0x0002
72 #define TUN_RCOLL       0x0004
73 #define TUN_IASET       0x0008
74 #define TUN_DSTADDR     0x0010
75 #define TUN_LMODE       0x0020
76 #define TUN_RWAIT       0x0040
77 #define TUN_ASYNC       0x0080
78 #define TUN_IFHEAD      0x0100
79
80 #define TUN_READY       (TUN_OPEN | TUN_INITED)
81
82         /*
83          * XXXRW: tun_pid is used to exclusively lock /dev/tun.  Is this
84          * actually needed?  Can we just return EBUSY if already open?
85          * Problem is that this involved inherent races when a tun device
86          * is handed off from one process to another, as opposed to just
87          * being slightly stale informationally.
88          */
89         pid_t   tun_pid;                /* owning pid */
90         struct  ifnet *tun_ifp;         /* the interface */
91         struct  sigio *tun_sigio;       /* information for async I/O */
92         struct  selinfo tun_rsel;       /* read select */
93         struct mtx      tun_mtx;        /* protect mutable softc fields */
94 };
95 #define TUN2IFP(sc)     ((sc)->tun_ifp)
96
97 #define TUNDEBUG        if (tundebug) if_printf
98 #define TUNNAME         "tun"
99
100 /*
101  * All mutable global variables in if_tun are locked using tunmtx, with
102  * the exception of tundebug, which is used unlocked, and tunclones,
103  * which is static after setup.
104  */
105 static struct mtx tunmtx;
106 static MALLOC_DEFINE(M_TUN, TUNNAME, "Tunnel Interface");
107 static int tundebug = 0;
108 static struct clonedevs *tunclones;
109 static TAILQ_HEAD(,tun_softc)   tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
110 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
111
112 static void     tunclone(void *arg, struct ucred *cred, char *name,
113                     int namelen, struct cdev **dev);
114 static void     tuncreate(struct cdev *dev);
115 static int      tunifioctl(struct ifnet *, u_long, caddr_t);
116 static int      tuninit(struct ifnet *);
117 static int      tunmodevent(module_t, int, void *);
118 static int      tunoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
119                     struct rtentry *rt);
120 static void     tunstart(struct ifnet *);
121
122 static d_open_t         tunopen;
123 static d_close_t        tunclose;
124 static d_read_t         tunread;
125 static d_write_t        tunwrite;
126 static d_ioctl_t        tunioctl;
127 static d_poll_t         tunpoll;
128 static d_kqfilter_t     tunkqfilter;
129
130 static int              tunkqread(struct knote *, long);
131 static int              tunkqwrite(struct knote *, long);
132 static void             tunkqdetach(struct knote *);
133
134 static struct filterops tun_read_filterops = {
135         .f_isfd =       1,
136         .f_attach =     NULL,
137         .f_detach =     tunkqdetach,
138         .f_event =      tunkqread,
139 };
140
141 static struct filterops tun_write_filterops = {
142         .f_isfd =       1,
143         .f_attach =     NULL,
144         .f_detach =     tunkqdetach,
145         .f_event =      tunkqwrite,
146 };
147
148 static struct cdevsw tun_cdevsw = {
149         .d_version =    D_VERSION,
150         .d_flags =      D_PSEUDO | D_NEEDGIANT,
151         .d_open =       tunopen,
152         .d_close =      tunclose,
153         .d_read =       tunread,
154         .d_write =      tunwrite,
155         .d_ioctl =      tunioctl,
156         .d_poll =       tunpoll,
157         .d_kqfilter =   tunkqfilter,
158         .d_name =       TUNNAME,
159 };
160
161 static void
162 tunclone(void *arg, struct ucred *cred, char *name, int namelen,
163     struct cdev **dev)
164 {
165         int u, i;
166
167         if (*dev != NULL)
168                 return;
169
170         if (strcmp(name, TUNNAME) == 0) {
171                 u = -1;
172         } else if (dev_stdclone(name, NULL, TUNNAME, &u) != 1)
173                 return; /* Don't recognise the name */
174         if (u != -1 && u > IF_MAXUNIT)
175                 return; /* Unit number too high */
176
177         /* find any existing device, or allocate new unit number */
178         i = clone_create(&tunclones, &tun_cdevsw, &u, dev, 0);
179         if (i) {
180                 /* No preexisting struct cdev *, create one */
181                 *dev = make_dev(&tun_cdevsw, unit2minor(u),
182                     UID_UUCP, GID_DIALER, 0600, "tun%d", u);
183                 if (*dev != NULL) {
184                         dev_ref(*dev);
185                         (*dev)->si_flags |= SI_CHEAPCLONE;
186                 }
187         }
188 }
189
190 static void
191 tun_destroy(struct tun_softc *tp)
192 {
193         struct cdev *dev;
194
195         /* Unlocked read. */
196         KASSERT((tp->tun_flags & TUN_OPEN) == 0,
197             ("tununits is out of sync - unit %d", TUN2IFP(tp)->if_dunit));
198
199         dev = tp->tun_dev;
200         bpfdetach(TUN2IFP(tp));
201         if_detach(TUN2IFP(tp));
202         if_free(TUN2IFP(tp));
203         destroy_dev(dev);
204         knlist_destroy(&tp->tun_rsel.si_note);
205         mtx_destroy(&tp->tun_mtx);
206         free(tp, M_TUN);
207 }
208
209 static int
210 tunmodevent(module_t mod, int type, void *data)
211 {
212         static eventhandler_tag tag;
213         struct tun_softc *tp;
214
215         switch (type) {
216         case MOD_LOAD:
217                 mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
218                 clone_setup(&tunclones);
219                 tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
220                 if (tag == NULL)
221                         return (ENOMEM);
222                 break;
223         case MOD_UNLOAD:
224                 EVENTHANDLER_DEREGISTER(dev_clone, tag);
225
226                 mtx_lock(&tunmtx);
227                 while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
228                         TAILQ_REMOVE(&tunhead, tp, tun_list);
229                         mtx_unlock(&tunmtx);
230                         tun_destroy(tp);
231                         mtx_lock(&tunmtx);
232                 }
233                 mtx_unlock(&tunmtx);
234                 clone_cleanup(&tunclones);
235                 mtx_destroy(&tunmtx);
236                 break;
237         default:
238                 return EOPNOTSUPP;
239         }
240         return 0;
241 }
242
243 static moduledata_t tun_mod = {
244         "if_tun",
245         tunmodevent,
246         0
247 };
248
249 DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
250
251 static void
252 tunstart(struct ifnet *ifp)
253 {
254         struct tun_softc *tp = ifp->if_softc;
255         struct mbuf *m;
256
257         TUNDEBUG(ifp,"%s starting\n", ifp->if_xname);
258         if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
259                 IFQ_LOCK(&ifp->if_snd);
260                 IFQ_POLL_NOLOCK(&ifp->if_snd, m);
261                 if (m == NULL) {
262                         IFQ_UNLOCK(&ifp->if_snd);
263                         return;
264                 }
265                 IFQ_UNLOCK(&ifp->if_snd);
266         }
267
268         mtx_lock(&tp->tun_mtx);
269         if (tp->tun_flags & TUN_RWAIT) {
270                 tp->tun_flags &= ~TUN_RWAIT;
271                 wakeup(tp);
272         }
273         if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
274                 mtx_unlock(&tp->tun_mtx);
275                 pgsigio(&tp->tun_sigio, SIGIO, 0);
276         } else
277                 mtx_unlock(&tp->tun_mtx);
278         selwakeuppri(&tp->tun_rsel, PZERO + 1);
279         KNOTE_UNLOCKED(&tp->tun_rsel.si_note, 0);
280 }
281
282 /* XXX: should return an error code so it can fail. */
283 static void
284 tuncreate(struct cdev *dev)
285 {
286         struct tun_softc *sc;
287         struct ifnet *ifp;
288
289         dev->si_flags &= ~SI_CHEAPCLONE;
290
291         MALLOC(sc, struct tun_softc *, sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
292         mtx_init(&sc->tun_mtx, "tun_mtx", NULL, MTX_DEF);
293         sc->tun_flags = TUN_INITED;
294         sc->tun_dev = dev;
295         mtx_lock(&tunmtx);
296         TAILQ_INSERT_TAIL(&tunhead, sc, tun_list);
297         mtx_unlock(&tunmtx);
298
299         ifp = sc->tun_ifp = if_alloc(IFT_PPP);
300         if (ifp == NULL)
301                 panic("%s%d: failed to if_alloc() interface.\n",
302                     TUNNAME, dev2unit(dev));
303         if_initname(ifp, TUNNAME, dev2unit(dev));
304         ifp->if_mtu = TUNMTU;
305         ifp->if_ioctl = tunifioctl;
306         ifp->if_output = tunoutput;
307         ifp->if_start = tunstart;
308         ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
309         ifp->if_softc = sc;
310         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
311         ifp->if_snd.ifq_drv_maxlen = 0;
312         IFQ_SET_READY(&ifp->if_snd);
313         knlist_init(&sc->tun_rsel.si_note, NULL, NULL, NULL, NULL);
314
315         if_attach(ifp);
316         bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
317         dev->si_drv1 = sc;
318         TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
319             ifp->if_xname, minor(dev));
320 }
321
322 static int
323 tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
324 {
325         struct ifnet    *ifp;
326         struct tun_softc *tp;
327
328         /*
329          * XXXRW: Non-atomic test and set of dev->si_drv1 requires
330          * synchronization.
331          */
332         tp = dev->si_drv1;
333         if (!tp) {
334                 tuncreate(dev);
335                 tp = dev->si_drv1;
336         }
337
338         /*
339          * XXXRW: This use of tun_pid is subject to error due to the
340          * fact that a reference to the tunnel can live beyond the
341          * death of the process that created it.  Can we replace this
342          * with a simple busy flag?
343          */
344         mtx_lock(&tp->tun_mtx);
345         if (tp->tun_pid != 0 && tp->tun_pid != td->td_proc->p_pid) {
346                 mtx_unlock(&tp->tun_mtx);
347                 return (EBUSY);
348         }
349         tp->tun_pid = td->td_proc->p_pid;
350
351         tp->tun_flags |= TUN_OPEN;
352         mtx_unlock(&tp->tun_mtx);
353         ifp = TUN2IFP(tp);
354         TUNDEBUG(ifp, "open\n");
355
356         return (0);
357 }
358
359 /*
360  * tunclose - close the device - mark i/f down & delete
361  * routing info
362  */
363 static  int
364 tunclose(struct cdev *dev, int foo, int bar, struct thread *td)
365 {
366         struct tun_softc *tp;
367         struct ifnet *ifp;
368         int s;
369
370         tp = dev->si_drv1;
371         ifp = TUN2IFP(tp);
372
373         mtx_lock(&tp->tun_mtx);
374         tp->tun_flags &= ~TUN_OPEN;
375         tp->tun_pid = 0;
376
377         /*
378          * junk all pending output
379          */
380         s = splimp();
381         IFQ_PURGE(&ifp->if_snd);
382         splx(s);
383         mtx_unlock(&tp->tun_mtx);
384
385         if (ifp->if_flags & IFF_UP) {
386                 s = splimp();
387                 if_down(ifp);
388                 splx(s);
389         }
390
391         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
392                 struct ifaddr *ifa;
393
394                 s = splimp();
395                 /* find internet addresses and delete routes */
396                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
397                         if (ifa->ifa_addr->sa_family == AF_INET)
398                                 /* Unlocked read. */
399                                 rtinit(ifa, (int)RTM_DELETE,
400                                     tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
401                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
402                 splx(s);
403         }
404
405         funsetown(&tp->tun_sigio);
406         selwakeuppri(&tp->tun_rsel, PZERO + 1);
407         KNOTE_UNLOCKED(&tp->tun_rsel.si_note, 0);
408         TUNDEBUG (ifp, "closed\n");
409         return (0);
410 }
411
412 static int
413 tuninit(struct ifnet *ifp)
414 {
415         struct tun_softc *tp = ifp->if_softc;
416         struct ifaddr *ifa;
417         int error = 0;
418
419         TUNDEBUG(ifp, "tuninit\n");
420
421         ifp->if_flags |= IFF_UP;
422         ifp->if_drv_flags |= IFF_DRV_RUNNING;
423         getmicrotime(&ifp->if_lastchange);
424
425 #ifdef INET
426         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
427                 if (ifa->ifa_addr->sa_family == AF_INET) {
428                         struct sockaddr_in *si;
429
430                         si = (struct sockaddr_in *)ifa->ifa_addr;
431                         mtx_lock(&tp->tun_mtx);
432                         if (si->sin_addr.s_addr)
433                                 tp->tun_flags |= TUN_IASET;
434
435                         si = (struct sockaddr_in *)ifa->ifa_dstaddr;
436                         if (si && si->sin_addr.s_addr)
437                                 tp->tun_flags |= TUN_DSTADDR;
438                         mtx_unlock(&tp->tun_mtx);
439                 }
440         }
441 #endif
442         return (error);
443 }
444
445 /*
446  * Process an ioctl request.
447  */
448 static int
449 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
450 {
451         struct ifreq *ifr = (struct ifreq *)data;
452         struct tun_softc *tp = ifp->if_softc;
453         struct ifstat *ifs;
454         int             error = 0, s;
455
456         s = splimp();
457         switch(cmd) {
458         case SIOCGIFSTATUS:
459                 ifs = (struct ifstat *)data;
460                 mtx_lock(&tp->tun_mtx);
461                 if (tp->tun_pid)
462                         sprintf(ifs->ascii + strlen(ifs->ascii),
463                             "\tOpened by PID %d\n", tp->tun_pid);
464                 mtx_unlock(&tp->tun_mtx);
465                 break;
466         case SIOCSIFADDR:
467                 error = tuninit(ifp);
468                 TUNDEBUG(ifp, "address set, error=%d\n", error);
469                 break;
470         case SIOCSIFDSTADDR:
471                 error = tuninit(ifp);
472                 TUNDEBUG(ifp, "destination address set, error=%d\n", error);
473                 break;
474         case SIOCSIFMTU:
475                 ifp->if_mtu = ifr->ifr_mtu;
476                 TUNDEBUG(ifp, "mtu set\n");
477                 break;
478         case SIOCSIFFLAGS:
479         case SIOCADDMULTI:
480         case SIOCDELMULTI:
481                 break;
482         default:
483                 error = EINVAL;
484         }
485         splx(s);
486         return (error);
487 }
488
489 /*
490  * tunoutput - queue packets from higher level ready to put out.
491  */
492 static int
493 tunoutput(
494         struct ifnet *ifp,
495         struct mbuf *m0,
496         struct sockaddr *dst,
497         struct rtentry *rt)
498 {
499         struct tun_softc *tp = ifp->if_softc;
500         u_short cached_tun_flags;
501         int error;
502         u_int32_t af;
503
504         TUNDEBUG (ifp, "tunoutput\n");
505
506 #ifdef MAC
507         error = mac_check_ifnet_transmit(ifp, m0);
508         if (error) {
509                 m_freem(m0);
510                 return (error);
511         }
512 #endif
513
514         /* Could be unlocked read? */
515         mtx_lock(&tp->tun_mtx);
516         cached_tun_flags = tp->tun_flags;
517         mtx_unlock(&tp->tun_mtx);
518         if ((cached_tun_flags & TUN_READY) != TUN_READY) {
519                 TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
520                 m_freem (m0);
521                 return (EHOSTDOWN);
522         }
523
524         if ((ifp->if_flags & IFF_UP) != IFF_UP) {
525                 m_freem (m0);
526                 return (EHOSTDOWN);
527         }
528
529         /* BPF writes need to be handled specially. */
530         if (dst->sa_family == AF_UNSPEC) {
531                 bcopy(dst->sa_data, &af, sizeof(af));
532                 dst->sa_family = af; 
533         }
534
535         if (bpf_peers_present(ifp->if_bpf)) {
536                 af = dst->sa_family;
537                 bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
538         }
539
540         /* prepend sockaddr? this may abort if the mbuf allocation fails */
541         if (cached_tun_flags & TUN_LMODE) {
542                 /* allocate space for sockaddr */
543                 M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
544
545                 /* if allocation failed drop packet */
546                 if (m0 == NULL) {
547                         ifp->if_iqdrops++;
548                         ifp->if_oerrors++;
549                         return (ENOBUFS);
550                 } else {
551                         bcopy(dst, m0->m_data, dst->sa_len);
552                 }
553         }
554
555         if (cached_tun_flags & TUN_IFHEAD) {
556                 /* Prepend the address family */
557                 M_PREPEND(m0, 4, M_DONTWAIT);
558
559                 /* if allocation failed drop packet */
560                 if (m0 == NULL) {
561                         ifp->if_iqdrops++;
562                         ifp->if_oerrors++;
563                         return (ENOBUFS);
564                 } else
565                         *(u_int32_t *)m0->m_data = htonl(dst->sa_family);
566         } else {
567 #ifdef INET
568                 if (dst->sa_family != AF_INET)
569 #endif
570                 {
571                         m_freem(m0);
572                         return (EAFNOSUPPORT);
573                 }
574         }
575
576         IFQ_HANDOFF(ifp, m0, error);
577         if (error) {
578                 ifp->if_collisions++;
579                 return (ENOBUFS);
580         }
581         ifp->if_opackets++;
582         return (0);
583 }
584
585 /*
586  * the cdevsw interface is now pretty minimal.
587  */
588 static  int
589 tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
590 {
591         int             s;
592         int             error;
593         struct tun_softc *tp = dev->si_drv1;
594         struct tuninfo *tunp;
595
596         switch (cmd) {
597         case TUNSIFINFO:
598                 tunp = (struct tuninfo *)data;
599                 if (tunp->mtu < IF_MINMTU)
600                         return (EINVAL);
601                 if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
602                         error = priv_check(td, PRIV_NET_SETIFMTU);
603                         if (error)
604                                 return (error);
605                 }
606                 TUN2IFP(tp)->if_mtu = tunp->mtu;
607                 TUN2IFP(tp)->if_type = tunp->type;
608                 TUN2IFP(tp)->if_baudrate = tunp->baudrate;
609                 break;
610         case TUNGIFINFO:
611                 tunp = (struct tuninfo *)data;
612                 tunp->mtu = TUN2IFP(tp)->if_mtu;
613                 tunp->type = TUN2IFP(tp)->if_type;
614                 tunp->baudrate = TUN2IFP(tp)->if_baudrate;
615                 break;
616         case TUNSDEBUG:
617                 tundebug = *(int *)data;
618                 break;
619         case TUNGDEBUG:
620                 *(int *)data = tundebug;
621                 break;
622         case TUNSLMODE:
623                 mtx_lock(&tp->tun_mtx);
624                 if (*(int *)data) {
625                         tp->tun_flags |= TUN_LMODE;
626                         tp->tun_flags &= ~TUN_IFHEAD;
627                 } else
628                         tp->tun_flags &= ~TUN_LMODE;
629                 mtx_unlock(&tp->tun_mtx);
630                 break;
631         case TUNSIFHEAD:
632                 mtx_lock(&tp->tun_mtx);
633                 if (*(int *)data) {
634                         tp->tun_flags |= TUN_IFHEAD;
635                         tp->tun_flags &= ~TUN_LMODE;
636                 } else
637                         tp->tun_flags &= ~TUN_IFHEAD;
638                 mtx_unlock(&tp->tun_mtx);
639                 break;
640         case TUNGIFHEAD:
641                 /* Could be unlocked read? */
642                 mtx_lock(&tp->tun_mtx);
643                 *(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
644                 mtx_unlock(&tp->tun_mtx);
645                 break;
646         case TUNSIFMODE:
647                 /* deny this if UP */
648                 if (TUN2IFP(tp)->if_flags & IFF_UP)
649                         return(EBUSY);
650
651                 switch (*(int *)data & ~IFF_MULTICAST) {
652                 case IFF_POINTOPOINT:
653                 case IFF_BROADCAST:
654                         TUN2IFP(tp)->if_flags &=
655                             ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
656                         TUN2IFP(tp)->if_flags |= *(int *)data;
657                         break;
658                 default:
659                         return(EINVAL);
660                 }
661                 break;
662         case TUNSIFPID:
663                 mtx_lock(&tp->tun_mtx);
664                 tp->tun_pid = curthread->td_proc->p_pid;
665                 mtx_unlock(&tp->tun_mtx);
666                 break;
667         case FIONBIO:
668                 break;
669         case FIOASYNC:
670                 mtx_lock(&tp->tun_mtx);
671                 if (*(int *)data)
672                         tp->tun_flags |= TUN_ASYNC;
673                 else
674                         tp->tun_flags &= ~TUN_ASYNC;
675                 mtx_unlock(&tp->tun_mtx);
676                 break;
677         case FIONREAD:
678                 s = splimp();
679                 if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
680                         struct mbuf *mb;
681                         IFQ_LOCK(&TUN2IFP(tp)->if_snd);
682                         IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
683                         for( *(int *)data = 0; mb != 0; mb = mb->m_next)
684                                 *(int *)data += mb->m_len;
685                         IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
686                 } else
687                         *(int *)data = 0;
688                 splx(s);
689                 break;
690         case FIOSETOWN:
691                 return (fsetown(*(int *)data, &tp->tun_sigio));
692
693         case FIOGETOWN:
694                 *(int *)data = fgetown(&tp->tun_sigio);
695                 return (0);
696
697         /* This is deprecated, FIOSETOWN should be used instead. */
698         case TIOCSPGRP:
699                 return (fsetown(-(*(int *)data), &tp->tun_sigio));
700
701         /* This is deprecated, FIOGETOWN should be used instead. */
702         case TIOCGPGRP:
703                 *(int *)data = -fgetown(&tp->tun_sigio);
704                 return (0);
705
706         default:
707                 return (ENOTTY);
708         }
709         return (0);
710 }
711
712 /*
713  * The cdevsw read interface - reads a packet at a time, or at
714  * least as much of a packet as can be read.
715  */
716 static  int
717 tunread(struct cdev *dev, struct uio *uio, int flag)
718 {
719         struct tun_softc *tp = dev->si_drv1;
720         struct ifnet    *ifp = TUN2IFP(tp);
721         struct mbuf     *m;
722         int             error=0, len, s;
723
724         TUNDEBUG (ifp, "read\n");
725         mtx_lock(&tp->tun_mtx);
726         if ((tp->tun_flags & TUN_READY) != TUN_READY) {
727                 mtx_unlock(&tp->tun_mtx);
728                 TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
729                 return (EHOSTDOWN);
730         }
731
732         tp->tun_flags &= ~TUN_RWAIT;
733         mtx_unlock(&tp->tun_mtx);
734
735         s = splimp();
736         do {
737                 IFQ_DEQUEUE(&ifp->if_snd, m);
738                 if (m == NULL) {
739                         if (flag & O_NONBLOCK) {
740                                 splx(s);
741                                 return (EWOULDBLOCK);
742                         }
743                         mtx_lock(&tp->tun_mtx);
744                         tp->tun_flags |= TUN_RWAIT;
745                         mtx_unlock(&tp->tun_mtx);
746                         if ((error = tsleep(tp, PCATCH | (PZERO + 1),
747                                         "tunread", 0)) != 0) {
748                                 splx(s);
749                                 return (error);
750                         }
751                 }
752         } while (m == NULL);
753         splx(s);
754
755         while (m && uio->uio_resid > 0 && error == 0) {
756                 len = min(uio->uio_resid, m->m_len);
757                 if (len != 0)
758                         error = uiomove(mtod(m, void *), len, uio);
759                 m = m_free(m);
760         }
761
762         if (m) {
763                 TUNDEBUG(ifp, "Dropping mbuf\n");
764                 m_freem(m);
765         }
766         return (error);
767 }
768
769 /*
770  * the cdevsw write interface - an atomic write is a packet - or else!
771  */
772 static  int
773 tunwrite(struct cdev *dev, struct uio *uio, int flag)
774 {
775         struct tun_softc *tp = dev->si_drv1;
776         struct ifnet    *ifp = TUN2IFP(tp);
777         struct mbuf     *m;
778         int             error = 0;
779         uint32_t        family;
780         int             isr;
781
782         TUNDEBUG(ifp, "tunwrite\n");
783
784         if ((ifp->if_flags & IFF_UP) != IFF_UP)
785                 /* ignore silently */
786                 return (0);
787
788         if (uio->uio_resid == 0)
789                 return (0);
790
791         if (uio->uio_resid < 0 || uio->uio_resid > TUNMRU) {
792                 TUNDEBUG(ifp, "len=%d!\n", uio->uio_resid);
793                 return (EIO);
794         }
795
796         if ((m = m_uiotombuf(uio, M_DONTWAIT, 0, 0, M_PKTHDR)) == NULL) {
797                 ifp->if_ierrors++;
798                 return (error);
799         }
800
801         m->m_pkthdr.rcvif = ifp;
802 #ifdef MAC
803         mac_create_mbuf_from_ifnet(ifp, m);
804 #endif
805
806         /* Could be unlocked read? */
807         mtx_lock(&tp->tun_mtx);
808         if (tp->tun_flags & TUN_IFHEAD) {
809                 mtx_unlock(&tp->tun_mtx);
810                 if (m->m_len < sizeof(family) &&
811                     (m = m_pullup(m, sizeof(family))) == NULL)
812                         return (ENOBUFS);
813                 family = ntohl(*mtod(m, u_int32_t *));
814                 m_adj(m, sizeof(family));
815         } else {
816                 mtx_unlock(&tp->tun_mtx);
817                 family = AF_INET;
818         }
819
820         BPF_MTAP2(ifp, &family, sizeof(family), m);
821
822         switch (family) {
823 #ifdef INET
824         case AF_INET:
825                 isr = NETISR_IP;
826                 break;
827 #endif
828 #ifdef INET6
829         case AF_INET6:
830                 isr = NETISR_IPV6;
831                 break;
832 #endif
833 #ifdef IPX
834         case AF_IPX:
835                 isr = NETISR_IPX;
836                 break;
837 #endif
838 #ifdef NETATALK
839         case AF_APPLETALK:
840                 isr = NETISR_ATALK2;
841                 break;
842 #endif
843         default:
844                 m_freem(m);
845                 return (EAFNOSUPPORT);
846         }
847         /* First chunk of an mbuf contains good junk */
848         if (harvest.point_to_point)
849                 random_harvest(m, 16, 3, 0, RANDOM_NET);
850         ifp->if_ibytes += m->m_pkthdr.len;
851         ifp->if_ipackets++;
852         netisr_dispatch(isr, m);
853         return (0);
854 }
855
856 /*
857  * tunpoll - the poll interface, this is only useful on reads
858  * really. The write detect always returns true, write never blocks
859  * anyway, it either accepts the packet or drops it.
860  */
861 static  int
862 tunpoll(struct cdev *dev, int events, struct thread *td)
863 {
864         int             s;
865         struct tun_softc *tp = dev->si_drv1;
866         struct ifnet    *ifp = TUN2IFP(tp);
867         int             revents = 0;
868         struct mbuf     *m;
869
870         s = splimp();
871         TUNDEBUG(ifp, "tunpoll\n");
872
873         if (events & (POLLIN | POLLRDNORM)) {
874                 IFQ_LOCK(&ifp->if_snd);
875                 IFQ_POLL_NOLOCK(&ifp->if_snd, m);
876                 if (m != NULL) {
877                         TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
878                         revents |= events & (POLLIN | POLLRDNORM);
879                 } else {
880                         TUNDEBUG(ifp, "tunpoll waiting\n");
881                         selrecord(td, &tp->tun_rsel);
882                 }
883                 IFQ_UNLOCK(&ifp->if_snd);
884         }
885         if (events & (POLLOUT | POLLWRNORM))
886                 revents |= events & (POLLOUT | POLLWRNORM);
887
888         splx(s);
889         return (revents);
890 }
891
892 /*
893  * tunkqfilter - support for the kevent() system call.
894  */
895 static int
896 tunkqfilter(struct cdev *dev, struct knote *kn)
897 {
898         int                     s;
899         struct tun_softc        *tp = dev->si_drv1;
900         struct ifnet    *ifp = TUN2IFP(tp);
901
902         s = splimp();
903         switch(kn->kn_filter) {
904         case EVFILT_READ:
905                 TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
906                     ifp->if_xname, minor(dev));
907                 kn->kn_fop = &tun_read_filterops;
908                 break;
909
910         case EVFILT_WRITE:
911                 TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
912                     ifp->if_xname, minor(dev));
913                 kn->kn_fop = &tun_write_filterops;
914                 break;
915         
916         default:
917                 TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
918                     ifp->if_xname, minor(dev));
919                 splx(s);
920                 return(EINVAL);
921         }
922         splx(s);
923
924         kn->kn_hook = (caddr_t) dev;
925         knlist_add(&tp->tun_rsel.si_note, kn, 0);
926
927         return (0);
928 }
929
930 /*
931  * Return true of there is data in the interface queue.
932  */
933 static int
934 tunkqread(struct knote *kn, long hint)
935 {
936         int                     ret, s;
937         struct cdev             *dev = (struct cdev *)(kn->kn_hook);
938         struct tun_softc        *tp = dev->si_drv1;
939         struct ifnet    *ifp = TUN2IFP(tp);
940
941         s = splimp();
942         if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
943                 TUNDEBUG(ifp,
944                     "%s have data in the queue.  Len = %d, minor = %#x\n",
945                     ifp->if_xname, ifp->if_snd.ifq_len, minor(dev));
946                 ret = 1;
947         } else {
948                 TUNDEBUG(ifp,
949                     "%s waiting for data, minor = %#x\n", ifp->if_xname,
950                     minor(dev));
951                 ret = 0;
952         }
953         splx(s);
954
955         return (ret);
956 }
957
958 /*
959  * Always can write, always return MTU in kn->data.
960  */
961 static int
962 tunkqwrite(struct knote *kn, long hint)
963 {
964         int                     s;
965         struct tun_softc        *tp = ((struct cdev *)kn->kn_hook)->si_drv1;
966         struct ifnet    *ifp = TUN2IFP(tp);
967
968         s = splimp();
969         kn->kn_data = ifp->if_mtu;
970         splx(s);
971
972         return (1);
973 }
974
975 static void
976 tunkqdetach(struct knote *kn)
977 {
978         struct tun_softc        *tp = ((struct cdev *)kn->kn_hook)->si_drv1;
979
980         knlist_remove(&tp->tun_rsel.si_note, kn, 0);
981 }