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