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