]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if_tuntap.c
if_tuntap: trigger the bpf hook on transmitting for the tap interface
[FreeBSD/FreeBSD.git] / sys / net / if_tuntap.c
1 /*      $NetBSD: if_tun.c,v 1.14 1994/06/29 06:36:25 cgd Exp $  */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause
4  *
5  * Copyright (C) 1999-2000 by Maksim Yevmenkin <m_evmenkin@yahoo.com>
6  * All rights reserved.
7  * Copyright (c) 2019 Kyle Evans <kevans@FreeBSD.org>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  * BASED ON:
32  * -------------------------------------------------------------------------
33  *
34  * Copyright (c) 1988, Julian Onions <jpo@cs.nott.ac.uk>
35  * Nottingham University 1987.
36  *
37  * This source may be freely distributed, however I would be interested
38  * in any changes that are made.
39  *
40  * This driver takes packets off the IP i/f and hands them up to a
41  * user process to have its wicked way with. This driver has it's
42  * roots in a similar driver written by Phil Cockcroft (formerly) at
43  * UCL. This driver is based much more on read/write/poll mode of
44  * operation though.
45  */
46
47 #include "opt_inet.h"
48 #include "opt_inet6.h"
49
50 #include <sys/param.h>
51 #include <sys/lock.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/systm.h>
55 #include <sys/jail.h>
56 #include <sys/mbuf.h>
57 #include <sys/module.h>
58 #include <sys/socket.h>
59 #include <sys/eventhandler.h>
60 #include <sys/fcntl.h>
61 #include <sys/filio.h>
62 #include <sys/sockio.h>
63 #include <sys/sx.h>
64 #include <sys/syslog.h>
65 #include <sys/ttycom.h>
66 #include <sys/poll.h>
67 #include <sys/selinfo.h>
68 #include <sys/signalvar.h>
69 #include <sys/filedesc.h>
70 #include <sys/kernel.h>
71 #include <sys/sysctl.h>
72 #include <sys/conf.h>
73 #include <sys/uio.h>
74 #include <sys/malloc.h>
75 #include <sys/random.h>
76 #include <sys/ctype.h>
77
78 #include <net/ethernet.h>
79 #include <net/if.h>
80 #include <net/if_var.h>
81 #include <net/if_clone.h>
82 #include <net/if_dl.h>
83 #include <net/if_media.h>
84 #include <net/if_types.h>
85 #include <net/if_vlan_var.h>
86 #include <net/netisr.h>
87 #include <net/route.h>
88 #include <net/vnet.h>
89 #include <netinet/in.h>
90 #ifdef INET
91 #include <netinet/ip.h>
92 #endif
93 #ifdef INET6
94 #include <netinet/ip6.h>
95 #include <netinet6/ip6_var.h>
96 #endif
97 #include <netinet/udp.h>
98 #include <netinet/tcp.h>
99 #include <net/bpf.h>
100 #include <net/if_tap.h>
101 #include <net/if_tun.h>
102
103 #include <dev/virtio/network/virtio_net.h>
104
105 #include <sys/queue.h>
106 #include <sys/condvar.h>
107 #include <security/mac/mac_framework.h>
108
109 struct tuntap_driver;
110
111 /*
112  * tun_list is protected by global tunmtx.  Other mutable fields are
113  * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
114  * static for the duration of a tunnel interface.
115  */
116 struct tuntap_softc {
117         TAILQ_ENTRY(tuntap_softc)        tun_list;
118         struct cdev                     *tun_alias;
119         struct cdev                     *tun_dev;
120         u_short                          tun_flags;     /* misc flags */
121 #define TUN_OPEN        0x0001
122 #define TUN_INITED      0x0002
123 #define TUN_UNUSED1     0x0008
124 #define TUN_UNUSED2     0x0010
125 #define TUN_LMODE       0x0020
126 #define TUN_RWAIT       0x0040
127 #define TUN_ASYNC       0x0080
128 #define TUN_IFHEAD      0x0100
129 #define TUN_DYING       0x0200
130 #define TUN_L2          0x0400
131 #define TUN_VMNET       0x0800
132
133 #define TUN_DRIVER_IDENT_MASK   (TUN_L2 | TUN_VMNET)
134 #define TUN_READY               (TUN_OPEN | TUN_INITED)
135
136         pid_t                    tun_pid;       /* owning pid */
137         struct ifnet            *tun_ifp;       /* the interface */
138         struct sigio            *tun_sigio;     /* async I/O info */
139         struct tuntap_driver    *tun_drv;       /* appropriate driver */
140         struct selinfo           tun_rsel;      /* read select */
141         struct mtx               tun_mtx;       /* softc field mutex */
142         struct cv                tun_cv;        /* for ref'd dev destroy */
143         struct ether_addr        tun_ether;     /* remote address */
144         int                      tun_busy;      /* busy count */
145         int                      tun_vhdrlen;   /* virtio-net header length */
146 };
147 #define TUN2IFP(sc)     ((sc)->tun_ifp)
148
149 #define TUNDEBUG        if (tundebug) if_printf
150
151 #define TUN_LOCK(tp)            mtx_lock(&(tp)->tun_mtx)
152 #define TUN_UNLOCK(tp)          mtx_unlock(&(tp)->tun_mtx)
153 #define TUN_LOCK_ASSERT(tp)     mtx_assert(&(tp)->tun_mtx, MA_OWNED);
154
155 #define TUN_VMIO_FLAG_MASK      0x0fff
156
157 /*
158  * Interface capabilities of a tap device that supports the virtio-net
159  * header.
160  */
161 #define TAP_VNET_HDR_CAPS       (IFCAP_HWCSUM | IFCAP_HWCSUM_IPV6       \
162                                 | IFCAP_VLAN_HWCSUM                     \
163                                 | IFCAP_TSO | IFCAP_LRO                 \
164                                 | IFCAP_VLAN_HWTSO)
165
166 #define TAP_ALL_OFFLOAD         (CSUM_TSO | CSUM_TCP | CSUM_UDP |\
167                                     CSUM_TCP_IPV6 | CSUM_UDP_IPV6)
168
169 /*
170  * All mutable global variables in if_tun are locked using tunmtx, with
171  * the exception of tundebug, which is used unlocked, and the drivers' *clones,
172  * which are static after setup.
173  */
174 static struct mtx tunmtx;
175 static eventhandler_tag arrival_tag;
176 static eventhandler_tag clone_tag;
177 static const char tunname[] = "tun";
178 static const char tapname[] = "tap";
179 static const char vmnetname[] = "vmnet";
180 static MALLOC_DEFINE(M_TUN, tunname, "Tunnel Interface");
181 static int tundebug = 0;
182 static int tundclone = 1;
183 static int tap_allow_uopen = 0; /* allow user devfs cloning */
184 static int tapuponopen = 0;     /* IFF_UP on open() */
185 static int tapdclone = 1;       /* enable devfs cloning */
186
187 static TAILQ_HEAD(,tuntap_softc)        tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
188 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
189
190 static struct sx tun_ioctl_sx;
191 SX_SYSINIT(tun_ioctl_sx, &tun_ioctl_sx, "tun_ioctl");
192
193 SYSCTL_DECL(_net_link);
194 /* tun */
195 static SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
196     "IP tunnel software network interface");
197 SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tundclone, 0,
198     "Enable legacy devfs interface creation");
199
200 /* tap */
201 static SYSCTL_NODE(_net_link, OID_AUTO, tap, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
202     "Ethernet tunnel software network interface");
203 SYSCTL_INT(_net_link_tap, OID_AUTO, user_open, CTLFLAG_RW, &tap_allow_uopen, 0,
204     "Enable legacy devfs interface creation for all users");
205 SYSCTL_INT(_net_link_tap, OID_AUTO, up_on_open, CTLFLAG_RW, &tapuponopen, 0,
206     "Bring interface up when /dev/tap is opened");
207 SYSCTL_INT(_net_link_tap, OID_AUTO, devfs_cloning, CTLFLAG_RWTUN, &tapdclone, 0,
208     "Enable legacy devfs interface creation");
209 SYSCTL_INT(_net_link_tap, OID_AUTO, debug, CTLFLAG_RW, &tundebug, 0, "");
210
211 static int      tun_create_device(struct tuntap_driver *drv, int unit,
212     struct ucred *cr, struct cdev **dev, const char *name);
213 static int      tun_busy_locked(struct tuntap_softc *tp);
214 static void     tun_unbusy_locked(struct tuntap_softc *tp);
215 static int      tun_busy(struct tuntap_softc *tp);
216 static void     tun_unbusy(struct tuntap_softc *tp);
217
218 static int      tuntap_name2info(const char *name, int *unit, int *flags);
219 static void     tunclone(void *arg, struct ucred *cred, char *name,
220                     int namelen, struct cdev **dev);
221 static void     tuncreate(struct cdev *dev);
222 static void     tundtor(void *data);
223 static void     tunrename(void *arg, struct ifnet *ifp);
224 static int      tunifioctl(struct ifnet *, u_long, caddr_t);
225 static void     tuninit(struct ifnet *);
226 static void     tunifinit(void *xtp);
227 static int      tuntapmodevent(module_t, int, void *);
228 static int      tunoutput(struct ifnet *, struct mbuf *,
229                     const struct sockaddr *, struct route *ro);
230 static void     tunstart(struct ifnet *);
231 static void     tunstart_l2(struct ifnet *);
232
233 static int      tun_clone_match(struct if_clone *ifc, const char *name);
234 static int      tap_clone_match(struct if_clone *ifc, const char *name);
235 static int      vmnet_clone_match(struct if_clone *ifc, const char *name);
236 static int      tun_clone_create(struct if_clone *, char *, size_t, caddr_t);
237 static int      tun_clone_destroy(struct if_clone *, struct ifnet *);
238 static void     tun_vnethdr_set(struct ifnet *ifp, int vhdrlen);
239
240 static d_open_t         tunopen;
241 static d_read_t         tunread;
242 static d_write_t        tunwrite;
243 static d_ioctl_t        tunioctl;
244 static d_poll_t         tunpoll;
245 static d_kqfilter_t     tunkqfilter;
246
247 static int              tunkqread(struct knote *, long);
248 static int              tunkqwrite(struct knote *, long);
249 static void             tunkqdetach(struct knote *);
250
251 static struct filterops tun_read_filterops = {
252         .f_isfd =       1,
253         .f_attach =     NULL,
254         .f_detach =     tunkqdetach,
255         .f_event =      tunkqread,
256 };
257
258 static struct filterops tun_write_filterops = {
259         .f_isfd =       1,
260         .f_attach =     NULL,
261         .f_detach =     tunkqdetach,
262         .f_event =      tunkqwrite,
263 };
264
265 static struct tuntap_driver {
266         struct cdevsw            cdevsw;
267         int                      ident_flags;
268         struct unrhdr           *unrhdr;
269         struct clonedevs        *clones;
270         ifc_match_t             *clone_match_fn;
271         ifc_create_t            *clone_create_fn;
272         ifc_destroy_t           *clone_destroy_fn;
273 } tuntap_drivers[] = {
274         {
275                 .ident_flags =  0,
276                 .cdevsw =       {
277                     .d_version =        D_VERSION,
278                     .d_flags =          D_NEEDMINOR,
279                     .d_open =           tunopen,
280                     .d_read =           tunread,
281                     .d_write =          tunwrite,
282                     .d_ioctl =          tunioctl,
283                     .d_poll =           tunpoll,
284                     .d_kqfilter =       tunkqfilter,
285                     .d_name =           tunname,
286                 },
287                 .clone_match_fn =       tun_clone_match,
288                 .clone_create_fn =      tun_clone_create,
289                 .clone_destroy_fn =     tun_clone_destroy,
290         },
291         {
292                 .ident_flags =  TUN_L2,
293                 .cdevsw =       {
294                     .d_version =        D_VERSION,
295                     .d_flags =          D_NEEDMINOR,
296                     .d_open =           tunopen,
297                     .d_read =           tunread,
298                     .d_write =          tunwrite,
299                     .d_ioctl =          tunioctl,
300                     .d_poll =           tunpoll,
301                     .d_kqfilter =       tunkqfilter,
302                     .d_name =           tapname,
303                 },
304                 .clone_match_fn =       tap_clone_match,
305                 .clone_create_fn =      tun_clone_create,
306                 .clone_destroy_fn =     tun_clone_destroy,
307         },
308         {
309                 .ident_flags =  TUN_L2 | TUN_VMNET,
310                 .cdevsw =       {
311                     .d_version =        D_VERSION,
312                     .d_flags =          D_NEEDMINOR,
313                     .d_open =           tunopen,
314                     .d_read =           tunread,
315                     .d_write =          tunwrite,
316                     .d_ioctl =          tunioctl,
317                     .d_poll =           tunpoll,
318                     .d_kqfilter =       tunkqfilter,
319                     .d_name =           vmnetname,
320                 },
321                 .clone_match_fn =       vmnet_clone_match,
322                 .clone_create_fn =      tun_clone_create,
323                 .clone_destroy_fn =     tun_clone_destroy,
324         },
325 };
326
327 struct tuntap_driver_cloner {
328         SLIST_ENTRY(tuntap_driver_cloner)        link;
329         struct tuntap_driver                    *drv;
330         struct if_clone                         *cloner;
331 };
332
333 VNET_DEFINE_STATIC(SLIST_HEAD(, tuntap_driver_cloner), tuntap_driver_cloners) =
334     SLIST_HEAD_INITIALIZER(tuntap_driver_cloners);
335
336 #define V_tuntap_driver_cloners VNET(tuntap_driver_cloners)
337
338 /*
339  * Mechanism for marking a tunnel device as busy so that we can safely do some
340  * orthogonal operations (such as operations on devices) without racing against
341  * tun_destroy.  tun_destroy will wait on the condvar if we're at all busy or
342  * open, to be woken up when the condition is alleviated.
343  */
344 static int
345 tun_busy_locked(struct tuntap_softc *tp)
346 {
347
348         TUN_LOCK_ASSERT(tp);
349         if ((tp->tun_flags & TUN_DYING) != 0) {
350                 /*
351                  * Perhaps unintuitive, but the device is busy going away.
352                  * Other interpretations of EBUSY from tun_busy make little
353                  * sense, since making a busy device even more busy doesn't
354                  * sound like a problem.
355                  */
356                 return (EBUSY);
357         }
358
359         ++tp->tun_busy;
360         return (0);
361 }
362
363 static void
364 tun_unbusy_locked(struct tuntap_softc *tp)
365 {
366
367         TUN_LOCK_ASSERT(tp);
368         KASSERT(tp->tun_busy != 0, ("tun_unbusy: called for non-busy tunnel"));
369
370         --tp->tun_busy;
371         /* Wake up anything that may be waiting on our busy tunnel. */
372         if (tp->tun_busy == 0)
373                 cv_broadcast(&tp->tun_cv);
374 }
375
376 static int
377 tun_busy(struct tuntap_softc *tp)
378 {
379         int ret;
380
381         TUN_LOCK(tp);
382         ret = tun_busy_locked(tp);
383         TUN_UNLOCK(tp);
384         return (ret);
385 }
386
387 static void
388 tun_unbusy(struct tuntap_softc *tp)
389 {
390
391         TUN_LOCK(tp);
392         tun_unbusy_locked(tp);
393         TUN_UNLOCK(tp);
394 }
395
396 /*
397  * Sets unit and/or flags given the device name.  Must be called with correct
398  * vnet context.
399  */
400 static int
401 tuntap_name2info(const char *name, int *outunit, int *outflags)
402 {
403         struct tuntap_driver *drv;
404         struct tuntap_driver_cloner *drvc;
405         char *dname;
406         int flags, unit;
407         bool found;
408
409         if (name == NULL)
410                 return (EINVAL);
411
412         /*
413          * Needed for dev_stdclone, but dev_stdclone will not modify, it just
414          * wants to be able to pass back a char * through the second param. We
415          * will always set that as NULL here, so we'll fake it.
416          */
417         dname = __DECONST(char *, name);
418         found = false;
419
420         KASSERT(!SLIST_EMPTY(&V_tuntap_driver_cloners),
421             ("tuntap_driver_cloners failed to initialize"));
422         SLIST_FOREACH(drvc, &V_tuntap_driver_cloners, link) {
423                 KASSERT(drvc->drv != NULL,
424                     ("tuntap_driver_cloners entry not properly initialized"));
425                 drv = drvc->drv;
426
427                 if (strcmp(name, drv->cdevsw.d_name) == 0) {
428                         found = true;
429                         unit = -1;
430                         flags = drv->ident_flags;
431                         break;
432                 }
433
434                 if (dev_stdclone(dname, NULL, drv->cdevsw.d_name, &unit) == 1) {
435                         found = true;
436                         flags = drv->ident_flags;
437                         break;
438                 }
439         }
440
441         if (!found)
442                 return (ENXIO);
443
444         if (outunit != NULL)
445                 *outunit = unit;
446         if (outflags != NULL)
447                 *outflags = flags;
448         return (0);
449 }
450
451 /*
452  * Get driver information from a set of flags specified.  Masks the identifying
453  * part of the flags and compares it against all of the available
454  * tuntap_drivers. Must be called with correct vnet context.
455  */
456 static struct tuntap_driver *
457 tuntap_driver_from_flags(int tun_flags)
458 {
459         struct tuntap_driver *drv;
460         struct tuntap_driver_cloner *drvc;
461
462         KASSERT(!SLIST_EMPTY(&V_tuntap_driver_cloners),
463             ("tuntap_driver_cloners failed to initialize"));
464         SLIST_FOREACH(drvc, &V_tuntap_driver_cloners, link) {
465                 KASSERT(drvc->drv != NULL,
466                     ("tuntap_driver_cloners entry not properly initialized"));
467                 drv = drvc->drv;
468                 if ((tun_flags & TUN_DRIVER_IDENT_MASK) == drv->ident_flags)
469                         return (drv);
470         }
471
472         return (NULL);
473 }
474
475 static int
476 tun_clone_match(struct if_clone *ifc, const char *name)
477 {
478         int tunflags;
479
480         if (tuntap_name2info(name, NULL, &tunflags) == 0) {
481                 if ((tunflags & TUN_L2) == 0)
482                         return (1);
483         }
484
485         return (0);
486 }
487
488 static int
489 tap_clone_match(struct if_clone *ifc, const char *name)
490 {
491         int tunflags;
492
493         if (tuntap_name2info(name, NULL, &tunflags) == 0) {
494                 if ((tunflags & (TUN_L2 | TUN_VMNET)) == TUN_L2)
495                         return (1);
496         }
497
498         return (0);
499 }
500
501 static int
502 vmnet_clone_match(struct if_clone *ifc, const char *name)
503 {
504         int tunflags;
505
506         if (tuntap_name2info(name, NULL, &tunflags) == 0) {
507                 if ((tunflags & TUN_VMNET) != 0)
508                         return (1);
509         }
510
511         return (0);
512 }
513
514 static int
515 tun_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
516 {
517         struct tuntap_driver *drv;
518         struct cdev *dev;
519         int err, i, tunflags, unit;
520
521         tunflags = 0;
522         /* The name here tells us exactly what we're creating */
523         err = tuntap_name2info(name, &unit, &tunflags);
524         if (err != 0)
525                 return (err);
526
527         drv = tuntap_driver_from_flags(tunflags);
528         if (drv == NULL)
529                 return (ENXIO);
530
531         if (unit != -1) {
532                 /* If this unit number is still available that's okay. */
533                 if (alloc_unr_specific(drv->unrhdr, unit) == -1)
534                         return (EEXIST);
535         } else {
536                 unit = alloc_unr(drv->unrhdr);
537         }
538
539         snprintf(name, IFNAMSIZ, "%s%d", drv->cdevsw.d_name, unit);
540
541         /* find any existing device, or allocate new unit number */
542         dev = NULL;
543         i = clone_create(&drv->clones, &drv->cdevsw, &unit, &dev, 0);
544         if (i == 0)
545                 dev_ref(dev);
546         /* No preexisting struct cdev *, create one */
547         if (i != 0)
548                 i = tun_create_device(drv, unit, NULL, &dev, name);
549         if (i == 0)
550                 tuncreate(dev);
551
552         return (i);
553 }
554
555 static void
556 tunclone(void *arg, struct ucred *cred, char *name, int namelen,
557     struct cdev **dev)
558 {
559         char devname[SPECNAMELEN + 1];
560         struct tuntap_driver *drv;
561         int append_unit, i, u, tunflags;
562         bool mayclone;
563
564         if (*dev != NULL)
565                 return;
566
567         tunflags = 0;
568         CURVNET_SET(CRED_TO_VNET(cred));
569         if (tuntap_name2info(name, &u, &tunflags) != 0)
570                 goto out;       /* Not recognized */
571
572         if (u != -1 && u > IF_MAXUNIT)
573                 goto out;       /* Unit number too high */
574
575         mayclone = priv_check_cred(cred, PRIV_NET_IFCREATE) == 0;
576         if ((tunflags & TUN_L2) != 0) {
577                 /* tap/vmnet allow user open with a sysctl */
578                 mayclone = (mayclone || tap_allow_uopen) && tapdclone;
579         } else {
580                 mayclone = mayclone && tundclone;
581         }
582
583         /*
584          * If tun cloning is enabled, only the superuser can create an
585          * interface.
586          */
587         if (!mayclone)
588                 goto out;
589
590         if (u == -1)
591                 append_unit = 1;
592         else
593                 append_unit = 0;
594
595         drv = tuntap_driver_from_flags(tunflags);
596         if (drv == NULL)
597                 goto out;
598
599         /* find any existing device, or allocate new unit number */
600         i = clone_create(&drv->clones, &drv->cdevsw, &u, dev, 0);
601         if (i == 0)
602                 dev_ref(*dev);
603         if (i) {
604                 if (append_unit) {
605                         namelen = snprintf(devname, sizeof(devname), "%s%d",
606                             name, u);
607                         name = devname;
608                 }
609
610                 i = tun_create_device(drv, u, cred, dev, name);
611         }
612         if (i == 0)
613                 if_clone_create(name, namelen, NULL);
614 out:
615         CURVNET_RESTORE();
616 }
617
618 static void
619 tun_destroy(struct tuntap_softc *tp)
620 {
621
622         TUN_LOCK(tp);
623         tp->tun_flags |= TUN_DYING;
624         if (tp->tun_busy != 0)
625                 cv_wait_unlock(&tp->tun_cv, &tp->tun_mtx);
626         else
627                 TUN_UNLOCK(tp);
628
629         CURVNET_SET(TUN2IFP(tp)->if_vnet);
630
631         /* destroy_dev will take care of any alias. */
632         destroy_dev(tp->tun_dev);
633         seldrain(&tp->tun_rsel);
634         knlist_clear(&tp->tun_rsel.si_note, 0);
635         knlist_destroy(&tp->tun_rsel.si_note);
636         if ((tp->tun_flags & TUN_L2) != 0) {
637                 ether_ifdetach(TUN2IFP(tp));
638         } else {
639                 bpfdetach(TUN2IFP(tp));
640                 if_detach(TUN2IFP(tp));
641         }
642         sx_xlock(&tun_ioctl_sx);
643         TUN2IFP(tp)->if_softc = NULL;
644         sx_xunlock(&tun_ioctl_sx);
645         free_unr(tp->tun_drv->unrhdr, TUN2IFP(tp)->if_dunit);
646         if_free(TUN2IFP(tp));
647         mtx_destroy(&tp->tun_mtx);
648         cv_destroy(&tp->tun_cv);
649         free(tp, M_TUN);
650         CURVNET_RESTORE();
651 }
652
653 static int
654 tun_clone_destroy(struct if_clone *ifc __unused, struct ifnet *ifp)
655 {
656         struct tuntap_softc *tp = ifp->if_softc;
657
658         mtx_lock(&tunmtx);
659         TAILQ_REMOVE(&tunhead, tp, tun_list);
660         mtx_unlock(&tunmtx);
661         tun_destroy(tp);
662
663         return (0);
664 }
665
666 static void
667 vnet_tun_init(const void *unused __unused)
668 {
669         struct tuntap_driver *drv;
670         struct tuntap_driver_cloner *drvc;
671         int i;
672
673         for (i = 0; i < nitems(tuntap_drivers); ++i) {
674                 drv = &tuntap_drivers[i];
675                 drvc = malloc(sizeof(*drvc), M_TUN, M_WAITOK | M_ZERO);
676
677                 drvc->drv = drv;
678                 drvc->cloner = if_clone_advanced(drv->cdevsw.d_name, 0,
679                     drv->clone_match_fn, drv->clone_create_fn,
680                     drv->clone_destroy_fn);
681                 SLIST_INSERT_HEAD(&V_tuntap_driver_cloners, drvc, link);
682         };
683 }
684 VNET_SYSINIT(vnet_tun_init, SI_SUB_PROTO_IF, SI_ORDER_ANY,
685                 vnet_tun_init, NULL);
686
687 static void
688 vnet_tun_uninit(const void *unused __unused)
689 {
690         struct tuntap_driver_cloner *drvc;
691
692         while (!SLIST_EMPTY(&V_tuntap_driver_cloners)) {
693                 drvc = SLIST_FIRST(&V_tuntap_driver_cloners);
694                 SLIST_REMOVE_HEAD(&V_tuntap_driver_cloners, link);
695
696                 if_clone_detach(drvc->cloner);
697                 free(drvc, M_TUN);
698         }
699 }
700 VNET_SYSUNINIT(vnet_tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY,
701     vnet_tun_uninit, NULL);
702
703 static void
704 tun_uninit(const void *unused __unused)
705 {
706         struct tuntap_driver *drv;
707         struct tuntap_softc *tp;
708         int i;
709
710         EVENTHANDLER_DEREGISTER(ifnet_arrival_event, arrival_tag);
711         EVENTHANDLER_DEREGISTER(dev_clone, clone_tag);
712         drain_dev_clone_events();
713
714         mtx_lock(&tunmtx);
715         while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
716                 TAILQ_REMOVE(&tunhead, tp, tun_list);
717                 mtx_unlock(&tunmtx);
718                 tun_destroy(tp);
719                 mtx_lock(&tunmtx);
720         }
721         mtx_unlock(&tunmtx);
722         for (i = 0; i < nitems(tuntap_drivers); ++i) {
723                 drv = &tuntap_drivers[i];
724                 delete_unrhdr(drv->unrhdr);
725                 clone_cleanup(&drv->clones);
726         }
727         mtx_destroy(&tunmtx);
728 }
729 SYSUNINIT(tun_uninit, SI_SUB_PROTO_IF, SI_ORDER_ANY, tun_uninit, NULL);
730
731 static struct tuntap_driver *
732 tuntap_driver_from_ifnet(const struct ifnet *ifp)
733 {
734         struct tuntap_driver *drv;
735         int i;
736
737         if (ifp == NULL)
738                 return (NULL);
739
740         for (i = 0; i < nitems(tuntap_drivers); ++i) {
741                 drv = &tuntap_drivers[i];
742                 if (strcmp(ifp->if_dname, drv->cdevsw.d_name) == 0)
743                         return (drv);
744         }
745
746         return (NULL);
747 }
748
749 static int
750 tuntapmodevent(module_t mod, int type, void *data)
751 {
752         struct tuntap_driver *drv;
753         int i;
754
755         switch (type) {
756         case MOD_LOAD:
757                 mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
758                 for (i = 0; i < nitems(tuntap_drivers); ++i) {
759                         drv = &tuntap_drivers[i];
760                         clone_setup(&drv->clones);
761                         drv->unrhdr = new_unrhdr(0, IF_MAXUNIT, &tunmtx);
762                 }
763                 arrival_tag = EVENTHANDLER_REGISTER(ifnet_arrival_event,
764                    tunrename, 0, 1000);
765                 if (arrival_tag == NULL)
766                         return (ENOMEM);
767                 clone_tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
768                 if (clone_tag == NULL)
769                         return (ENOMEM);
770                 break;
771         case MOD_UNLOAD:
772                 /* See tun_uninit, so it's done after the vnet_sysuninit() */
773                 break;
774         default:
775                 return EOPNOTSUPP;
776         }
777         return 0;
778 }
779
780 static moduledata_t tuntap_mod = {
781         "if_tuntap",
782         tuntapmodevent,
783         0
784 };
785
786 /* We'll only ever have these two, so no need for a macro. */
787 static moduledata_t tun_mod = { "if_tun", NULL, 0 };
788 static moduledata_t tap_mod = { "if_tap", NULL, 0 };
789
790 DECLARE_MODULE(if_tuntap, tuntap_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
791 MODULE_VERSION(if_tuntap, 1);
792 DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
793 MODULE_VERSION(if_tun, 1);
794 DECLARE_MODULE(if_tap, tap_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
795 MODULE_VERSION(if_tap, 1);
796
797 static int
798 tun_create_device(struct tuntap_driver *drv, int unit, struct ucred *cr,
799     struct cdev **dev, const char *name)
800 {
801         struct make_dev_args args;
802         struct tuntap_softc *tp;
803         int error;
804
805         tp = malloc(sizeof(*tp), M_TUN, M_WAITOK | M_ZERO);
806         mtx_init(&tp->tun_mtx, "tun_mtx", NULL, MTX_DEF);
807         cv_init(&tp->tun_cv, "tun_condvar");
808         tp->tun_flags = drv->ident_flags;
809         tp->tun_drv = drv;
810
811         make_dev_args_init(&args);
812         if (cr != NULL)
813                 args.mda_flags = MAKEDEV_REF | MAKEDEV_CHECKNAME;
814         args.mda_devsw = &drv->cdevsw;
815         args.mda_cr = cr;
816         args.mda_uid = UID_UUCP;
817         args.mda_gid = GID_DIALER;
818         args.mda_mode = 0600;
819         args.mda_unit = unit;
820         args.mda_si_drv1 = tp;
821         error = make_dev_s(&args, dev, "%s", name);
822         if (error != 0) {
823                 free(tp, M_TUN);
824                 return (error);
825         }
826
827         KASSERT((*dev)->si_drv1 != NULL,
828             ("Failed to set si_drv1 at %s creation", name));
829         tp->tun_dev = *dev;
830         knlist_init_mtx(&tp->tun_rsel.si_note, &tp->tun_mtx);
831         mtx_lock(&tunmtx);
832         TAILQ_INSERT_TAIL(&tunhead, tp, tun_list);
833         mtx_unlock(&tunmtx);
834         return (0);
835 }
836
837 static void
838 tunstart(struct ifnet *ifp)
839 {
840         struct tuntap_softc *tp = ifp->if_softc;
841         struct mbuf *m;
842
843         TUNDEBUG(ifp, "starting\n");
844         if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
845                 IFQ_LOCK(&ifp->if_snd);
846                 IFQ_POLL_NOLOCK(&ifp->if_snd, m);
847                 if (m == NULL) {
848                         IFQ_UNLOCK(&ifp->if_snd);
849                         return;
850                 }
851                 IFQ_UNLOCK(&ifp->if_snd);
852         }
853
854         TUN_LOCK(tp);
855         if (tp->tun_flags & TUN_RWAIT) {
856                 tp->tun_flags &= ~TUN_RWAIT;
857                 wakeup(tp);
858         }
859         selwakeuppri(&tp->tun_rsel, PZERO + 1);
860         KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
861         if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
862                 TUN_UNLOCK(tp);
863                 pgsigio(&tp->tun_sigio, SIGIO, 0);
864         } else
865                 TUN_UNLOCK(tp);
866 }
867
868 /*
869  * tunstart_l2
870  *
871  * queue packets from higher level ready to put out
872  */
873 static void
874 tunstart_l2(struct ifnet *ifp)
875 {
876         struct tuntap_softc     *tp = ifp->if_softc;
877
878         TUNDEBUG(ifp, "starting\n");
879
880         /*
881          * do not junk pending output if we are in VMnet mode.
882          * XXX: can this do any harm because of queue overflow?
883          */
884
885         TUN_LOCK(tp);
886         if (((tp->tun_flags & TUN_VMNET) == 0) &&
887             ((tp->tun_flags & TUN_READY) != TUN_READY)) {
888                 struct mbuf *m;
889
890                 /* Unlocked read. */
891                 TUNDEBUG(ifp, "not ready, tun_flags = 0x%x\n", tp->tun_flags);
892
893                 for (;;) {
894                         IF_DEQUEUE(&ifp->if_snd, m);
895                         if (m != NULL) {
896                                 m_freem(m);
897                                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
898                         } else
899                                 break;
900                 }
901                 TUN_UNLOCK(tp);
902
903                 return;
904         }
905
906         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
907
908         if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
909                 if (tp->tun_flags & TUN_RWAIT) {
910                         tp->tun_flags &= ~TUN_RWAIT;
911                         wakeup(tp);
912                 }
913
914                 if ((tp->tun_flags & TUN_ASYNC) && (tp->tun_sigio != NULL)) {
915                         TUN_UNLOCK(tp);
916                         pgsigio(&tp->tun_sigio, SIGIO, 0);
917                         TUN_LOCK(tp);
918                 }
919
920                 selwakeuppri(&tp->tun_rsel, PZERO+1);
921                 KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
922                 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* obytes are counted in ether_output */
923         }
924
925         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
926         TUN_UNLOCK(tp);
927 } /* tunstart_l2 */
928
929 static int
930 tap_transmit(struct ifnet *ifp, struct mbuf *m)
931 {
932         int error;
933
934         BPF_MTAP(ifp, m);
935         IFQ_HANDOFF(ifp, m, error);
936         return (error);
937 }
938
939 /* XXX: should return an error code so it can fail. */
940 static void
941 tuncreate(struct cdev *dev)
942 {
943         struct tuntap_driver *drv;
944         struct tuntap_softc *tp;
945         struct ifnet *ifp;
946         struct ether_addr eaddr;
947         int iflags;
948         u_char type;
949
950         tp = dev->si_drv1;
951         KASSERT(tp != NULL,
952             ("si_drv1 should have been initialized at creation"));
953
954         drv = tp->tun_drv;
955         iflags = IFF_MULTICAST;
956         if ((tp->tun_flags & TUN_L2) != 0) {
957                 type = IFT_ETHER;
958                 iflags |= IFF_BROADCAST | IFF_SIMPLEX;
959         } else {
960                 type = IFT_PPP;
961                 iflags |= IFF_POINTOPOINT;
962         }
963         ifp = tp->tun_ifp = if_alloc(type);
964         if (ifp == NULL)
965                 panic("%s%d: failed to if_alloc() interface.\n",
966                     drv->cdevsw.d_name, dev2unit(dev));
967         ifp->if_softc = tp;
968         if_initname(ifp, drv->cdevsw.d_name, dev2unit(dev));
969         ifp->if_ioctl = tunifioctl;
970         ifp->if_flags = iflags;
971         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
972         ifp->if_capabilities |= IFCAP_LINKSTATE;
973         ifp->if_capenable |= IFCAP_LINKSTATE;
974
975         if ((tp->tun_flags & TUN_L2) != 0) {
976                 ifp->if_init = tunifinit;
977                 ifp->if_start = tunstart_l2;
978                 ifp->if_transmit = tap_transmit;
979                 ifp->if_qflush = if_qflush;
980
981                 ether_gen_addr(ifp, &eaddr);
982                 ether_ifattach(ifp, eaddr.octet);
983         } else {
984                 ifp->if_mtu = TUNMTU;
985                 ifp->if_start = tunstart;
986                 ifp->if_output = tunoutput;
987
988                 ifp->if_snd.ifq_drv_maxlen = 0;
989                 IFQ_SET_READY(&ifp->if_snd);
990
991                 if_attach(ifp);
992                 bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
993         }
994
995         TUN_LOCK(tp);
996         tp->tun_flags |= TUN_INITED;
997         TUN_UNLOCK(tp);
998
999         TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
1000             ifp->if_xname, dev2unit(dev));
1001 }
1002
1003 static void
1004 tunrename(void *arg __unused, struct ifnet *ifp)
1005 {
1006         struct tuntap_softc *tp;
1007         int error;
1008
1009         if ((ifp->if_flags & IFF_RENAMING) == 0)
1010                 return;
1011
1012         if (tuntap_driver_from_ifnet(ifp) == NULL)
1013                 return;
1014
1015         /*
1016          * We need to grab the ioctl sx long enough to make sure the softc is
1017          * still there.  If it is, we can safely try to busy the tun device.
1018          * The busy may fail if the device is currently dying, in which case
1019          * we do nothing.  If it doesn't fail, the busy count stops the device
1020          * from dying until we've created the alias (that will then be
1021          * subsequently destroyed).
1022          */
1023         sx_xlock(&tun_ioctl_sx);
1024         tp = ifp->if_softc;
1025         if (tp == NULL) {
1026                 sx_xunlock(&tun_ioctl_sx);
1027                 return;
1028         }
1029         error = tun_busy(tp);
1030         sx_xunlock(&tun_ioctl_sx);
1031         if (error != 0)
1032                 return;
1033         if (tp->tun_alias != NULL) {
1034                 destroy_dev(tp->tun_alias);
1035                 tp->tun_alias = NULL;
1036         }
1037
1038         if (strcmp(ifp->if_xname, tp->tun_dev->si_name) == 0)
1039                 goto out;
1040
1041         /*
1042          * Failure's ok, aliases are created on a best effort basis.  If a
1043          * tun user/consumer decides to rename the interface to conflict with
1044          * another device (non-ifnet) on the system, we will assume they know
1045          * what they are doing.  make_dev_alias_p won't touch tun_alias on
1046          * failure, so we use it but ignore the return value.
1047          */
1048         make_dev_alias_p(MAKEDEV_CHECKNAME, &tp->tun_alias, tp->tun_dev, "%s",
1049             ifp->if_xname);
1050 out:
1051         tun_unbusy(tp);
1052 }
1053
1054 static int
1055 tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
1056 {
1057         struct ifnet    *ifp;
1058         struct tuntap_softc *tp;
1059         int error, tunflags;
1060
1061         tunflags = 0;
1062         CURVNET_SET(TD_TO_VNET(td));
1063         error = tuntap_name2info(dev->si_name, NULL, &tunflags);
1064         if (error != 0) {
1065                 CURVNET_RESTORE();
1066                 return (error); /* Shouldn't happen */
1067         }
1068
1069         tp = dev->si_drv1;
1070         KASSERT(tp != NULL,
1071             ("si_drv1 should have been initialized at creation"));
1072
1073         TUN_LOCK(tp);
1074         if ((tp->tun_flags & TUN_INITED) == 0) {
1075                 TUN_UNLOCK(tp);
1076                 CURVNET_RESTORE();
1077                 return (ENXIO);
1078         }
1079         if ((tp->tun_flags & (TUN_OPEN | TUN_DYING)) != 0) {
1080                 TUN_UNLOCK(tp);
1081                 CURVNET_RESTORE();
1082                 return (EBUSY);
1083         }
1084
1085         error = tun_busy_locked(tp);
1086         KASSERT(error == 0, ("Must be able to busy an unopen tunnel"));
1087         ifp = TUN2IFP(tp);
1088
1089         if ((tp->tun_flags & TUN_L2) != 0) {
1090                 bcopy(IF_LLADDR(ifp), tp->tun_ether.octet,
1091                     sizeof(tp->tun_ether.octet));
1092
1093                 ifp->if_drv_flags |= IFF_DRV_RUNNING;
1094                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1095
1096                 if (tapuponopen)
1097                         ifp->if_flags |= IFF_UP;
1098         }
1099
1100         tp->tun_pid = td->td_proc->p_pid;
1101         tp->tun_flags |= TUN_OPEN;
1102
1103         if_link_state_change(ifp, LINK_STATE_UP);
1104         TUNDEBUG(ifp, "open\n");
1105         TUN_UNLOCK(tp);
1106
1107         /*
1108          * This can fail with either ENOENT or EBUSY.  This is in the middle of
1109          * d_open, so ENOENT should not be possible.  EBUSY is possible, but
1110          * the only cdevpriv dtor being set will be tundtor and the softc being
1111          * passed is constant for a given cdev.  We ignore the possible error
1112          * because of this as either "unlikely" or "not actually a problem."
1113          */
1114         (void)devfs_set_cdevpriv(tp, tundtor);
1115         CURVNET_RESTORE();
1116         return (0);
1117 }
1118
1119 /*
1120  * tundtor - tear down the device - mark i/f down & delete
1121  * routing info
1122  */
1123 static void
1124 tundtor(void *data)
1125 {
1126         struct proc *p;
1127         struct tuntap_softc *tp;
1128         struct ifnet *ifp;
1129         bool l2tun;
1130
1131         tp = data;
1132         p = curproc;
1133         ifp = TUN2IFP(tp);
1134
1135         TUN_LOCK(tp);
1136
1137         /*
1138          * Realistically, we can't be obstinate here.  This only means that the
1139          * tuntap device was closed out of order, and the last closer wasn't the
1140          * controller.  These are still good to know about, though, as software
1141          * should avoid multiple processes with a tuntap device open and
1142          * ill-defined transfer of control (e.g., handoff, TUNSIFPID, close in
1143          * parent).
1144          */
1145         if (p->p_pid != tp->tun_pid) {
1146                 log(LOG_INFO,
1147                     "pid %d (%s), %s: tun/tap protocol violation, non-controlling process closed last.\n",
1148                     p->p_pid, p->p_comm, tp->tun_dev->si_name);
1149         }
1150
1151         /*
1152          * junk all pending output
1153          */
1154         CURVNET_SET(ifp->if_vnet);
1155
1156         l2tun = false;
1157         if ((tp->tun_flags & TUN_L2) != 0) {
1158                 l2tun = true;
1159                 IF_DRAIN(&ifp->if_snd);
1160         } else {
1161                 IFQ_PURGE(&ifp->if_snd);
1162         }
1163
1164         /* For vmnet, we won't do most of the address/route bits */
1165         if ((tp->tun_flags & TUN_VMNET) != 0 ||
1166             (l2tun && (ifp->if_flags & IFF_LINK0) != 0))
1167                 goto out;
1168
1169         if (ifp->if_flags & IFF_UP) {
1170                 TUN_UNLOCK(tp);
1171                 if_down(ifp);
1172                 TUN_LOCK(tp);
1173         }
1174
1175         /* Delete all addresses and routes which reference this interface. */
1176         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1177                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1178                 TUN_UNLOCK(tp);
1179                 if_purgeaddrs(ifp);
1180                 TUN_LOCK(tp);
1181         }
1182
1183 out:
1184         if_link_state_change(ifp, LINK_STATE_DOWN);
1185         CURVNET_RESTORE();
1186
1187         funsetown(&tp->tun_sigio);
1188         selwakeuppri(&tp->tun_rsel, PZERO + 1);
1189         KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
1190         TUNDEBUG (ifp, "closed\n");
1191         tp->tun_flags &= ~TUN_OPEN;
1192         tp->tun_pid = 0;
1193         tun_vnethdr_set(ifp, 0);
1194
1195         tun_unbusy_locked(tp);
1196         TUN_UNLOCK(tp);
1197 }
1198
1199 static void
1200 tuninit(struct ifnet *ifp)
1201 {
1202         struct tuntap_softc *tp = ifp->if_softc;
1203
1204         TUNDEBUG(ifp, "tuninit\n");
1205
1206         TUN_LOCK(tp);
1207         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1208         if ((tp->tun_flags & TUN_L2) == 0) {
1209                 ifp->if_flags |= IFF_UP;
1210                 getmicrotime(&ifp->if_lastchange);
1211                 TUN_UNLOCK(tp);
1212         } else {
1213                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1214                 TUN_UNLOCK(tp);
1215                 /* attempt to start output */
1216                 tunstart_l2(ifp);
1217         }
1218
1219 }
1220
1221 /*
1222  * Used only for l2 tunnel.
1223  */
1224 static void
1225 tunifinit(void *xtp)
1226 {
1227         struct tuntap_softc *tp;
1228
1229         tp = (struct tuntap_softc *)xtp;
1230         tuninit(tp->tun_ifp);
1231 }
1232
1233 /*
1234  * To be called under TUN_LOCK. Update ifp->if_hwassist according to the
1235  * current value of ifp->if_capenable.
1236  */
1237 static void
1238 tun_caps_changed(struct ifnet *ifp)
1239 {
1240         uint64_t hwassist = 0;
1241
1242         TUN_LOCK_ASSERT((struct tuntap_softc *)ifp->if_softc);
1243         if (ifp->if_capenable & IFCAP_TXCSUM)
1244                 hwassist |= CSUM_TCP | CSUM_UDP;
1245         if (ifp->if_capenable & IFCAP_TXCSUM_IPV6)
1246                 hwassist |= CSUM_TCP_IPV6
1247                     | CSUM_UDP_IPV6;
1248         if (ifp->if_capenable & IFCAP_TSO4)
1249                 hwassist |= CSUM_IP_TSO;
1250         if (ifp->if_capenable & IFCAP_TSO6)
1251                 hwassist |= CSUM_IP6_TSO;
1252         ifp->if_hwassist = hwassist;
1253 }
1254
1255 /*
1256  * To be called under TUN_LOCK. Update tp->tun_vhdrlen and adjust
1257  * if_capabilities and if_capenable as needed.
1258  */
1259 static void
1260 tun_vnethdr_set(struct ifnet *ifp, int vhdrlen)
1261 {
1262         struct tuntap_softc *tp = ifp->if_softc;
1263
1264         TUN_LOCK_ASSERT(tp);
1265
1266         if (tp->tun_vhdrlen == vhdrlen)
1267                 return;
1268
1269         /*
1270          * Update if_capabilities to reflect the
1271          * functionalities offered by the virtio-net
1272          * header.
1273          */
1274         if (vhdrlen != 0)
1275                 ifp->if_capabilities |=
1276                         TAP_VNET_HDR_CAPS;
1277         else
1278                 ifp->if_capabilities &=
1279                         ~TAP_VNET_HDR_CAPS;
1280         /*
1281          * Disable any capabilities that we don't
1282          * support anymore.
1283          */
1284         ifp->if_capenable &= ifp->if_capabilities;
1285         tun_caps_changed(ifp);
1286         tp->tun_vhdrlen = vhdrlen;
1287
1288         TUNDEBUG(ifp, "vnet_hdr_len=%d, if_capabilities=%x\n",
1289             vhdrlen, ifp->if_capabilities);
1290 }
1291
1292 /*
1293  * Process an ioctl request.
1294  */
1295 static int
1296 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1297 {
1298         struct ifreq *ifr = (struct ifreq *)data;
1299         struct tuntap_softc *tp;
1300         struct ifstat *ifs;
1301         struct ifmediareq       *ifmr;
1302         int             dummy, error = 0;
1303         bool            l2tun;
1304
1305         ifmr = NULL;
1306         sx_xlock(&tun_ioctl_sx);
1307         tp = ifp->if_softc;
1308         if (tp == NULL) {
1309                 error = ENXIO;
1310                 goto bad;
1311         }
1312         l2tun = (tp->tun_flags & TUN_L2) != 0;
1313         switch(cmd) {
1314         case SIOCGIFSTATUS:
1315                 ifs = (struct ifstat *)data;
1316                 TUN_LOCK(tp);
1317                 if (tp->tun_pid)
1318                         snprintf(ifs->ascii, sizeof(ifs->ascii),
1319                             "\tOpened by PID %d\n", tp->tun_pid);
1320                 else
1321                         ifs->ascii[0] = '\0';
1322                 TUN_UNLOCK(tp);
1323                 break;
1324         case SIOCSIFADDR:
1325                 if (l2tun)
1326                         error = ether_ioctl(ifp, cmd, data);
1327                 else
1328                         tuninit(ifp);
1329                 if (error == 0)
1330                     TUNDEBUG(ifp, "address set\n");
1331                 break;
1332         case SIOCSIFMTU:
1333                 ifp->if_mtu = ifr->ifr_mtu;
1334                 TUNDEBUG(ifp, "mtu set\n");
1335                 break;
1336         case SIOCSIFFLAGS:
1337         case SIOCADDMULTI:
1338         case SIOCDELMULTI:
1339                 break;
1340         case SIOCGIFMEDIA:
1341                 if (!l2tun) {
1342                         error = EINVAL;
1343                         break;
1344                 }
1345
1346                 ifmr = (struct ifmediareq *)data;
1347                 dummy = ifmr->ifm_count;
1348                 ifmr->ifm_count = 1;
1349                 ifmr->ifm_status = IFM_AVALID;
1350                 ifmr->ifm_active = IFM_ETHER;
1351                 if (tp->tun_flags & TUN_OPEN)
1352                         ifmr->ifm_status |= IFM_ACTIVE;
1353                 ifmr->ifm_current = ifmr->ifm_active;
1354                 if (dummy >= 1) {
1355                         int media = IFM_ETHER;
1356                         error = copyout(&media, ifmr->ifm_ulist, sizeof(int));
1357                 }
1358                 break;
1359         case SIOCSIFCAP:
1360                 TUN_LOCK(tp);
1361                 ifp->if_capenable = ifr->ifr_reqcap;
1362                 tun_caps_changed(ifp);
1363                 TUN_UNLOCK(tp);
1364                 VLAN_CAPABILITIES(ifp);
1365                 break;
1366         default:
1367                 if (l2tun) {
1368                         error = ether_ioctl(ifp, cmd, data);
1369                 } else {
1370                         error = EINVAL;
1371                 }
1372         }
1373 bad:
1374         sx_xunlock(&tun_ioctl_sx);
1375         return (error);
1376 }
1377
1378 /*
1379  * tunoutput - queue packets from higher level ready to put out.
1380  */
1381 static int
1382 tunoutput(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst,
1383     struct route *ro)
1384 {
1385         struct tuntap_softc *tp = ifp->if_softc;
1386         u_short cached_tun_flags;
1387         int error;
1388         u_int32_t af;
1389
1390         TUNDEBUG (ifp, "tunoutput\n");
1391
1392 #ifdef MAC
1393         error = mac_ifnet_check_transmit(ifp, m0);
1394         if (error) {
1395                 m_freem(m0);
1396                 return (error);
1397         }
1398 #endif
1399
1400         /* Could be unlocked read? */
1401         TUN_LOCK(tp);
1402         cached_tun_flags = tp->tun_flags;
1403         TUN_UNLOCK(tp);
1404         if ((cached_tun_flags & TUN_READY) != TUN_READY) {
1405                 TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
1406                 m_freem (m0);
1407                 return (EHOSTDOWN);
1408         }
1409
1410         if ((ifp->if_flags & IFF_UP) != IFF_UP) {
1411                 m_freem (m0);
1412                 return (EHOSTDOWN);
1413         }
1414
1415         /* BPF writes need to be handled specially. */
1416         if (dst->sa_family == AF_UNSPEC)
1417                 bcopy(dst->sa_data, &af, sizeof(af));
1418         else
1419                 af = RO_GET_FAMILY(ro, dst);
1420
1421         BPF_MTAP2(ifp, &af, sizeof(af), m0);
1422
1423         /* prepend sockaddr? this may abort if the mbuf allocation fails */
1424         if (cached_tun_flags & TUN_LMODE) {
1425                 /* allocate space for sockaddr */
1426                 M_PREPEND(m0, dst->sa_len, M_NOWAIT);
1427
1428                 /* if allocation failed drop packet */
1429                 if (m0 == NULL) {
1430                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1431                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1432                         return (ENOBUFS);
1433                 } else {
1434                         bcopy(dst, m0->m_data, dst->sa_len);
1435                 }
1436         }
1437
1438         if (cached_tun_flags & TUN_IFHEAD) {
1439                 /* Prepend the address family */
1440                 M_PREPEND(m0, 4, M_NOWAIT);
1441
1442                 /* if allocation failed drop packet */
1443                 if (m0 == NULL) {
1444                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1445                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1446                         return (ENOBUFS);
1447                 } else
1448                         *(u_int32_t *)m0->m_data = htonl(af);
1449         } else {
1450 #ifdef INET
1451                 if (af != AF_INET)
1452 #endif
1453                 {
1454                         m_freem(m0);
1455                         return (EAFNOSUPPORT);
1456                 }
1457         }
1458
1459         error = (ifp->if_transmit)(ifp, m0);
1460         if (error)
1461                 return (ENOBUFS);
1462         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1463         return (0);
1464 }
1465
1466 /*
1467  * the cdevsw interface is now pretty minimal.
1468  */
1469 static  int
1470 tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag,
1471     struct thread *td)
1472 {
1473         struct ifreq ifr, *ifrp;
1474         struct tuntap_softc *tp = dev->si_drv1;
1475         struct ifnet *ifp = TUN2IFP(tp);
1476         struct tuninfo *tunp;
1477         int error, iflags, ival;
1478         bool    l2tun;
1479
1480         l2tun = (tp->tun_flags & TUN_L2) != 0;
1481         if (l2tun) {
1482                 /* tap specific ioctls */
1483                 switch(cmd) {
1484                 /* VMware/VMnet port ioctl's */
1485 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
1486     defined(COMPAT_FREEBSD4)
1487                 case _IO('V', 0):
1488                         ival = IOCPARM_IVAL(data);
1489                         data = (caddr_t)&ival;
1490                         /* FALLTHROUGH */
1491 #endif
1492                 case VMIO_SIOCSIFFLAGS: /* VMware/VMnet SIOCSIFFLAGS */
1493                         iflags = *(int *)data;
1494                         iflags &= TUN_VMIO_FLAG_MASK;
1495                         iflags &= ~IFF_CANTCHANGE;
1496                         iflags |= IFF_UP;
1497
1498                         TUN_LOCK(tp);
1499                         ifp->if_flags = iflags |
1500                             (ifp->if_flags & IFF_CANTCHANGE);
1501                         TUN_UNLOCK(tp);
1502
1503                         return (0);
1504                 case SIOCGIFADDR:       /* get MAC address of the remote side */
1505                         TUN_LOCK(tp);
1506                         bcopy(&tp->tun_ether.octet, data,
1507                             sizeof(tp->tun_ether.octet));
1508                         TUN_UNLOCK(tp);
1509
1510                         return (0);
1511                 case SIOCSIFADDR:       /* set MAC address of the remote side */
1512                         TUN_LOCK(tp);
1513                         bcopy(data, &tp->tun_ether.octet,
1514                             sizeof(tp->tun_ether.octet));
1515                         TUN_UNLOCK(tp);
1516
1517                         return (0);
1518                 case TAPSVNETHDR:
1519                         ival = *(int *)data;
1520                         if (ival != 0 &&
1521                             ival != sizeof(struct virtio_net_hdr) &&
1522                             ival != sizeof(struct virtio_net_hdr_mrg_rxbuf)) {
1523                                 return (EINVAL);
1524                         }
1525                         TUN_LOCK(tp);
1526                         tun_vnethdr_set(ifp, ival);
1527                         TUN_UNLOCK(tp);
1528
1529                         return (0);
1530                 case TAPGVNETHDR:
1531                         TUN_LOCK(tp);
1532                         *(int *)data = tp->tun_vhdrlen;
1533                         TUN_UNLOCK(tp);
1534
1535                         return (0);
1536                 }
1537
1538                 /* Fall through to the common ioctls if unhandled */
1539         } else {
1540                 switch (cmd) {
1541                 case TUNSLMODE:
1542                         TUN_LOCK(tp);
1543                         if (*(int *)data) {
1544                                 tp->tun_flags |= TUN_LMODE;
1545                                 tp->tun_flags &= ~TUN_IFHEAD;
1546                         } else
1547                                 tp->tun_flags &= ~TUN_LMODE;
1548                         TUN_UNLOCK(tp);
1549
1550                         return (0);
1551                 case TUNSIFHEAD:
1552                         TUN_LOCK(tp);
1553                         if (*(int *)data) {
1554                                 tp->tun_flags |= TUN_IFHEAD;
1555                                 tp->tun_flags &= ~TUN_LMODE;
1556                         } else
1557                                 tp->tun_flags &= ~TUN_IFHEAD;
1558                         TUN_UNLOCK(tp);
1559
1560                         return (0);
1561                 case TUNGIFHEAD:
1562                         TUN_LOCK(tp);
1563                         *(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
1564                         TUN_UNLOCK(tp);
1565
1566                         return (0);
1567                 case TUNSIFMODE:
1568                         /* deny this if UP */
1569                         if (TUN2IFP(tp)->if_flags & IFF_UP)
1570                                 return (EBUSY);
1571
1572                         switch (*(int *)data & ~IFF_MULTICAST) {
1573                         case IFF_POINTOPOINT:
1574                         case IFF_BROADCAST:
1575                                 TUN_LOCK(tp);
1576                                 TUN2IFP(tp)->if_flags &=
1577                                     ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
1578                                 TUN2IFP(tp)->if_flags |= *(int *)data;
1579                                 TUN_UNLOCK(tp);
1580
1581                                 break;
1582                         default:
1583                                 return (EINVAL);
1584                         }
1585
1586                         return (0);
1587                 case TUNSIFPID:
1588                         TUN_LOCK(tp);
1589                         tp->tun_pid = curthread->td_proc->p_pid;
1590                         TUN_UNLOCK(tp);
1591
1592                         return (0);
1593                 }
1594                 /* Fall through to the common ioctls if unhandled */
1595         }
1596
1597         switch (cmd) {
1598         case TUNGIFNAME:
1599                 ifrp = (struct ifreq *)data;
1600                 strlcpy(ifrp->ifr_name, TUN2IFP(tp)->if_xname, IFNAMSIZ);
1601
1602                 return (0);
1603         case TUNSIFINFO:
1604                 tunp = (struct tuninfo *)data;
1605                 if (TUN2IFP(tp)->if_type != tunp->type)
1606                         return (EPROTOTYPE);
1607                 TUN_LOCK(tp);
1608                 if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
1609                         strlcpy(ifr.ifr_name, if_name(TUN2IFP(tp)), IFNAMSIZ);
1610                         ifr.ifr_mtu = tunp->mtu;
1611                         CURVNET_SET(TUN2IFP(tp)->if_vnet);
1612                         error = ifhwioctl(SIOCSIFMTU, TUN2IFP(tp),
1613                             (caddr_t)&ifr, td);
1614                         CURVNET_RESTORE();
1615                         if (error) {
1616                                 TUN_UNLOCK(tp);
1617                                 return (error);
1618                         }
1619                 }
1620                 TUN2IFP(tp)->if_baudrate = tunp->baudrate;
1621                 TUN_UNLOCK(tp);
1622                 break;
1623         case TUNGIFINFO:
1624                 tunp = (struct tuninfo *)data;
1625                 TUN_LOCK(tp);
1626                 tunp->mtu = TUN2IFP(tp)->if_mtu;
1627                 tunp->type = TUN2IFP(tp)->if_type;
1628                 tunp->baudrate = TUN2IFP(tp)->if_baudrate;
1629                 TUN_UNLOCK(tp);
1630                 break;
1631         case TUNSDEBUG:
1632                 tundebug = *(int *)data;
1633                 break;
1634         case TUNGDEBUG:
1635                 *(int *)data = tundebug;
1636                 break;
1637         case FIONBIO:
1638                 break;
1639         case FIOASYNC:
1640                 TUN_LOCK(tp);
1641                 if (*(int *)data)
1642                         tp->tun_flags |= TUN_ASYNC;
1643                 else
1644                         tp->tun_flags &= ~TUN_ASYNC;
1645                 TUN_UNLOCK(tp);
1646                 break;
1647         case FIONREAD:
1648                 if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
1649                         struct mbuf *mb;
1650                         IFQ_LOCK(&TUN2IFP(tp)->if_snd);
1651                         IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
1652                         for (*(int *)data = 0; mb != NULL; mb = mb->m_next)
1653                                 *(int *)data += mb->m_len;
1654                         IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
1655                 } else
1656                         *(int *)data = 0;
1657                 break;
1658         case FIOSETOWN:
1659                 return (fsetown(*(int *)data, &tp->tun_sigio));
1660
1661         case FIOGETOWN:
1662                 *(int *)data = fgetown(&tp->tun_sigio);
1663                 return (0);
1664
1665         /* This is deprecated, FIOSETOWN should be used instead. */
1666         case TIOCSPGRP:
1667                 return (fsetown(-(*(int *)data), &tp->tun_sigio));
1668
1669         /* This is deprecated, FIOGETOWN should be used instead. */
1670         case TIOCGPGRP:
1671                 *(int *)data = -fgetown(&tp->tun_sigio);
1672                 return (0);
1673
1674         default:
1675                 return (ENOTTY);
1676         }
1677         return (0);
1678 }
1679
1680 /*
1681  * The cdevsw read interface - reads a packet at a time, or at
1682  * least as much of a packet as can be read.
1683  */
1684 static  int
1685 tunread(struct cdev *dev, struct uio *uio, int flag)
1686 {
1687         struct tuntap_softc *tp = dev->si_drv1;
1688         struct ifnet    *ifp = TUN2IFP(tp);
1689         struct mbuf     *m;
1690         size_t          len;
1691         int             error = 0;
1692
1693         TUNDEBUG (ifp, "read\n");
1694         TUN_LOCK(tp);
1695         if ((tp->tun_flags & TUN_READY) != TUN_READY) {
1696                 TUN_UNLOCK(tp);
1697                 TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
1698                 return (EHOSTDOWN);
1699         }
1700
1701         tp->tun_flags &= ~TUN_RWAIT;
1702
1703         for (;;) {
1704                 IFQ_DEQUEUE(&ifp->if_snd, m);
1705                 if (m != NULL)
1706                         break;
1707                 if (flag & O_NONBLOCK) {
1708                         TUN_UNLOCK(tp);
1709                         return (EWOULDBLOCK);
1710                 }
1711                 tp->tun_flags |= TUN_RWAIT;
1712                 error = mtx_sleep(tp, &tp->tun_mtx, PCATCH | (PZERO + 1),
1713                     "tunread", 0);
1714                 if (error != 0) {
1715                         TUN_UNLOCK(tp);
1716                         return (error);
1717                 }
1718         }
1719         TUN_UNLOCK(tp);
1720
1721         len = min(tp->tun_vhdrlen, uio->uio_resid);
1722         if (len > 0) {
1723                 struct virtio_net_hdr_mrg_rxbuf vhdr;
1724
1725                 bzero(&vhdr, sizeof(vhdr));
1726                 if (m->m_pkthdr.csum_flags & TAP_ALL_OFFLOAD) {
1727                         m = virtio_net_tx_offload(ifp, m, false, &vhdr.hdr);
1728                 }
1729
1730                 TUNDEBUG(ifp, "txvhdr: f %u, gt %u, hl %u, "
1731                     "gs %u, cs %u, co %u\n", vhdr.hdr.flags,
1732                     vhdr.hdr.gso_type, vhdr.hdr.hdr_len,
1733                     vhdr.hdr.gso_size, vhdr.hdr.csum_start,
1734                     vhdr.hdr.csum_offset);
1735                 error = uiomove(&vhdr, len, uio);
1736         }
1737
1738         while (m && uio->uio_resid > 0 && error == 0) {
1739                 len = min(uio->uio_resid, m->m_len);
1740                 if (len != 0)
1741                         error = uiomove(mtod(m, void *), len, uio);
1742                 m = m_free(m);
1743         }
1744
1745         if (m) {
1746                 TUNDEBUG(ifp, "Dropping mbuf\n");
1747                 m_freem(m);
1748         }
1749         return (error);
1750 }
1751
1752 static int
1753 tunwrite_l2(struct tuntap_softc *tp, struct mbuf *m,
1754             struct virtio_net_hdr_mrg_rxbuf *vhdr)
1755 {
1756         struct epoch_tracker et;
1757         struct ether_header *eh;
1758         struct ifnet *ifp;
1759
1760         ifp = TUN2IFP(tp);
1761
1762         /*
1763          * Only pass a unicast frame to ether_input(), if it would
1764          * actually have been received by non-virtual hardware.
1765          */
1766         if (m->m_len < sizeof(struct ether_header)) {
1767                 m_freem(m);
1768                 return (0);
1769         }
1770
1771         eh = mtod(m, struct ether_header *);
1772
1773         if (eh && (ifp->if_flags & IFF_PROMISC) == 0 &&
1774             !ETHER_IS_MULTICAST(eh->ether_dhost) &&
1775             bcmp(eh->ether_dhost, IF_LLADDR(ifp), ETHER_ADDR_LEN) != 0) {
1776                 m_freem(m);
1777                 return (0);
1778         }
1779
1780         if (vhdr != NULL && virtio_net_rx_csum(m, &vhdr->hdr)) {
1781                 m_freem(m);
1782                 return (0);
1783         }
1784
1785         /* Pass packet up to parent. */
1786         CURVNET_SET(ifp->if_vnet);
1787         NET_EPOCH_ENTER(et);
1788         (*ifp->if_input)(ifp, m);
1789         NET_EPOCH_EXIT(et);
1790         CURVNET_RESTORE();
1791         /* ibytes are counted in parent */
1792         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1793         return (0);
1794 }
1795
1796 static int
1797 tunwrite_l3(struct tuntap_softc *tp, struct mbuf *m)
1798 {
1799         struct epoch_tracker et;
1800         struct ifnet *ifp;
1801         int family, isr;
1802
1803         ifp = TUN2IFP(tp);
1804         /* Could be unlocked read? */
1805         TUN_LOCK(tp);
1806         if (tp->tun_flags & TUN_IFHEAD) {
1807                 TUN_UNLOCK(tp);
1808                 if (m->m_len < sizeof(family) &&
1809                 (m = m_pullup(m, sizeof(family))) == NULL)
1810                         return (ENOBUFS);
1811                 family = ntohl(*mtod(m, u_int32_t *));
1812                 m_adj(m, sizeof(family));
1813         } else {
1814                 TUN_UNLOCK(tp);
1815                 family = AF_INET;
1816         }
1817
1818         BPF_MTAP2(ifp, &family, sizeof(family), m);
1819
1820         switch (family) {
1821 #ifdef INET
1822         case AF_INET:
1823                 isr = NETISR_IP;
1824                 break;
1825 #endif
1826 #ifdef INET6
1827         case AF_INET6:
1828                 isr = NETISR_IPV6;
1829                 break;
1830 #endif
1831         default:
1832                 m_freem(m);
1833                 return (EAFNOSUPPORT);
1834         }
1835         random_harvest_queue(m, sizeof(*m), RANDOM_NET_TUN);
1836         if_inc_counter(ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
1837         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1838         CURVNET_SET(ifp->if_vnet);
1839         M_SETFIB(m, ifp->if_fib);
1840         NET_EPOCH_ENTER(et);
1841         netisr_dispatch(isr, m);
1842         NET_EPOCH_EXIT(et);
1843         CURVNET_RESTORE();
1844         return (0);
1845 }
1846
1847 /*
1848  * the cdevsw write interface - an atomic write is a packet - or else!
1849  */
1850 static  int
1851 tunwrite(struct cdev *dev, struct uio *uio, int flag)
1852 {
1853         struct virtio_net_hdr_mrg_rxbuf vhdr;
1854         struct tuntap_softc *tp;
1855         struct ifnet    *ifp;
1856         struct mbuf     *m;
1857         uint32_t        mru;
1858         int             align, vhdrlen, error;
1859         bool            l2tun;
1860
1861         tp = dev->si_drv1;
1862         ifp = TUN2IFP(tp);
1863         TUNDEBUG(ifp, "tunwrite\n");
1864         if ((ifp->if_flags & IFF_UP) != IFF_UP)
1865                 /* ignore silently */
1866                 return (0);
1867
1868         if (uio->uio_resid == 0)
1869                 return (0);
1870
1871         l2tun = (tp->tun_flags & TUN_L2) != 0;
1872         mru = l2tun ? TAPMRU : TUNMRU;
1873         vhdrlen = tp->tun_vhdrlen;
1874         align = 0;
1875         if (l2tun) {
1876                 align = ETHER_ALIGN;
1877                 mru += vhdrlen;
1878         } else if ((tp->tun_flags & TUN_IFHEAD) != 0)
1879                 mru += sizeof(uint32_t);        /* family */
1880         if (uio->uio_resid < 0 || uio->uio_resid > mru) {
1881                 TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
1882                 return (EIO);
1883         }
1884
1885         if (vhdrlen > 0) {
1886                 error = uiomove(&vhdr, vhdrlen, uio);
1887                 if (error != 0)
1888                         return (error);
1889                 TUNDEBUG(ifp, "txvhdr: f %u, gt %u, hl %u, "
1890                     "gs %u, cs %u, co %u\n", vhdr.hdr.flags,
1891                     vhdr.hdr.gso_type, vhdr.hdr.hdr_len,
1892                     vhdr.hdr.gso_size, vhdr.hdr.csum_start,
1893                     vhdr.hdr.csum_offset);
1894         }
1895
1896         if ((m = m_uiotombuf(uio, M_NOWAIT, 0, align, M_PKTHDR)) == NULL) {
1897                 if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1898                 return (ENOBUFS);
1899         }
1900
1901         m->m_pkthdr.rcvif = ifp;
1902 #ifdef MAC
1903         mac_ifnet_create_mbuf(ifp, m);
1904 #endif
1905
1906         if (l2tun)
1907                 return (tunwrite_l2(tp, m, vhdrlen > 0 ? &vhdr : NULL));
1908
1909         return (tunwrite_l3(tp, m));
1910 }
1911
1912 /*
1913  * tunpoll - the poll interface, this is only useful on reads
1914  * really. The write detect always returns true, write never blocks
1915  * anyway, it either accepts the packet or drops it.
1916  */
1917 static  int
1918 tunpoll(struct cdev *dev, int events, struct thread *td)
1919 {
1920         struct tuntap_softc *tp = dev->si_drv1;
1921         struct ifnet    *ifp = TUN2IFP(tp);
1922         int             revents = 0;
1923
1924         TUNDEBUG(ifp, "tunpoll\n");
1925
1926         if (events & (POLLIN | POLLRDNORM)) {
1927                 IFQ_LOCK(&ifp->if_snd);
1928                 if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
1929                         TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
1930                         revents |= events & (POLLIN | POLLRDNORM);
1931                 } else {
1932                         TUNDEBUG(ifp, "tunpoll waiting\n");
1933                         selrecord(td, &tp->tun_rsel);
1934                 }
1935                 IFQ_UNLOCK(&ifp->if_snd);
1936         }
1937         revents |= events & (POLLOUT | POLLWRNORM);
1938
1939         return (revents);
1940 }
1941
1942 /*
1943  * tunkqfilter - support for the kevent() system call.
1944  */
1945 static int
1946 tunkqfilter(struct cdev *dev, struct knote *kn)
1947 {
1948         struct tuntap_softc     *tp = dev->si_drv1;
1949         struct ifnet    *ifp = TUN2IFP(tp);
1950
1951         switch(kn->kn_filter) {
1952         case EVFILT_READ:
1953                 TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
1954                     ifp->if_xname, dev2unit(dev));
1955                 kn->kn_fop = &tun_read_filterops;
1956                 break;
1957
1958         case EVFILT_WRITE:
1959                 TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
1960                     ifp->if_xname, dev2unit(dev));
1961                 kn->kn_fop = &tun_write_filterops;
1962                 break;
1963
1964         default:
1965                 TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1966                     ifp->if_xname, dev2unit(dev));
1967                 return(EINVAL);
1968         }
1969
1970         kn->kn_hook = tp;
1971         knlist_add(&tp->tun_rsel.si_note, kn, 0);
1972
1973         return (0);
1974 }
1975
1976 /*
1977  * Return true of there is data in the interface queue.
1978  */
1979 static int
1980 tunkqread(struct knote *kn, long hint)
1981 {
1982         int                     ret;
1983         struct tuntap_softc     *tp = kn->kn_hook;
1984         struct cdev             *dev = tp->tun_dev;
1985         struct ifnet    *ifp = TUN2IFP(tp);
1986
1987         if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1988                 TUNDEBUG(ifp,
1989                     "%s have data in the queue.  Len = %d, minor = %#x\n",
1990                     ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1991                 ret = 1;
1992         } else {
1993                 TUNDEBUG(ifp,
1994                     "%s waiting for data, minor = %#x\n", ifp->if_xname,
1995                     dev2unit(dev));
1996                 ret = 0;
1997         }
1998
1999         return (ret);
2000 }
2001
2002 /*
2003  * Always can write, always return MTU in kn->data.
2004  */
2005 static int
2006 tunkqwrite(struct knote *kn, long hint)
2007 {
2008         struct tuntap_softc     *tp = kn->kn_hook;
2009         struct ifnet    *ifp = TUN2IFP(tp);
2010
2011         kn->kn_data = ifp->if_mtu;
2012
2013         return (1);
2014 }
2015
2016 static void
2017 tunkqdetach(struct knote *kn)
2018 {
2019         struct tuntap_softc     *tp = kn->kn_hook;
2020
2021         knlist_remove(&tp->tun_rsel.si_note, kn, 0);
2022 }