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