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