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