Home | History | Annotate | Line # | Download | only in net
if_tap.c revision 1.108
      1 /*	$NetBSD: if_tap.c,v 1.108 2019/03/25 09:32:25 pgoyette Exp $	*/
      2 
      3 /*
      4  *  Copyright (c) 2003, 2004, 2008, 2009 The NetBSD Foundation.
      5  *  All rights reserved.
      6  *
      7  *  Redistribution and use in source and binary forms, with or without
      8  *  modification, are permitted provided that the following conditions
      9  *  are met:
     10  *  1. Redistributions of source code must retain the above copyright
     11  *     notice, this list of conditions and the following disclaimer.
     12  *  2. Redistributions in binary form must reproduce the above copyright
     13  *     notice, this list of conditions and the following disclaimer in the
     14  *     documentation and/or other materials provided with the distribution.
     15  *
     16  *  THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  *  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  *  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  *  PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  *  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  *  POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * tap(4) is a virtual Ethernet interface.  It appears as a real Ethernet
     31  * device to the system, but can also be accessed by userland through a
     32  * character device interface, which allows reading and injecting frames.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 __KERNEL_RCSID(0, "$NetBSD: if_tap.c,v 1.108 2019/03/25 09:32:25 pgoyette Exp $");
     37 
     38 #if defined(_KERNEL_OPT)
     39 
     40 #include "opt_modular.h"
     41 #include "opt_compat_netbsd.h"
     42 #endif
     43 
     44 #include <sys/param.h>
     45 #include <sys/atomic.h>
     46 #include <sys/conf.h>
     47 #include <sys/cprng.h>
     48 #include <sys/device.h>
     49 #include <sys/file.h>
     50 #include <sys/filedesc.h>
     51 #include <sys/intr.h>
     52 #include <sys/kauth.h>
     53 #include <sys/kernel.h>
     54 #include <sys/kmem.h>
     55 #include <sys/module.h>
     56 #include <sys/mutex.h>
     57 #include <sys/condvar.h>
     58 #include <sys/poll.h>
     59 #include <sys/proc.h>
     60 #include <sys/select.h>
     61 #include <sys/sockio.h>
     62 #include <sys/stat.h>
     63 #include <sys/sysctl.h>
     64 #include <sys/systm.h>
     65 
     66 #include <net/if.h>
     67 #include <net/if_dl.h>
     68 #include <net/if_ether.h>
     69 #include <net/if_media.h>
     70 #include <net/if_tap.h>
     71 #include <net/bpf.h>
     72 
     73 #include <compat/sys/sockio.h>
     74 
     75 #include "ioconf.h"
     76 
     77 /*
     78  * sysctl node management
     79  *
     80  * It's not really possible to use a SYSCTL_SETUP block with
     81  * current module implementation, so it is easier to just define
     82  * our own function.
     83  *
     84  * The handler function is a "helper" in Andrew Brown's sysctl
     85  * framework terminology.  It is used as a gateway for sysctl
     86  * requests over the nodes.
     87  *
     88  * tap_log allows the module to log creations of nodes and
     89  * destroy them all at once using sysctl_teardown.
     90  */
     91 static int	tap_node;
     92 static int	tap_sysctl_handler(SYSCTLFN_PROTO);
     93 static void	sysctl_tap_setup(struct sysctllog **);
     94 
     95 /*
     96  * Since we're an Ethernet device, we need the 2 following
     97  * components: a struct ethercom and a struct ifmedia
     98  * since we don't attach a PHY to ourselves.
     99  * We could emulate one, but there's no real point.
    100  */
    101 
    102 struct tap_softc {
    103 	device_t	sc_dev;
    104 	struct ifmedia	sc_im;
    105 	struct ethercom	sc_ec;
    106 	int		sc_flags;
    107 #define	TAP_INUSE	0x00000001	/* tap device can only be opened once */
    108 #define TAP_ASYNCIO	0x00000002	/* user is using async I/O (SIGIO) on the device */
    109 #define TAP_NBIO	0x00000004	/* user wants calls to avoid blocking */
    110 #define TAP_GOING	0x00000008	/* interface is being destroyed */
    111 	struct selinfo	sc_rsel;
    112 	pid_t		sc_pgid; /* For async. IO */
    113 	kmutex_t	sc_lock;
    114 	kcondvar_t	sc_cv;
    115 	void		*sc_sih;
    116 	struct timespec sc_atime;
    117 	struct timespec sc_mtime;
    118 	struct timespec sc_btime;
    119 };
    120 
    121 /* autoconf(9) glue */
    122 
    123 static int	tap_match(device_t, cfdata_t, void *);
    124 static void	tap_attach(device_t, device_t, void *);
    125 static int	tap_detach(device_t, int);
    126 
    127 CFATTACH_DECL_NEW(tap, sizeof(struct tap_softc),
    128     tap_match, tap_attach, tap_detach, NULL);
    129 extern struct cfdriver tap_cd;
    130 
    131 /* Real device access routines */
    132 static int	tap_dev_close(struct tap_softc *);
    133 static int	tap_dev_read(int, struct uio *, int);
    134 static int	tap_dev_write(int, struct uio *, int);
    135 static int	tap_dev_ioctl(int, u_long, void *, struct lwp *);
    136 static int	tap_dev_poll(int, int, struct lwp *);
    137 static int	tap_dev_kqfilter(int, struct knote *);
    138 
    139 /* Fileops access routines */
    140 static int	tap_fops_close(file_t *);
    141 static int	tap_fops_read(file_t *, off_t *, struct uio *,
    142     kauth_cred_t, int);
    143 static int	tap_fops_write(file_t *, off_t *, struct uio *,
    144     kauth_cred_t, int);
    145 static int	tap_fops_ioctl(file_t *, u_long, void *);
    146 static int	tap_fops_poll(file_t *, int);
    147 static int	tap_fops_stat(file_t *, struct stat *);
    148 static int	tap_fops_kqfilter(file_t *, struct knote *);
    149 
    150 static const struct fileops tap_fileops = {
    151 	.fo_name = "tap",
    152 	.fo_read = tap_fops_read,
    153 	.fo_write = tap_fops_write,
    154 	.fo_ioctl = tap_fops_ioctl,
    155 	.fo_fcntl = fnullop_fcntl,
    156 	.fo_poll = tap_fops_poll,
    157 	.fo_stat = tap_fops_stat,
    158 	.fo_close = tap_fops_close,
    159 	.fo_kqfilter = tap_fops_kqfilter,
    160 	.fo_restart = fnullop_restart,
    161 };
    162 
    163 /* Helper for cloning open() */
    164 static int	tap_dev_cloner(struct lwp *);
    165 
    166 /* Character device routines */
    167 static int	tap_cdev_open(dev_t, int, int, struct lwp *);
    168 static int	tap_cdev_close(dev_t, int, int, struct lwp *);
    169 static int	tap_cdev_read(dev_t, struct uio *, int);
    170 static int	tap_cdev_write(dev_t, struct uio *, int);
    171 static int	tap_cdev_ioctl(dev_t, u_long, void *, int, struct lwp *);
    172 static int	tap_cdev_poll(dev_t, int, struct lwp *);
    173 static int	tap_cdev_kqfilter(dev_t, struct knote *);
    174 
    175 const struct cdevsw tap_cdevsw = {
    176 	.d_open = tap_cdev_open,
    177 	.d_close = tap_cdev_close,
    178 	.d_read = tap_cdev_read,
    179 	.d_write = tap_cdev_write,
    180 	.d_ioctl = tap_cdev_ioctl,
    181 	.d_stop = nostop,
    182 	.d_tty = notty,
    183 	.d_poll = tap_cdev_poll,
    184 	.d_mmap = nommap,
    185 	.d_kqfilter = tap_cdev_kqfilter,
    186 	.d_discard = nodiscard,
    187 	.d_flag = D_OTHER | D_MPSAFE
    188 };
    189 
    190 #define TAP_CLONER	0xfffff		/* Maximal minor value */
    191 
    192 /* kqueue-related routines */
    193 static void	tap_kqdetach(struct knote *);
    194 static int	tap_kqread(struct knote *, long);
    195 
    196 /*
    197  * Those are needed by the if_media interface.
    198  */
    199 
    200 static int	tap_mediachange(struct ifnet *);
    201 static void	tap_mediastatus(struct ifnet *, struct ifmediareq *);
    202 
    203 /*
    204  * Those are needed by the ifnet interface, and would typically be
    205  * there for any network interface driver.
    206  * Some other routines are optional: watchdog and drain.
    207  */
    208 
    209 static void	tap_start(struct ifnet *);
    210 static void	tap_stop(struct ifnet *, int);
    211 static int	tap_init(struct ifnet *);
    212 static int	tap_ioctl(struct ifnet *, u_long, void *);
    213 
    214 /* Internal functions */
    215 static int	tap_lifaddr(struct ifnet *, u_long, struct ifaliasreq *);
    216 static void	tap_softintr(void *);
    217 
    218 /*
    219  * tap is a clonable interface, although it is highly unrealistic for
    220  * an Ethernet device.
    221  *
    222  * Here are the bits needed for a clonable interface.
    223  */
    224 static int	tap_clone_create(struct if_clone *, int);
    225 static int	tap_clone_destroy(struct ifnet *);
    226 
    227 struct if_clone tap_cloners = IF_CLONE_INITIALIZER("tap",
    228 					tap_clone_create,
    229 					tap_clone_destroy);
    230 
    231 /* Helper functions shared by the two cloning code paths */
    232 static struct tap_softc *	tap_clone_creator(int);
    233 int	tap_clone_destroyer(device_t);
    234 
    235 static struct sysctllog *tap_sysctl_clog;
    236 
    237 #ifdef _MODULE
    238 devmajor_t tap_bmajor = -1, tap_cmajor = -1;
    239 #endif
    240 
    241 static u_int tap_count;
    242 
    243 void
    244 tapattach(int n)
    245 {
    246 
    247 	/*
    248 	 * Nothing to do here, initialization is handled by the
    249 	 * module initialization code in tapinit() below).
    250 	 */
    251 }
    252 
    253 static void
    254 tapinit(void)
    255 {
    256 	int error = config_cfattach_attach(tap_cd.cd_name, &tap_ca);
    257 	if (error) {
    258 		aprint_error("%s: unable to register cfattach\n",
    259 		    tap_cd.cd_name);
    260 		(void)config_cfdriver_detach(&tap_cd);
    261 		return;
    262 	}
    263 
    264 	if_clone_attach(&tap_cloners);
    265 	sysctl_tap_setup(&tap_sysctl_clog);
    266 #ifdef _MODULE
    267 	devsw_attach("tap", NULL, &tap_bmajor, &tap_cdevsw, &tap_cmajor);
    268 #endif
    269 }
    270 
    271 static int
    272 tapdetach(void)
    273 {
    274 	int error = 0;
    275 
    276 	if_clone_detach(&tap_cloners);
    277 #ifdef _MODULE
    278 	error = devsw_detach(NULL, &tap_cdevsw);
    279 	if (error != 0)
    280 		goto out2;
    281 #endif
    282 
    283 	if (tap_count != 0) {
    284 		error = EBUSY;
    285 		goto out1;
    286 	}
    287 
    288 	error = config_cfattach_detach(tap_cd.cd_name, &tap_ca);
    289 	if (error != 0)
    290 		goto out1;
    291 
    292 	sysctl_teardown(&tap_sysctl_clog);
    293 
    294 	return 0;
    295 
    296  out1:
    297 #ifdef _MODULE
    298 	devsw_attach("tap", NULL, &tap_bmajor, &tap_cdevsw, &tap_cmajor);
    299 #endif
    300  out2:
    301 	if_clone_attach(&tap_cloners);
    302 
    303 	return error;
    304 }
    305 
    306 /* Pretty much useless for a pseudo-device */
    307 static int
    308 tap_match(device_t parent, cfdata_t cfdata, void *arg)
    309 {
    310 
    311 	return 1;
    312 }
    313 
    314 void
    315 tap_attach(device_t parent, device_t self, void *aux)
    316 {
    317 	struct tap_softc *sc = device_private(self);
    318 	struct ifnet *ifp;
    319 	const struct sysctlnode *node;
    320 	int error;
    321 	uint8_t enaddr[ETHER_ADDR_LEN] =
    322 	    { 0xf2, 0x0b, 0xa4, 0xff, 0xff, 0xff };
    323 	char enaddrstr[3 * ETHER_ADDR_LEN];
    324 
    325 	sc->sc_dev = self;
    326 	sc->sc_sih = NULL;
    327 	getnanotime(&sc->sc_btime);
    328 	sc->sc_atime = sc->sc_mtime = sc->sc_btime;
    329 	sc->sc_flags = 0;
    330 	selinit(&sc->sc_rsel);
    331 
    332 	cv_init(&sc->sc_cv, "tapread");
    333 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NET);
    334 
    335 	if (!pmf_device_register(self, NULL, NULL))
    336 		aprint_error_dev(self, "couldn't establish power handler\n");
    337 
    338 	/*
    339 	 * In order to obtain unique initial Ethernet address on a host,
    340 	 * do some randomisation.  It's not meant for anything but avoiding
    341 	 * hard-coding an address.
    342 	 */
    343 	cprng_fast(&enaddr[3], 3);
    344 
    345 	aprint_verbose_dev(self, "Ethernet address %s\n",
    346 	    ether_snprintf(enaddrstr, sizeof(enaddrstr), enaddr));
    347 
    348 	/*
    349 	 * Why 1000baseT? Why not? You can add more.
    350 	 *
    351 	 * Note that there are 3 steps: init, one or several additions to
    352 	 * list of supported media, and in the end, the selection of one
    353 	 * of them.
    354 	 */
    355 	ifmedia_init(&sc->sc_im, 0, tap_mediachange, tap_mediastatus);
    356 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_1000_T, 0, NULL);
    357 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_1000_T|IFM_FDX, 0, NULL);
    358 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_100_TX, 0, NULL);
    359 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_100_TX|IFM_FDX, 0, NULL);
    360 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_10_T, 0, NULL);
    361 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_10_T|IFM_FDX, 0, NULL);
    362 	ifmedia_add(&sc->sc_im, IFM_ETHER|IFM_AUTO, 0, NULL);
    363 	ifmedia_set(&sc->sc_im, IFM_ETHER|IFM_AUTO);
    364 
    365 	/*
    366 	 * One should note that an interface must do multicast in order
    367 	 * to support IPv6.
    368 	 */
    369 	ifp = &sc->sc_ec.ec_if;
    370 	strcpy(ifp->if_xname, device_xname(self));
    371 	ifp->if_softc	= sc;
    372 	ifp->if_flags	= IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
    373 	ifp->if_extflags = IFEF_NO_LINK_STATE_CHANGE;
    374 #ifdef NET_MPSAFE
    375 	ifp->if_extflags |= IFEF_MPSAFE;
    376 #endif
    377 	ifp->if_ioctl	= tap_ioctl;
    378 	ifp->if_start	= tap_start;
    379 	ifp->if_stop	= tap_stop;
    380 	ifp->if_init	= tap_init;
    381 	IFQ_SET_READY(&ifp->if_snd);
    382 
    383 	sc->sc_ec.ec_capabilities = ETHERCAP_VLAN_MTU | ETHERCAP_JUMBO_MTU;
    384 
    385 	/* Those steps are mandatory for an Ethernet driver. */
    386 	error = if_initialize(ifp);
    387 	if (error != 0) {
    388 		aprint_error_dev(self, "if_initialize failed(%d)\n", error);
    389 		ifmedia_removeall(&sc->sc_im);
    390 		pmf_device_deregister(self);
    391 		mutex_destroy(&sc->sc_lock);
    392 		seldestroy(&sc->sc_rsel);
    393 
    394 		return; /* Error */
    395 	}
    396 	ifp->if_percpuq = if_percpuq_create(ifp);
    397 	ether_ifattach(ifp, enaddr);
    398 	if_register(ifp);
    399 
    400 	/*
    401 	 * Add a sysctl node for that interface.
    402 	 *
    403 	 * The pointer transmitted is not a string, but instead a pointer to
    404 	 * the softc structure, which we can use to build the string value on
    405 	 * the fly in the helper function of the node.  See the comments for
    406 	 * tap_sysctl_handler for details.
    407 	 *
    408 	 * Usually sysctl_createv is called with CTL_CREATE as the before-last
    409 	 * component.  However, we can allocate a number ourselves, as we are
    410 	 * the only consumer of the net.link.<iface> node.  In this case, the
    411 	 * unit number is conveniently used to number the node.  CTL_CREATE
    412 	 * would just work, too.
    413 	 */
    414 	if ((error = sysctl_createv(NULL, 0, NULL,
    415 	    &node, CTLFLAG_READWRITE,
    416 	    CTLTYPE_STRING, device_xname(self), NULL,
    417 	    tap_sysctl_handler, 0, (void *)sc, 18,
    418 	    CTL_NET, AF_LINK, tap_node, device_unit(sc->sc_dev),
    419 	    CTL_EOL)) != 0)
    420 		aprint_error_dev(self,
    421 		    "sysctl_createv returned %d, ignoring\n", error);
    422 }
    423 
    424 /*
    425  * When detaching, we do the inverse of what is done in the attach
    426  * routine, in reversed order.
    427  */
    428 static int
    429 tap_detach(device_t self, int flags)
    430 {
    431 	struct tap_softc *sc = device_private(self);
    432 	struct ifnet *ifp = &sc->sc_ec.ec_if;
    433 	int error;
    434 
    435 	sc->sc_flags |= TAP_GOING;
    436 	tap_stop(ifp, 1);
    437 	if_down(ifp);
    438 
    439 	if (sc->sc_sih != NULL) {
    440 		softint_disestablish(sc->sc_sih);
    441 		sc->sc_sih = NULL;
    442 	}
    443 
    444 	/*
    445 	 * Destroying a single leaf is a very straightforward operation using
    446 	 * sysctl_destroyv.  One should be sure to always end the path with
    447 	 * CTL_EOL.
    448 	 */
    449 	if ((error = sysctl_destroyv(NULL, CTL_NET, AF_LINK, tap_node,
    450 	    device_unit(sc->sc_dev), CTL_EOL)) != 0)
    451 		aprint_error_dev(self,
    452 		    "sysctl_destroyv returned %d, ignoring\n", error);
    453 	ether_ifdetach(ifp);
    454 	if_detach(ifp);
    455 	ifmedia_removeall(&sc->sc_im);
    456 	seldestroy(&sc->sc_rsel);
    457 	mutex_destroy(&sc->sc_lock);
    458 	cv_destroy(&sc->sc_cv);
    459 
    460 	pmf_device_deregister(self);
    461 
    462 	return 0;
    463 }
    464 
    465 /*
    466  * This function is called by the ifmedia layer to notify the driver
    467  * that the user requested a media change.  A real driver would
    468  * reconfigure the hardware.
    469  */
    470 static int
    471 tap_mediachange(struct ifnet *ifp)
    472 {
    473 	return 0;
    474 }
    475 
    476 /*
    477  * Here the user asks for the currently used media.
    478  */
    479 static void
    480 tap_mediastatus(struct ifnet *ifp, struct ifmediareq *imr)
    481 {
    482 	struct tap_softc *sc = (struct tap_softc *)ifp->if_softc;
    483 	imr->ifm_active = sc->sc_im.ifm_cur->ifm_media;
    484 }
    485 
    486 /*
    487  * This is the function where we SEND packets.
    488  *
    489  * There is no 'receive' equivalent.  A typical driver will get
    490  * interrupts from the hardware, and from there will inject new packets
    491  * into the network stack.
    492  *
    493  * Once handled, a packet must be freed.  A real driver might not be able
    494  * to fit all the pending packets into the hardware, and is allowed to
    495  * return before having sent all the packets.  It should then use the
    496  * if_flags flag IFF_OACTIVE to notify the upper layer.
    497  *
    498  * There are also other flags one should check, such as IFF_PAUSE.
    499  *
    500  * It is our duty to make packets available to BPF listeners.
    501  *
    502  * You should be aware that this function is called by the Ethernet layer
    503  * at splnet().
    504  *
    505  * When the device is opened, we have to pass the packet(s) to the
    506  * userland.  For that we stay in OACTIVE mode while the userland gets
    507  * the packets, and we send a signal to the processes waiting to read.
    508  *
    509  * wakeup(sc) is the counterpart to the tsleep call in
    510  * tap_dev_read, while selnotify() is used for kevent(2) and
    511  * poll(2) (which includes select(2)) listeners.
    512  */
    513 static void
    514 tap_start(struct ifnet *ifp)
    515 {
    516 	struct tap_softc *sc = (struct tap_softc *)ifp->if_softc;
    517 	struct mbuf *m0;
    518 
    519 	mutex_enter(&sc->sc_lock);
    520 	if ((sc->sc_flags & TAP_INUSE) == 0) {
    521 		/* Simply drop packets */
    522 		for(;;) {
    523 			IFQ_DEQUEUE(&ifp->if_snd, m0);
    524 			if (m0 == NULL)
    525 				goto done;
    526 
    527 			ifp->if_opackets++;
    528 			bpf_mtap(ifp, m0, BPF_D_OUT);
    529 
    530 			m_freem(m0);
    531 		}
    532 	} else if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
    533 		ifp->if_flags |= IFF_OACTIVE;
    534 		cv_broadcast(&sc->sc_cv);
    535 		selnotify(&sc->sc_rsel, 0, 1);
    536 		if (sc->sc_flags & TAP_ASYNCIO)
    537 			softint_schedule(sc->sc_sih);
    538 	}
    539 done:
    540 	mutex_exit(&sc->sc_lock);
    541 }
    542 
    543 static void
    544 tap_softintr(void *cookie)
    545 {
    546 	struct tap_softc *sc;
    547 	struct ifnet *ifp;
    548 	int a, b;
    549 
    550 	sc = cookie;
    551 
    552 	if (sc->sc_flags & TAP_ASYNCIO) {
    553 		ifp = &sc->sc_ec.ec_if;
    554 		if (ifp->if_flags & IFF_RUNNING) {
    555 			a = POLL_IN;
    556 			b = POLLIN|POLLRDNORM;
    557 		} else {
    558 			a = POLL_HUP;
    559 			b = 0;
    560 		}
    561 		fownsignal(sc->sc_pgid, SIGIO, a, b, NULL);
    562 	}
    563 }
    564 
    565 /*
    566  * A typical driver will only contain the following handlers for
    567  * ioctl calls, except SIOCSIFPHYADDR.
    568  * The latter is a hack I used to set the Ethernet address of the
    569  * faked device.
    570  *
    571  * Note that both ifmedia_ioctl() and ether_ioctl() have to be
    572  * called under splnet().
    573  */
    574 static int
    575 tap_ioctl(struct ifnet *ifp, u_long cmd, void *data)
    576 {
    577 	struct tap_softc *sc = (struct tap_softc *)ifp->if_softc;
    578 	struct ifreq *ifr = (struct ifreq *)data;
    579 	int s, error;
    580 
    581 	s = splnet();
    582 
    583 	switch (cmd) {
    584 #ifdef OSIOCSIFMEDIA
    585 	case OSIOCSIFMEDIA:
    586 #endif
    587 	case SIOCSIFMEDIA:
    588 	case SIOCGIFMEDIA:
    589 		error = ifmedia_ioctl(ifp, ifr, &sc->sc_im, cmd);
    590 		break;
    591 	case SIOCSIFPHYADDR:
    592 		error = tap_lifaddr(ifp, cmd, (struct ifaliasreq *)data);
    593 		break;
    594 	default:
    595 		error = ether_ioctl(ifp, cmd, data);
    596 		if (error == ENETRESET)
    597 			error = 0;
    598 		break;
    599 	}
    600 
    601 	splx(s);
    602 
    603 	return error;
    604 }
    605 
    606 /*
    607  * Helper function to set Ethernet address.  This has been replaced by
    608  * the generic SIOCALIFADDR ioctl on a PF_LINK socket.
    609  */
    610 static int
    611 tap_lifaddr(struct ifnet *ifp, u_long cmd, struct ifaliasreq *ifra)
    612 {
    613 	const struct sockaddr *sa = &ifra->ifra_addr;
    614 
    615 	if (sa->sa_family != AF_LINK)
    616 		return EINVAL;
    617 
    618 	if_set_sadl(ifp, sa->sa_data, ETHER_ADDR_LEN, false);
    619 
    620 	return 0;
    621 }
    622 
    623 /*
    624  * _init() would typically be called when an interface goes up,
    625  * meaning it should configure itself into the state in which it
    626  * can send packets.
    627  */
    628 static int
    629 tap_init(struct ifnet *ifp)
    630 {
    631 	ifp->if_flags |= IFF_RUNNING;
    632 
    633 	tap_start(ifp);
    634 
    635 	return 0;
    636 }
    637 
    638 /*
    639  * _stop() is called when an interface goes down.  It is our
    640  * responsability to validate that state by clearing the
    641  * IFF_RUNNING flag.
    642  *
    643  * We have to wake up all the sleeping processes to have the pending
    644  * read requests cancelled.
    645  */
    646 static void
    647 tap_stop(struct ifnet *ifp, int disable)
    648 {
    649 	struct tap_softc *sc = (struct tap_softc *)ifp->if_softc;
    650 
    651 	mutex_enter(&sc->sc_lock);
    652 	ifp->if_flags &= ~IFF_RUNNING;
    653 	cv_broadcast(&sc->sc_cv);
    654 	selnotify(&sc->sc_rsel, 0, 1);
    655 	if (sc->sc_flags & TAP_ASYNCIO)
    656 		softint_schedule(sc->sc_sih);
    657 	mutex_exit(&sc->sc_lock);
    658 }
    659 
    660 /*
    661  * The 'create' command of ifconfig can be used to create
    662  * any numbered instance of a given device.  Thus we have to
    663  * make sure we have enough room in cd_devs to create the
    664  * user-specified instance.  config_attach_pseudo will do this
    665  * for us.
    666  */
    667 static int
    668 tap_clone_create(struct if_clone *ifc, int unit)
    669 {
    670 	if (tap_clone_creator(unit) == NULL) {
    671 		aprint_error("%s%d: unable to attach an instance\n",
    672 		    tap_cd.cd_name, unit);
    673 		return ENXIO;
    674 	}
    675 	atomic_inc_uint(&tap_count);
    676 	return 0;
    677 }
    678 
    679 /*
    680  * tap(4) can be cloned by two ways:
    681  *   using 'ifconfig tap0 create', which will use the network
    682  *     interface cloning API, and call tap_clone_create above.
    683  *   opening the cloning device node, whose minor number is TAP_CLONER.
    684  *     See below for an explanation on how this part work.
    685  */
    686 static struct tap_softc *
    687 tap_clone_creator(int unit)
    688 {
    689 	cfdata_t cf;
    690 
    691 	cf = kmem_alloc(sizeof(*cf), KM_SLEEP);
    692 	cf->cf_name = tap_cd.cd_name;
    693 	cf->cf_atname = tap_ca.ca_name;
    694 	if (unit == -1) {
    695 		/* let autoconf find the first free one */
    696 		cf->cf_unit = 0;
    697 		cf->cf_fstate = FSTATE_STAR;
    698 	} else {
    699 		cf->cf_unit = unit;
    700 		cf->cf_fstate = FSTATE_NOTFOUND;
    701 	}
    702 
    703 	return device_private(config_attach_pseudo(cf));
    704 }
    705 
    706 /*
    707  * The clean design of if_clone and autoconf(9) makes that part
    708  * really straightforward.  The second argument of config_detach
    709  * means neither QUIET nor FORCED.
    710  */
    711 static int
    712 tap_clone_destroy(struct ifnet *ifp)
    713 {
    714 	struct tap_softc *sc = ifp->if_softc;
    715 	int error = tap_clone_destroyer(sc->sc_dev);
    716 
    717 	if (error == 0)
    718 		atomic_dec_uint(&tap_count);
    719 	return error;
    720 }
    721 
    722 int
    723 tap_clone_destroyer(device_t dev)
    724 {
    725 	cfdata_t cf = device_cfdata(dev);
    726 	int error;
    727 
    728 	if ((error = config_detach(dev, 0)) != 0)
    729 		aprint_error_dev(dev, "unable to detach instance\n");
    730 	kmem_free(cf, sizeof(*cf));
    731 
    732 	return error;
    733 }
    734 
    735 /*
    736  * tap(4) is a bit of an hybrid device.  It can be used in two different
    737  * ways:
    738  *  1. ifconfig tapN create, then use /dev/tapN to read/write off it.
    739  *  2. open /dev/tap, get a new interface created and read/write off it.
    740  *     That interface is destroyed when the process that had it created exits.
    741  *
    742  * The first way is managed by the cdevsw structure, and you access interfaces
    743  * through a (major, minor) mapping:  tap4 is obtained by the minor number
    744  * 4.  The entry points for the cdevsw interface are prefixed by tap_cdev_.
    745  *
    746  * The second way is the so-called "cloning" device.  It's a special minor
    747  * number (chosen as the maximal number, to allow as much tap devices as
    748  * possible).  The user first opens the cloner (e.g., /dev/tap), and that
    749  * call ends in tap_cdev_open.  The actual place where it is handled is
    750  * tap_dev_cloner.
    751  *
    752  * An tap device cannot be opened more than once at a time, so the cdevsw
    753  * part of open() does nothing but noting that the interface is being used and
    754  * hence ready to actually handle packets.
    755  */
    756 
    757 static int
    758 tap_cdev_open(dev_t dev, int flags, int fmt, struct lwp *l)
    759 {
    760 	struct tap_softc *sc;
    761 
    762 	if (minor(dev) == TAP_CLONER)
    763 		return tap_dev_cloner(l);
    764 
    765 	sc = device_lookup_private(&tap_cd, minor(dev));
    766 	if (sc == NULL)
    767 		return ENXIO;
    768 
    769 	/* The device can only be opened once */
    770 	if (sc->sc_flags & TAP_INUSE)
    771 		return EBUSY;
    772 	sc->sc_flags |= TAP_INUSE;
    773 	return 0;
    774 }
    775 
    776 /*
    777  * There are several kinds of cloning devices, and the most simple is the one
    778  * tap(4) uses.  What it does is change the file descriptor with a new one,
    779  * with its own fileops structure (which maps to the various read, write,
    780  * ioctl functions).  It starts allocating a new file descriptor with falloc,
    781  * then actually creates the new tap devices.
    782  *
    783  * Once those two steps are successful, we can re-wire the existing file
    784  * descriptor to its new self.  This is done with fdclone():  it fills the fp
    785  * structure as needed (notably f_devunit gets filled with the fifth parameter
    786  * passed, the unit of the tap device which will allows us identifying the
    787  * device later), and returns EMOVEFD.
    788  *
    789  * That magic value is interpreted by sys_open() which then replaces the
    790  * current file descriptor by the new one (through a magic member of struct
    791  * lwp, l_dupfd).
    792  *
    793  * The tap device is flagged as being busy since it otherwise could be
    794  * externally accessed through the corresponding device node with the cdevsw
    795  * interface.
    796  */
    797 
    798 static int
    799 tap_dev_cloner(struct lwp *l)
    800 {
    801 	struct tap_softc *sc;
    802 	file_t *fp;
    803 	int error, fd;
    804 
    805 	if ((error = fd_allocfile(&fp, &fd)) != 0)
    806 		return error;
    807 
    808 	if ((sc = tap_clone_creator(-1)) == NULL) {
    809 		fd_abort(curproc, fp, fd);
    810 		return ENXIO;
    811 	}
    812 
    813 	sc->sc_flags |= TAP_INUSE;
    814 
    815 	return fd_clone(fp, fd, FREAD|FWRITE, &tap_fileops,
    816 	    (void *)(intptr_t)device_unit(sc->sc_dev));
    817 }
    818 
    819 /*
    820  * While all other operations (read, write, ioctl, poll and kqfilter) are
    821  * really the same whether we are in cdevsw or fileops mode, the close()
    822  * function is slightly different in the two cases.
    823  *
    824  * As for the other, the core of it is shared in tap_dev_close.  What
    825  * it does is sufficient for the cdevsw interface, but the cloning interface
    826  * needs another thing:  the interface is destroyed when the processes that
    827  * created it closes it.
    828  */
    829 static int
    830 tap_cdev_close(dev_t dev, int flags, int fmt,
    831     struct lwp *l)
    832 {
    833 	struct tap_softc *sc =
    834 	    device_lookup_private(&tap_cd, minor(dev));
    835 
    836 	if (sc == NULL)
    837 		return ENXIO;
    838 
    839 	return tap_dev_close(sc);
    840 }
    841 
    842 /*
    843  * It might happen that the administrator used ifconfig to externally destroy
    844  * the interface.  In that case, tap_fops_close will be called while
    845  * tap_detach is already happening.  If we called it again from here, we
    846  * would dead lock.  TAP_GOING ensures that this situation doesn't happen.
    847  */
    848 static int
    849 tap_fops_close(file_t *fp)
    850 {
    851 	int unit = fp->f_devunit;
    852 	struct tap_softc *sc;
    853 	int error;
    854 
    855 	sc = device_lookup_private(&tap_cd, unit);
    856 	if (sc == NULL)
    857 		return ENXIO;
    858 
    859 	/* tap_dev_close currently always succeeds, but it might not
    860 	 * always be the case. */
    861 	KERNEL_LOCK(1, NULL);
    862 	if ((error = tap_dev_close(sc)) != 0) {
    863 		KERNEL_UNLOCK_ONE(NULL);
    864 		return error;
    865 	}
    866 
    867 	/* Destroy the device now that it is no longer useful,
    868 	 * unless it's already being destroyed. */
    869 	if ((sc->sc_flags & TAP_GOING) != 0) {
    870 		KERNEL_UNLOCK_ONE(NULL);
    871 		return 0;
    872 	}
    873 
    874 	error = tap_clone_destroyer(sc->sc_dev);
    875 	KERNEL_UNLOCK_ONE(NULL);
    876 	return error;
    877 }
    878 
    879 static int
    880 tap_dev_close(struct tap_softc *sc)
    881 {
    882 	struct ifnet *ifp;
    883 	int s;
    884 
    885 	s = splnet();
    886 	/* Let tap_start handle packets again */
    887 	ifp = &sc->sc_ec.ec_if;
    888 	ifp->if_flags &= ~IFF_OACTIVE;
    889 
    890 	/* Purge output queue */
    891 	if (!(IFQ_IS_EMPTY(&ifp->if_snd))) {
    892 		struct mbuf *m;
    893 
    894 		for (;;) {
    895 			IFQ_DEQUEUE(&ifp->if_snd, m);
    896 			if (m == NULL)
    897 				break;
    898 
    899 			ifp->if_opackets++;
    900 			bpf_mtap(ifp, m, BPF_D_OUT);
    901 			m_freem(m);
    902 		}
    903 	}
    904 	splx(s);
    905 
    906 	if (sc->sc_sih != NULL) {
    907 		softint_disestablish(sc->sc_sih);
    908 		sc->sc_sih = NULL;
    909 	}
    910 	sc->sc_flags &= ~(TAP_INUSE | TAP_ASYNCIO);
    911 
    912 	return 0;
    913 }
    914 
    915 static int
    916 tap_cdev_read(dev_t dev, struct uio *uio, int flags)
    917 {
    918 	return tap_dev_read(minor(dev), uio, flags);
    919 }
    920 
    921 static int
    922 tap_fops_read(file_t *fp, off_t *offp, struct uio *uio,
    923     kauth_cred_t cred, int flags)
    924 {
    925 	int error;
    926 
    927 	KERNEL_LOCK(1, NULL);
    928 	error = tap_dev_read(fp->f_devunit, uio, flags);
    929 	KERNEL_UNLOCK_ONE(NULL);
    930 	return error;
    931 }
    932 
    933 static int
    934 tap_dev_read(int unit, struct uio *uio, int flags)
    935 {
    936 	struct tap_softc *sc = device_lookup_private(&tap_cd, unit);
    937 	struct ifnet *ifp;
    938 	struct mbuf *m, *n;
    939 	int error = 0;
    940 
    941 	if (sc == NULL)
    942 		return ENXIO;
    943 
    944 	getnanotime(&sc->sc_atime);
    945 
    946 	ifp = &sc->sc_ec.ec_if;
    947 	if ((ifp->if_flags & IFF_UP) == 0)
    948 		return EHOSTDOWN;
    949 
    950 	/*
    951 	 * In the TAP_NBIO case, we have to make sure we won't be sleeping
    952 	 */
    953 	if ((sc->sc_flags & TAP_NBIO) != 0) {
    954 		if (!mutex_tryenter(&sc->sc_lock))
    955 			return EWOULDBLOCK;
    956 	} else {
    957 		mutex_enter(&sc->sc_lock);
    958 	}
    959 
    960 	if (IFQ_IS_EMPTY(&ifp->if_snd)) {
    961 		ifp->if_flags &= ~IFF_OACTIVE;
    962 		if (sc->sc_flags & TAP_NBIO)
    963 			error = EWOULDBLOCK;
    964 		else
    965 			error = cv_wait_sig(&sc->sc_cv, &sc->sc_lock);
    966 
    967 		if (error != 0) {
    968 			mutex_exit(&sc->sc_lock);
    969 			return error;
    970 		}
    971 		/* The device might have been downed */
    972 		if ((ifp->if_flags & IFF_UP) == 0) {
    973 			mutex_exit(&sc->sc_lock);
    974 			return EHOSTDOWN;
    975 		}
    976 	}
    977 
    978 	IFQ_DEQUEUE(&ifp->if_snd, m);
    979 	mutex_exit(&sc->sc_lock);
    980 
    981 	ifp->if_flags &= ~IFF_OACTIVE;
    982 	if (m == NULL) {
    983 		error = 0;
    984 		goto out;
    985 	}
    986 
    987 	ifp->if_opackets++;
    988 	bpf_mtap(ifp, m, BPF_D_OUT);
    989 
    990 	/*
    991 	 * One read is one packet.
    992 	 */
    993 	do {
    994 		error = uiomove(mtod(m, void *),
    995 		    uimin(m->m_len, uio->uio_resid), uio);
    996 		m = n = m_free(m);
    997 	} while (m != NULL && uio->uio_resid > 0 && error == 0);
    998 
    999 	if (m != NULL)
   1000 		m_freem(m);
   1001 
   1002 out:
   1003 	return error;
   1004 }
   1005 
   1006 static int
   1007 tap_fops_stat(file_t *fp, struct stat *st)
   1008 {
   1009 	int error = 0;
   1010 	struct tap_softc *sc;
   1011 	int unit = fp->f_devunit;
   1012 
   1013 	(void)memset(st, 0, sizeof(*st));
   1014 
   1015 	KERNEL_LOCK(1, NULL);
   1016 	sc = device_lookup_private(&tap_cd, unit);
   1017 	if (sc == NULL) {
   1018 		error = ENXIO;
   1019 		goto out;
   1020 	}
   1021 
   1022 	st->st_dev = makedev(cdevsw_lookup_major(&tap_cdevsw), unit);
   1023 	st->st_atimespec = sc->sc_atime;
   1024 	st->st_mtimespec = sc->sc_mtime;
   1025 	st->st_ctimespec = st->st_birthtimespec = sc->sc_btime;
   1026 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   1027 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   1028 out:
   1029 	KERNEL_UNLOCK_ONE(NULL);
   1030 	return error;
   1031 }
   1032 
   1033 static int
   1034 tap_cdev_write(dev_t dev, struct uio *uio, int flags)
   1035 {
   1036 	return tap_dev_write(minor(dev), uio, flags);
   1037 }
   1038 
   1039 static int
   1040 tap_fops_write(file_t *fp, off_t *offp, struct uio *uio,
   1041     kauth_cred_t cred, int flags)
   1042 {
   1043 	int error;
   1044 
   1045 	KERNEL_LOCK(1, NULL);
   1046 	error = tap_dev_write(fp->f_devunit, uio, flags);
   1047 	KERNEL_UNLOCK_ONE(NULL);
   1048 	return error;
   1049 }
   1050 
   1051 static int
   1052 tap_dev_write(int unit, struct uio *uio, int flags)
   1053 {
   1054 	struct tap_softc *sc =
   1055 	    device_lookup_private(&tap_cd, unit);
   1056 	struct ifnet *ifp;
   1057 	struct mbuf *m, **mp;
   1058 	int error = 0;
   1059 
   1060 	if (sc == NULL)
   1061 		return ENXIO;
   1062 
   1063 	getnanotime(&sc->sc_mtime);
   1064 	ifp = &sc->sc_ec.ec_if;
   1065 
   1066 	/* One write, one packet, that's the rule */
   1067 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1068 	if (m == NULL) {
   1069 		ifp->if_ierrors++;
   1070 		return ENOBUFS;
   1071 	}
   1072 	m->m_pkthdr.len = uio->uio_resid;
   1073 
   1074 	mp = &m;
   1075 	while (error == 0 && uio->uio_resid > 0) {
   1076 		if (*mp != m) {
   1077 			MGET(*mp, M_DONTWAIT, MT_DATA);
   1078 			if (*mp == NULL) {
   1079 				error = ENOBUFS;
   1080 				break;
   1081 			}
   1082 		}
   1083 		(*mp)->m_len = uimin(MHLEN, uio->uio_resid);
   1084 		error = uiomove(mtod(*mp, void *), (*mp)->m_len, uio);
   1085 		mp = &(*mp)->m_next;
   1086 	}
   1087 	if (error) {
   1088 		ifp->if_ierrors++;
   1089 		m_freem(m);
   1090 		return error;
   1091 	}
   1092 
   1093 	m_set_rcvif(m, ifp);
   1094 
   1095 	if_percpuq_enqueue(ifp->if_percpuq, m);
   1096 
   1097 	return 0;
   1098 }
   1099 
   1100 static int
   1101 tap_cdev_ioctl(dev_t dev, u_long cmd, void *data, int flags,
   1102     struct lwp *l)
   1103 {
   1104 	return tap_dev_ioctl(minor(dev), cmd, data, l);
   1105 }
   1106 
   1107 static int
   1108 tap_fops_ioctl(file_t *fp, u_long cmd, void *data)
   1109 {
   1110 	return tap_dev_ioctl(fp->f_devunit, cmd, data, curlwp);
   1111 }
   1112 
   1113 static int
   1114 tap_dev_ioctl(int unit, u_long cmd, void *data, struct lwp *l)
   1115 {
   1116 	struct tap_softc *sc = device_lookup_private(&tap_cd, unit);
   1117 
   1118 	if (sc == NULL)
   1119 		return ENXIO;
   1120 
   1121 	switch (cmd) {
   1122 	case FIONREAD:
   1123 		{
   1124 			struct ifnet *ifp = &sc->sc_ec.ec_if;
   1125 			struct mbuf *m;
   1126 			int s;
   1127 
   1128 			s = splnet();
   1129 			IFQ_POLL(&ifp->if_snd, m);
   1130 
   1131 			if (m == NULL)
   1132 				*(int *)data = 0;
   1133 			else
   1134 				*(int *)data = m->m_pkthdr.len;
   1135 			splx(s);
   1136 			return 0;
   1137 		}
   1138 	case TIOCSPGRP:
   1139 	case FIOSETOWN:
   1140 		return fsetown(&sc->sc_pgid, cmd, data);
   1141 	case TIOCGPGRP:
   1142 	case FIOGETOWN:
   1143 		return fgetown(sc->sc_pgid, cmd, data);
   1144 	case FIOASYNC:
   1145 		if (*(int *)data) {
   1146 			if (sc->sc_sih == NULL) {
   1147 				sc->sc_sih = softint_establish(SOFTINT_CLOCK,
   1148 				    tap_softintr, sc);
   1149 				if (sc->sc_sih == NULL)
   1150 					return EBUSY; /* XXX */
   1151 			}
   1152 			sc->sc_flags |= TAP_ASYNCIO;
   1153 		} else {
   1154 			sc->sc_flags &= ~TAP_ASYNCIO;
   1155 			if (sc->sc_sih != NULL) {
   1156 				softint_disestablish(sc->sc_sih);
   1157 				sc->sc_sih = NULL;
   1158 			}
   1159 		}
   1160 		return 0;
   1161 	case FIONBIO:
   1162 		if (*(int *)data)
   1163 			sc->sc_flags |= TAP_NBIO;
   1164 		else
   1165 			sc->sc_flags &= ~TAP_NBIO;
   1166 		return 0;
   1167 #ifdef OTAPGIFNAME
   1168 	case OTAPGIFNAME:
   1169 #endif
   1170 	case TAPGIFNAME:
   1171 		{
   1172 			struct ifreq *ifr = (struct ifreq *)data;
   1173 			struct ifnet *ifp = &sc->sc_ec.ec_if;
   1174 
   1175 			strlcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
   1176 			return 0;
   1177 		}
   1178 	default:
   1179 		return ENOTTY;
   1180 	}
   1181 }
   1182 
   1183 static int
   1184 tap_cdev_poll(dev_t dev, int events, struct lwp *l)
   1185 {
   1186 	return tap_dev_poll(minor(dev), events, l);
   1187 }
   1188 
   1189 static int
   1190 tap_fops_poll(file_t *fp, int events)
   1191 {
   1192 	return tap_dev_poll(fp->f_devunit, events, curlwp);
   1193 }
   1194 
   1195 static int
   1196 tap_dev_poll(int unit, int events, struct lwp *l)
   1197 {
   1198 	struct tap_softc *sc =
   1199 	    device_lookup_private(&tap_cd, unit);
   1200 	int revents = 0;
   1201 
   1202 	if (sc == NULL)
   1203 		return POLLERR;
   1204 
   1205 	if (events & (POLLIN|POLLRDNORM)) {
   1206 		struct ifnet *ifp = &sc->sc_ec.ec_if;
   1207 		struct mbuf *m;
   1208 		int s;
   1209 
   1210 		s = splnet();
   1211 		IFQ_POLL(&ifp->if_snd, m);
   1212 
   1213 		if (m != NULL)
   1214 			revents |= events & (POLLIN|POLLRDNORM);
   1215 		else {
   1216 			mutex_spin_enter(&sc->sc_lock);
   1217 			selrecord(l, &sc->sc_rsel);
   1218 			mutex_spin_exit(&sc->sc_lock);
   1219 		}
   1220 		splx(s);
   1221 	}
   1222 	revents |= events & (POLLOUT|POLLWRNORM);
   1223 
   1224 	return revents;
   1225 }
   1226 
   1227 static struct filterops tap_read_filterops = { 1, NULL, tap_kqdetach,
   1228 	tap_kqread };
   1229 static struct filterops tap_seltrue_filterops = { 1, NULL, tap_kqdetach,
   1230 	filt_seltrue };
   1231 
   1232 static int
   1233 tap_cdev_kqfilter(dev_t dev, struct knote *kn)
   1234 {
   1235 	return tap_dev_kqfilter(minor(dev), kn);
   1236 }
   1237 
   1238 static int
   1239 tap_fops_kqfilter(file_t *fp, struct knote *kn)
   1240 {
   1241 	return tap_dev_kqfilter(fp->f_devunit, kn);
   1242 }
   1243 
   1244 static int
   1245 tap_dev_kqfilter(int unit, struct knote *kn)
   1246 {
   1247 	struct tap_softc *sc =
   1248 	    device_lookup_private(&tap_cd, unit);
   1249 
   1250 	if (sc == NULL)
   1251 		return ENXIO;
   1252 
   1253 	KERNEL_LOCK(1, NULL);
   1254 	switch(kn->kn_filter) {
   1255 	case EVFILT_READ:
   1256 		kn->kn_fop = &tap_read_filterops;
   1257 		break;
   1258 	case EVFILT_WRITE:
   1259 		kn->kn_fop = &tap_seltrue_filterops;
   1260 		break;
   1261 	default:
   1262 		KERNEL_UNLOCK_ONE(NULL);
   1263 		return EINVAL;
   1264 	}
   1265 
   1266 	kn->kn_hook = sc;
   1267 	mutex_spin_enter(&sc->sc_lock);
   1268 	SLIST_INSERT_HEAD(&sc->sc_rsel.sel_klist, kn, kn_selnext);
   1269 	mutex_spin_exit(&sc->sc_lock);
   1270 	KERNEL_UNLOCK_ONE(NULL);
   1271 	return 0;
   1272 }
   1273 
   1274 static void
   1275 tap_kqdetach(struct knote *kn)
   1276 {
   1277 	struct tap_softc *sc = (struct tap_softc *)kn->kn_hook;
   1278 
   1279 	KERNEL_LOCK(1, NULL);
   1280 	mutex_spin_enter(&sc->sc_lock);
   1281 	SLIST_REMOVE(&sc->sc_rsel.sel_klist, kn, knote, kn_selnext);
   1282 	mutex_spin_exit(&sc->sc_lock);
   1283 	KERNEL_UNLOCK_ONE(NULL);
   1284 }
   1285 
   1286 static int
   1287 tap_kqread(struct knote *kn, long hint)
   1288 {
   1289 	struct tap_softc *sc = (struct tap_softc *)kn->kn_hook;
   1290 	struct ifnet *ifp = &sc->sc_ec.ec_if;
   1291 	struct mbuf *m;
   1292 	int s, rv;
   1293 
   1294 	KERNEL_LOCK(1, NULL);
   1295 	s = splnet();
   1296 	IFQ_POLL(&ifp->if_snd, m);
   1297 
   1298 	if (m == NULL)
   1299 		kn->kn_data = 0;
   1300 	else
   1301 		kn->kn_data = m->m_pkthdr.len;
   1302 	splx(s);
   1303 	rv = (kn->kn_data != 0 ? 1 : 0);
   1304 	KERNEL_UNLOCK_ONE(NULL);
   1305 	return rv;
   1306 }
   1307 
   1308 /*
   1309  * sysctl management routines
   1310  * You can set the address of an interface through:
   1311  * net.link.tap.tap<number>
   1312  *
   1313  * Note the consistent use of tap_log in order to use
   1314  * sysctl_teardown at unload time.
   1315  *
   1316  * In the kernel you will find a lot of SYSCTL_SETUP blocks.  Those
   1317  * blocks register a function in a special section of the kernel
   1318  * (called a link set) which is used at init_sysctl() time to cycle
   1319  * through all those functions to create the kernel's sysctl tree.
   1320  *
   1321  * It is not possible to use link sets in a module, so the
   1322  * easiest is to simply call our own setup routine at load time.
   1323  *
   1324  * In the SYSCTL_SETUP blocks you find in the kernel, nodes have the
   1325  * CTLFLAG_PERMANENT flag, meaning they cannot be removed.  Once the
   1326  * whole kernel sysctl tree is built, it is not possible to add any
   1327  * permanent node.
   1328  *
   1329  * It should be noted that we're not saving the sysctlnode pointer
   1330  * we are returned when creating the "tap" node.  That structure
   1331  * cannot be trusted once out of the calling function, as it might
   1332  * get reused.  So we just save the MIB number, and always give the
   1333  * full path starting from the root for later calls to sysctl_createv
   1334  * and sysctl_destroyv.
   1335  */
   1336 static void
   1337 sysctl_tap_setup(struct sysctllog **clog)
   1338 {
   1339 	const struct sysctlnode *node;
   1340 	int error = 0;
   1341 
   1342 	if ((error = sysctl_createv(clog, 0, NULL, NULL,
   1343 	    CTLFLAG_PERMANENT,
   1344 	    CTLTYPE_NODE, "link", NULL,
   1345 	    NULL, 0, NULL, 0,
   1346 	    CTL_NET, AF_LINK, CTL_EOL)) != 0)
   1347 		return;
   1348 
   1349 	/*
   1350 	 * The first four parameters of sysctl_createv are for management.
   1351 	 *
   1352 	 * The four that follows, here starting with a '0' for the flags,
   1353 	 * describe the node.
   1354 	 *
   1355 	 * The next series of four set its value, through various possible
   1356 	 * means.
   1357 	 *
   1358 	 * Last but not least, the path to the node is described.  That path
   1359 	 * is relative to the given root (third argument).  Here we're
   1360 	 * starting from the root.
   1361 	 */
   1362 	if ((error = sysctl_createv(clog, 0, NULL, &node,
   1363 	    CTLFLAG_PERMANENT,
   1364 	    CTLTYPE_NODE, "tap", NULL,
   1365 	    NULL, 0, NULL, 0,
   1366 	    CTL_NET, AF_LINK, CTL_CREATE, CTL_EOL)) != 0)
   1367 		return;
   1368 	tap_node = node->sysctl_num;
   1369 }
   1370 
   1371 /*
   1372  * The helper functions make Andrew Brown's interface really
   1373  * shine.  It makes possible to create value on the fly whether
   1374  * the sysctl value is read or written.
   1375  *
   1376  * As shown as an example in the man page, the first step is to
   1377  * create a copy of the node to have sysctl_lookup work on it.
   1378  *
   1379  * Here, we have more work to do than just a copy, since we have
   1380  * to create the string.  The first step is to collect the actual
   1381  * value of the node, which is a convenient pointer to the softc
   1382  * of the interface.  From there we create the string and use it
   1383  * as the value, but only for the *copy* of the node.
   1384  *
   1385  * Then we let sysctl_lookup do the magic, which consists in
   1386  * setting oldp and newp as required by the operation.  When the
   1387  * value is read, that means that the string will be copied to
   1388  * the user, and when it is written, the new value will be copied
   1389  * over in the addr array.
   1390  *
   1391  * If newp is NULL, the user was reading the value, so we don't
   1392  * have anything else to do.  If a new value was written, we
   1393  * have to check it.
   1394  *
   1395  * If it is incorrect, we can return an error and leave 'node' as
   1396  * it is:  since it is a copy of the actual node, the change will
   1397  * be forgotten.
   1398  *
   1399  * Upon a correct input, we commit the change to the ifnet
   1400  * structure of our interface.
   1401  */
   1402 static int
   1403 tap_sysctl_handler(SYSCTLFN_ARGS)
   1404 {
   1405 	struct sysctlnode node;
   1406 	struct tap_softc *sc;
   1407 	struct ifnet *ifp;
   1408 	int error;
   1409 	size_t len;
   1410 	char addr[3 * ETHER_ADDR_LEN];
   1411 	uint8_t enaddr[ETHER_ADDR_LEN];
   1412 
   1413 	node = *rnode;
   1414 	sc = node.sysctl_data;
   1415 	ifp = &sc->sc_ec.ec_if;
   1416 	(void)ether_snprintf(addr, sizeof(addr), CLLADDR(ifp->if_sadl));
   1417 	node.sysctl_data = addr;
   1418 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   1419 	if (error || newp == NULL)
   1420 		return error;
   1421 
   1422 	len = strlen(addr);
   1423 	if (len < 11 || len > 17)
   1424 		return EINVAL;
   1425 
   1426 	/* Commit change */
   1427 	if (ether_aton_r(enaddr, sizeof(enaddr), addr) != 0)
   1428 		return EINVAL;
   1429 	if_set_sadl(ifp, enaddr, ETHER_ADDR_LEN, false);
   1430 	return error;
   1431 }
   1432 
   1433 /*
   1434  * Module infrastructure
   1435  */
   1436 #include "if_module.h"
   1437 
   1438 IF_MODULE(MODULE_CLASS_DRIVER, tap, "")
   1439