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