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