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