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