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