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