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