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