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