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